JavaFX 2 Automatic Column Width

前端 未结 8 835
盖世英雄少女心
盖世英雄少女心 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: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
    

提交回复
热议问题