Hello JavaFX 2! - A TableView Component 📎
import javafx.application.Application;
import javafx.application.Launcher;
import javafx.collections.FXCollections;
import javafx.collections.Sequence;
import javafx.scene.Group;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.table.TableColumn;
import javafx.scene.control.table.TableView;
import javafx.scene.control.table.model.SequenceTableModel;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start() {
Stage stage = new Stage();
stage.setTitle("Hello Table");
final Group root = new Group();
Scene scene = new Scene(root);
stage.setScene(scene);
Sequence children = root.getChildren();
children.add(getTableView());
stage.setVisible(true);
}
//TableView is a node...
public static Node getTableView() {
Sequence data = fetchDataFromServer();
TableView tableView = new TableView();
SequenceTableModel tableModel = new SequenceTableModel(data);
tableView.setModel(tableModel);
TableColumn[] columns = buildColumns(data);
tableView.getColumns().addAll(columns);
return tableView;
}
//sequence is an Observable java.util.List. It could come directly from e.g. JPA EntityManager.
public static Sequence fetchDataFromServer() {
return FXCollections.sequence(
new Person("Duke", "Java"),
new Person("DukeFX", "JavaFX"));
}
public static TableColumn[] buildColumns(final Sequence data) {
TableColumn firstNameCol = new TableColumn();
firstNameCol.setText("First");
firstNameCol.setGetCellData(new TableColumn.GetCellData() {
@Override
public Object get(long row, int col) {
return data.get((int) row).getFirstName();
}
});
TableColumn lastNameCol = new TableColumn();
lastNameCol.setText("Last");
lastNameCol.setGetCellData(new TableColumn.GetCellData() {
@Override
public Object get(long row, int col) {
return data.get((int) row).getLastName();
}
});
return new TableColumn[]{firstNameCol, lastNameCol};
}
public static void main(String[] args) {
Launcher.launch(Main.class, args);
}
}
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
//with getters.
}
A similar example comes with JavaFX 2 already. I just decomposed the origin example in several methods to see what happens behind the scenes.Java FX 2 application can be compiled having jfxrt.jar in the classpath and launched like any other Java application:
java -cp javafx-sdk2.0-ea/rt/jfxrt.jar com.abien.table.Main
Even in the case of the preview the startup performance is <1 sec and significantly faster, than 1.X version.
This post is based on Java FX 2 Early Access - the API and runtime can change any time.
Sees official JavaFX roadmap for more details.