I am trying to construct the following resizeable JPanel:
+-----------------------+
| |
| |
| |
| |
| |
| JScrollPane |
| (containing a |
| JTable) |
| |
| |
| |
| |
| |
+-----------+-----------+
| button1 | b2 |
+-----------+-----------+
I want to button1 and b2 to always be the same width, meaning that when the whole component is resized horizontally, both buttons should gain or lose the same width. There should be no space between the buttons themselves nor between the buttons and the panel’s border. That is, the buttons should always take up all available horizontal space. Note that the text on the buttons is of different length.
When the component is resized vertically, I want the JScrollPane to gain the new height, while the row with the buttons should always remain the same height (essentially button1.getPreferedSize().getHeight()).
I have tried a whole bunch of different LayoutManagers. The closest I got was to put the two buttons in a new JPanel and setting the LayoutManger of that panel to new GridLayout(0,2). That at least maintained a uniform width for both buttons and filled out all horizontal space. However, they still changed their height when the panel was resized vertically.
With other LayoutManagers such as GroupLayout I was able to maintain the same width by linking the buttons (groupLayout.linkSize(button1, b2)), but unable to get them to fill the whole horizontal space.
Whats the best way to achieve this and what LayoutManager should be used?
I would highly suggest checking out MigLayout. It’s a very flexible and easy to use layoutmanager.
If you don’t want to use that, I would suggest making a JPanel with a BorderLayout and put the scrollpane in the center of the borderlayout. Then, make another JPanel with a GridLayout that’s 1 row and 2 columns, and add both of the buttons to that. Then, add that panel to the south region of the JPanel with the borderlayout.
The code would look something like this: