Reputation: 17
i have the following code to create a custom Table. but in the output it shows many rows which doesn't contain any values. i would like to display just two rows and 1 columns. is there any solution for this, else Javafx produces this by default. Is there any alternate way to create a table. May be using a GridPaneBuilder
private TableView<Person> table = new TableView<Person>();
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("Jacob"),
new Person("Isabella")
);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group());
stage.setTitle("Table View Sample");
stage.setWidth(450);
stage.setHeight(500);
final Label label = new Label("Address Book");
label.setFont(new Font("Arial", 20));
table.setEditable(true);
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(
new PropertyValueFactory<Person, String>("firstName"));
table.setItems(data);
table.getColumns().addAll(firstNameCol);
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(label, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
}
public static class Person {
private final SimpleStringProperty firstName;
private Person(String fName) {
this.firstName = new SimpleStringProperty(fName);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
}
Upvotes: 0
Views: 467
Reputation: 1075
You can set that the columns take as much space as possible by:
myTable.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
I don't know if there is an easy way to set height of the table according to the amount of rows, but you could set the maxHeight of the table accoring to the amount of rows multiplied by the rowHeight:
myTable.setMaxHeight(countOfRows * rowHeight + headerHeight);
And a more flexible way would be to use JavaFX binding, so when you add or delete a row the height of the table changes.
Upvotes: 0