2

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:

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

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.

1
  • 1
    you should use cellvaluefactory for this Commented Jan 2, 2016 at 20:44

1 Answer 1

5

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();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know what the type of cellData is?
cellData is aTableColumn.CellDataFeatures<String, String>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.