I am trying to use the table view to render / edit the \"key = value\" pairs. So the table is supposed to have two columns : \"key\" and \"value\". Key is just a normal stri
Here is a table displaying pairs of Strings and Objects of various types.
A custom cell factory is used to handle display of different object types (by performing an instanceof check on the object's type and rendering the appropriate text or graphic).
import javafx.application.*;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.value.ObservableValue;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import javafx.util.Callback;
import javafx.util.Pair;
public class PairTable extends Application {
public static final String NAME_COLUMN_NAME = "Name";
public static final String VALUE_COLUMN_NAME = "Value";
final TableView> table = new TableView<>();
public static void main(String[] args) throws Exception {
launch(args);
}
public void start(final Stage stage) throws Exception {
// model data
ObservableList> data = FXCollections.observableArrayList(
pair("Song", "Bach Cello Suite 2"),
pair("Image", new Image("http://upload.wikimedia.org/wikipedia/en/9/99/Bach_Seal.jpg")),
pair("Rating", 4),
pair("Classic", true),
pair("Song Data", new byte[]{})
);
table.getItems().setAll(data);
table.setPrefHeight(275);
// table definition
TableColumn, String> nameColumn = new TableColumn<>(NAME_COLUMN_NAME);
nameColumn.setPrefWidth(100);
TableColumn, Object> valueColumn = new TableColumn<>(VALUE_COLUMN_NAME);
valueColumn.setSortable(false);
valueColumn.setPrefWidth(150);
nameColumn.setCellValueFactory(new PairKeyFactory());
valueColumn.setCellValueFactory(new PairValueFactory());
table.getColumns().setAll(nameColumn, valueColumn);
valueColumn.setCellFactory(new Callback, Object>, TableCell, Object>>() {
@Override
public TableCell, Object> call(TableColumn, Object> column) {
return new PairValueCell();
}
});
// layout the scene.
final StackPane layout = new StackPane();
layout.getChildren().setAll(table);
Scene scene = new Scene(layout);
stage.setScene(scene);
stage.show();
}
private Pair pair(String name, Object value) {
return new Pair<>(name, value);
}
}
class PairKeyFactory implements Callback, String>, ObservableValue> {
@Override
public ObservableValue call(TableColumn.CellDataFeatures, String> data) {
return new ReadOnlyObjectWrapper<>(data.getValue().getKey());
}
}
class PairValueFactory implements Callback, Object>, ObservableValue