JavaFX tableview resize to fit window

后端 未结 2 1600
终归单人心
终归单人心 2021-02-19 03:24

I am just trying out JavaFX and am forcing my way into it because it is suppose to be the future. I am trying to create a table with 4 columns. The columns AND THE TABLE shoul

2条回答
  •  伪装坚强ぢ
    2021-02-19 04:12

    How Resizable Layout Works

    The size of resizable items in JavaFX is managed by the layout managers in which the items are placed.

    What you need to do

    For your particular issue, you need to set the GridPane sizing constraints to manage the TableView that you placed in the grid.

    See the GridPane.hgrow and GridPane.vgrow constraints I added on the TableView:

    
    

    FXML just reflects the Java API, so you could also do the same in Java source as well; i.e. GridPane.setHGrow(node, priority). Though, if you are using FXML for your layout, defining the layout constraints in FXML is recommended.

    grid

    Refactored Sample

    I loaded your FXML up in Scene Builder 2 and set the appropriate constraints and it appears to resize automatically fine when I use the preview functionality of Scene Builder.

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
      
        
          
            
              
                
                
              
            
            
              
                
                
                
              
            
          
        
      
      

    Some Advice

    You are placing the TableView inside a GridPane. Using a GridPane in your case is a little strange as the GridPane you only place one node in the GridPane. Just placing the TableView directly in the center of your BorderPane or using a simpler layout parent such as a StackPane would have worked just fine. But perhaps this is just some cut down version of a more complex UI, so perhaps that is why you have used a GridPane.

    Further Reading

    If you have time, read up on layout in JavaFX in the Node, Pane, Group and GridPane javadoc and try this little layout bounds demo too.

    Additional Questions for Comments

    mention a StackPane would work, but StackPanes don't seem to have Hgrow and Vgrow?

    StackPanes don't need a Hgrow or Vgrow constraints. Those constraints set Priorities, which are defined as:

    Enumeration used to determine the grow (or shrink) priority of a given node's layout area when its region has more (or less) space available and multiple nodes are competing for that space.

    With a StackPane, all children are layered on top of each other, they don't compete for space, so such growth priority settings for child nodes are not applicable.

提交回复
热议问题