JPanel size by inner components

前端 未结 8 2202
夕颜
夕颜 2021-02-18 13:48

Is it possible to tell JPanel to set its size to fit all components that it contains? Something like pack() for JFrame.

edit: The trick with preferredSize d

相关标签:
8条回答
  • 2021-02-18 14:41

    I would try:

    panel.revalidate();
    panel.repaint();
    

    This will not necessarily set the panel to its preferred size, that is more dependent on what the layout manager decides to use.

    This is useful in cases where you have added/removed components from a panel that is currently displayed and visible.

    Update: Based on your screenshot I can say the following: 1) Consider programatically changing the divider location. 2) Consider programatically resizing the window itself horizontally since it seems to be a little tight to show both sides of the split pane. Or both. You can set the divider location by doing

    splitPane.setDividerLocation(newSize);
    

    Keep in mind that there are two overloaded methods for this, one taking a float one taking an int. The float does a percentage of the size while the int is the size in pixels. The size is for the left hand panel (or top panel for that orientation). I would consider possibly changing the divider location based on the preferred width of the panels.

    0 讨论(0)
  • 2021-02-18 14:53

    maybe you can do something like that by removing from your panel

    setResizable(false);

    0 讨论(0)
提交回复
热议问题