How to increase the width of table header and table cell in JavaFX Tableview

534 views Asked by At

How to increase the spacing of table header and table cell in JavaFX.

I have created my table like below:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TableViewExample extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  @Override
  public void start(Stage primaryStage) {

    TableView tableView = new TableView();

    TableColumn<Person, String> column1 = new TableColumn<>("First Name");
    column1.setCellValueFactory(new PropertyValueFactory<>("firstName"));


    TableColumn<Person, String> column2 = new TableColumn<>("Last Name");
    column2.setCellValueFactory(new PropertyValueFactory<>("lastName"));


    tableView.getColumns().add(column1);
    tableView.getColumns().add(column2);

    tableView.getItems().add(new Person("John", "Doe"));
    tableView.getItems().add(new Person("Jane", "Deer"));

    VBox vbox = new VBox(tableView);

    Scene scene = new Scene(vbox);

    primaryStage.setScene(scene);

    primaryStage.show();
  }

}
2

There are 2 answers

0
Renis1235 On BEST ANSWER

If you want to change the width of the columns then use:

column1.setMinWidth(100);

If you want to increase the spacing between the header and the data rows. then you could add some empty rows like this:

tableView.getItems().add(new Person("", ""));
0
Sai Dandem On

I agree with what @sorifiend mentioned in the comment. You need to be a bit more elaborative with the question about what kind of spacing you are seeking for.

If you are asking for how to enlarge the cell/header, one way is you can do it by changing the css values.

Add your css stylesheet as below:

scene.getStylesheets().add(getClass().getResource("table.css").toExternalForm());

And include the below css in the table.css file:

.table-cell, .column-header.table-column .label{
  -fx-padding:10px;
}

enter image description here