如何使JButton在纵向上填充BoxLayout?

3

最好通过图片来解释,因此我将用图片来说明。现在的样子如下:

image

我希望所有的JButton都是相同的大小,即在垂直方向上完全填满BoxLayout。

这是我的代码:

public class TestarBara extends JFrame implements ActionListener{

JButton heyy;

public static void main(String[] args){
    new TestarBara();
}
    JPanel panel = new JPanel();
    JPanel panel2 = new JPanel();

    public TestarBara(){
    super("knapparnshit");
    panel.setLayout(new GridLayout(3,3,2,2));

    for(int x=1; x < 10; x++){
        String y = Integer.toString(x);
        JButton button = new JButton(y);
        button.addActionListener(this);
        panel.add(button);
    }
    add(panel, BorderLayout.CENTER);

    JButton b1 = new JButton("this");
    JButton b2 = new JButton("does");
    JButton b3 = new JButton("not");
    JButton b4 = new JButton("work");

    panel2.setLayout(new BoxLayout(panel2, BoxLayout.PAGE_AXIS));
    panel2.add(b1);
    panel2.add(Box.createRigidArea(new Dimension(0,4)));
    panel2.add(b2);
    panel2.add(Box.createRigidArea(new Dimension(0,4)));
    panel2.add(b3);
    panel2.add(Box.createRigidArea(new Dimension(0,4)));
    panel2.add(b4);
    panel2.setBorder(BorderFactory.createBevelBorder(1));
    add(panel2, BorderLayout.WEST);

    Dimension dim = panel2.getPreferredSize();
    b1.setPreferredSize(dim);
    b2.setPreferredSize(dim);
    b3.setPreferredSize(dim);
    b4.setPreferredSize(dim);

    setResizable(true);
    setSize(300,300);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

    @Override
public void actionPerformed(ActionEvent e) {

        Object button = e.getSource();
    if(button instanceof JButton){
    ((JButton) button).setEnabled(false);   
    ((JButton) button).setText("dead");
    Toolkit.getDefaultToolkit().beep();

    }

}
}

我需要怎么做才能让所有的JButton都是相同的大小,并且它们全部靠在最左边?

1
@andrew thompsons 谢谢您的编辑。 - CJR
我不能说我特别喜欢BoxLayout,我更喜欢GridBagLayout - MadProgrammer
1个回答

5
问题在于BoxLayout会遵循各个组件的preferredSize,你最好使用提供更多控制的布局管理器,比如GridBagLayout...

GridBagLayout

panel2.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.insets = new Insets(0, 0, 4, 0);
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
panel2.add(b1, gbc);
panel2.add(b2, gbc);
panel2.add(b3, gbc);
gbc.insets = new Insets(0, 0, 0, 0);
panel2.add(b4, gbc);

或者GridLayout...。

插入图像描述

panel2.setLayout(new GridLayout(0, 1, 0, 4));
panel2.add(b1);
panel2.add(b2);
panel2.add(b3);
panel2.add(b4);

谢谢,这回答了我的问题。很抱歉,我不能给你点赞,因为我没有15个声望值。 - CJR
我会代替你完成 :-) - Nabin
如果一段时间内没有更好的答案出现,并且这个答案已经满足了您的需求,请考虑通过点击答案旁边的小勾勾来接受该答案。 - MadProgrammer
@MadProgrammer 做完了!谢谢。 - CJR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接