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

多くの点でうまくいきます – hudi

関連する問題