Setting size of JPanel using MiGLayout
Question
I'm using the MiGLayout to create several different JPanels, however I'm having a problem resizing one of them. Below is a diagram showing what I want to achieve:
-------------------------------------------------------
| |
| Panel 1 |
| |
-------------------------------------------------------
--------------------------- ---------------------------
| | | |
| Panel 2 | | Panel 3 |
| | | |
--------------------------- ---------------------------
The key thing I want to achieve is to make Panel 1 spread across the two other panels. I seem to have achieved this layout, however I've got an issue such that the border isn't showing up for Panel 1 as shown in my diagram. I have tried using the setSize
method but it didn't seem to work.
Here is the code I'm using to create the panels (please note I haven't included the widgets inside the panel):
// Create Panel 1
JPanel panelOne = new JPanel();
panelone.setSize(600, 50);
panelOne.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panelOne.setLayout(new MigLayout());
// Create Panel 2
JPanel panelTwo = new JPanel();
panelTwo.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panelTwo.setLayout(new MigLayout());
// Create Panel 3
JPanel panelThree = new JPanel();
panelThree.setBorder(BorderFactory.createTitledBorder("Panel 3"));
panelThree.setLayout(new MigLayout());
// Add the panels to the main frame
mainFrame.add(panelOne, "span, wrap, align center");
mainFrame.add.add(panelTwo);
mainFrame.add.add(panelThree);
Please can someone suggest a way to get the border to be shown as in my diagram?
Solution
Try this:
mainFrame.getContentPane().setLayout(new MigLayout());
getContentPane().add(panelTwo);
getContentPane().add(panelThree, "wrap"); // Wrap to next row
getContentPane().add(panelOne, "dock north");
Also, ensure you are adding your GUI elements to the main frame's content pane not to the frame itself.
EDIT From the comments below:
You can also use new CC.wrap()
or new CC.dockNorth()
Thanks to @Andrew Thompson and @Howard for the tip :)
OTHER TIPS
panelone.setSize(600, 50); // from original code
I've never used that layout, but layouts in general are more likely to respect (enforce) the preferred size than the size.