JavaFX 2 Automatic Column Width

前端 未结 8 813
盖世英雄少女心
盖世英雄少女心 2020-11-29 01:09

I have a JavaFX 2 table that is displaying contact details for people, lets imagine there are three columns: first name, last name and email address. When my application sta

相关标签:
8条回答
  • 2020-11-29 01:35

    If your total number of columns are pre-known. You can distribute the column widths among the tableview's width:

    nameCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
    surnameCol.prefWidthProperty().bind(personTable.widthProperty().divide(2)); // w * 1/2
    emailCol.prefWidthProperty().bind(personTable.widthProperty().divide(4)); // w * 1/4
    

    In this code, the width proportions of columns are kept in sync when the tableview is resized, so you don't need to do it manually. Also the surnameCol takes the half space of the tableview's width.

    0 讨论(0)
  • 2020-11-29 01:39

    Also, a very simple trick based on an AnchorPane will be a good solution.

    We gonna wrap the TableView into a AnchorPane but also we gonna anchor the left and right side of the TableView like this:

    AnchorPane wrapper = new AnchorPane();
    
    AnchorPane.setRightAnchor(table, 10.0);
    AnchorPane.setLeftAnchor(table, 10.0);
    wrapper.getChildren().add(table);
    

    This simple code will stretch the TableView in both directions (right and left) also, it will adjust whenever the scrollbar is added.

    You can get an idea of how this works watching this animated gif.

    Now you can resize the columns, adding these lines:

    fnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
    lnColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 40 ); // 40% width
    emColumn.setMaxWidth( 1f * Integer.MAX_VALUE * 30 ); // 30% width
    
    0 讨论(0)
提交回复
热议问题