2012-04-14 69 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