gpt4 book ai didi

java - *基本* 单个字符串列的 JavaFX TableView

转载 作者:行者123 更新时间:2023-11-29 04:53:32 25 4
gpt4 key购买 nike

我正在尝试创建一个非常简单的 JavaFX TableView:1 列字符串。我有一个我想可视化的数组:

String[] acronyms = {"Foo", "Bar"};

documentation假定一些数据类型来填充多个列(例如人、书等)。我要说的“hello world”远不止于此:只是显示一个字符串数组。

我使用场景生成器创建了一个包含表和列的 fxml 文件:

<TableView fx:id="clientAcronymTable" prefHeight="200.0" prefWidth="200.0">
<columns>
<TableColumn fx:id="clientAcronymColumn" prefWidth="199.0" text="Client Acronyms" />
</columns>
<columnResizePolicy>
<TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
</columnResizePolicy>
</TableView>

然后我将这些元素“连接”到我的 Controller 中:

@FXML private TableView<String> clientAcronymTable;

@FXML private TableColumn<ObservableList<String>, String> clientAcronymColumn;

在我的 Initializable::initialize 方法中,我有:

clientAcronymTable.setItems(FXCollections.observableList(acronyms));

但是,没有任何字符串出现在 GUI 中。我知道发生了什么,因为列中显示了可见的行,但它们都是空的。

当然也有类似的问题并不真正适用:

  1. Related to more than one column, not applicable
  2. Creates acustom Row Class which seems like overkill

所以,我的问题是:

如何使数组中的字符串在 TableView 中可见

如何使单个列可编辑以便用户可以添加更多字符串

提前感谢您的考虑和回复。

最佳答案

首先,您的 TableColumn 类型错误.由于每一行都包含一个 String (不是 ObservableList<String> ),你需要

@FXML private TableColumn<String, String> clientAcronymColumn;

然后你需要一个cellValueFactory ,它告诉列中的每个单元格如何从行中获取它显示的值:

clientAcronymColumn.setCellValueFactory(cellData -> 
new ReadOnlyStringWrapper(cellData.getValue()));

至于添加更多字符串,您通常会有一个外部文本字段供用户提供更多:

// you can of course define the text field in FXML if you prefer...
TextField newAcronymTextField = new TextField();

newAcronymTextField.setOnAction(e -> {
clientAcronymTable.getItems().add(newAcronymTextField.getText());
newAcronymTextField.clear();
});

关于java - *基本* 单个字符串列的 JavaFX TableView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com