2012-04-14 71 views
3

这里是一块我的代码:宽框布局

pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); 

JPanel a = new JPanel(); 
a.setAlignmentX(Component.CENTER_ALIGNMENT); 
a.setPreferredSize(new Dimension(100, 100)); 
a.setBorder(BorderFactory.createTitledBorder("aa")); 
JPanel b = new JPanel(); 
b.setAlignmentX(Component.CENTER_ALIGNMENT); 
b.setPreferredSize(new Dimension(50, 50)); 
b.setBorder(BorderFactory.createTitledBorder("bb")); 
pane.add(a); 
pane.add(b); 

问题是与第二面板的宽度,你可以在图片看到:

enter image description here怎样才能解决这个问题?

因为在流式布局看起来我想: enter image description here

回答

7

正如前面提到的,BoxLayout的关注组件的 请求最小,首选和最大大小。当你 微调布局,你可能需要调整这些sizes.¹

import java.awt.Component; 
import java.awt.Dimension; 
import javax.swing.BorderFactory; 
import javax.swing.BoxLayout; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class BoxLayoutDemo { 
    private static void createAndShowGUI(){ 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS)); 

     JPanel a = new JPanel(); 
     a.setAlignmentX(Component.CENTER_ALIGNMENT); 
     a.setPreferredSize(new Dimension(100, 100)); 
     a.setMaximumSize(new Dimension(100, 100)); // set max = pref 
     a.setBorder(BorderFactory.createTitledBorder("aa")); 
     JPanel b = new JPanel(); 
     b.setAlignmentX(Component.CENTER_ALIGNMENT); 
     b.setPreferredSize(new Dimension(50, 50)); 
     b.setMaximumSize(new Dimension(50, 50)); // set max = pref 
     b.setBorder(BorderFactory.createTitledBorder("bb")); 

     frame.getContentPane().add(a); 
     frame.getContentPane().add(b); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      @Override 
      public void run() { 
       createAndShowGUI();    
      } 
     }); 
    } 
} 

enter image description here

¹How to Use BoxLayout: Specifying Component Sizes

+0

thx很多工作 – hudi 2012-04-15 00:31:52