Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

swing - java BoxLayout panel's alignment

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example that will left align all the JPanels added to the panel used as a container.

   JPanel a = new JPanel();
   JPanel b = new JPanel();
   JPanel c = new JPanel();

   a.setBackground( Color.RED );
   b.setBackground( Color.GREEN  );
   c.setBackground( Color.BLUE );

   a.setMaximumSize( new Dimension(  10, 10) );
   b.setMaximumSize( new Dimension(  50, 10) );

   a.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
   b.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0
   c.setAlignmentX( Component.LEFT_ALIGNMENT );//0.0

   JPanel panel = new JPanel();
   panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
   panel.add(a);
   panel.add(b);
   panel.add(c); 

   int result = JOptionPane.showConfirmDialog(null, panel, "Please enter values.", JOptionPane.OK_CANCEL_OPTION);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...