I have browsed around and haven't found a solution that specifically tailors to my situation. I have a panel that I display in a dialog box:
//create dialog panel
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(headerPanel);
panel.add(type1Panel);
panel.add(type2Panel);
panel.add(type3Panel);
panel.add(type4Panel);
panel.add(type5Panel);
panel.add(type6Panel);
int result = JOptionPane.showConfirmDialog(null, panel, "Please enter values.", JOptionPane.OK_CANCEL_OPTION);
The size of the last two panels, type5 & type6, are of equal size so they look fine. However, the header and first 4 panels are of different sizes and I would like them all to be left aligned. As of yet I haven't found a good solution as how to fix this.
Question is, how can I left align the first 5 panels, but not last 2? If not how can I left align them all? The setalignmentx() isn't available for panels. I've tried using GridLayout, but then the width of the gui's main window is rather large and doesn't fit nicely onto the screen, hence the BoxLayout along Y axis.Thanks for any help or suggestions.
Create a horizontal javax.swing.Box object to contain each typenPanel object. Using horizontal struts and glue you can do whatever you want:
For simplicity, write a helper method to do this for you:
Then:
etc.... You can get fancier with each line, adding components, glue, and struts. I've had great luck deeply nesting vertical and horizontal boxes, and writing helper methods when I want to do the same layout in a box more than once. There's no limits to what you can do, mixing components, struts, and glue as necessary.
I'm sure there's a better way to do all this, but I haven't found it yet. And the dynamic resizing lets a user with short bits of text use a small window and a user with lots of text resize it so it all fits.
Here is an example that will left align all the JPanels added to the panel used as a container.
You should use
setAlignmentX
on the panels because it is available forJPanel
. The methodssetAlignmentX
andsetAlignmentY
are found inJComponent
, whichJPanel
extends. It works...I've got code that uses those methods to align JPanels in aBoxLayout
.Ok, fine, edit your question while I'm answering it :)
Instead of using a JPanel try using a
Box
. I've found theBox
class to be very useful as a container. From the API:If you haven't seen it yet, the tutorial How to Use BoxLayout is very helpful.