4

ここに私のコードの一部があります:

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);

問題は、画像でわかるように、2 番目のパネルの幅にあります。

ここに画像の説明を入力どうすれば修正できますか?

フローレイアウトでは、私が望むように見えるからです: ここに画像の説明を入力

4

1 に答える 1

8

前述のように、BoxLayout は、コンポーネントの要求された最小サイズ、優先サイズ、および最大サイズに注意を払います。レイアウトを微調整している間に、これらのサイズの調整が必要になる場合があります。¹

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();             
            }
        });
    }
}

ここに画像の説明を入力

¹ BoxLayout の使用方法: コンポーネント サイズの指定

于 2012-04-15T00:17:12.450 に答える