Reputation: 17923
I am trying to create an incredibly simple JavaFX TableView: 1 column of Strings. I have an Array which I would like to visualize:
String[] acronyms = {"Foo", "Bar"};
The documentation presumes some datatype to fill multiple columns (e.g. Person, Book, etc.). I am going much more "hello world" than that: just displaying an Array of Strings.
Using scene builder I created an fxml file with the table & column:
<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>
I then "wire" these elements inside of my controller:
@FXML private TableView<String> clientAcronymTable;
@FXML private TableColumn<ObservableList<String>, String> clientAcronymColumn;
And inside my Initializable::initialize
method I have:
clientAcronymTable.setItems(FXCollections.observableList(acronyms));
However, none of the Strings appear in the GUI. I know something is happening because there are visible row lines displayed in the column, but they're all empty.
There are of course similar questions which don't really apply:
So, my questions are:
How do I make the Strings in my Array visible inside of the TableView?
How do I make the single column editable so the user can add more Strings?
Thank you in advance for your consideration and response.
Upvotes: 2
Views: 2835
Reputation: 209225
First, you have the wrong type for your TableColumn
. Since each row contains a String
(not an ObservableList<String>
), you need
@FXML private TableColumn<String, String> clientAcronymColumn;
And then you need a cellValueFactory
, which tells each cell in the column how to get the value it displays from the row:
clientAcronymColumn.setCellValueFactory(cellData ->
new ReadOnlyStringWrapper(cellData.getValue()));
As for adding more strings, you would typically have an external text field for the user to provide more:
// 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();
});
Upvotes: 5