java - 如何让JButton垂直填充BoxLayout?

标签 java swing jbutton layout-manager boxlayout

用图解释最简单,就到这里吧。这是它现在的样子:

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 的大小相同,并且都一直向左?

最佳答案

问题是 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...

enter image description here

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

关于java - 如何让JButton垂直填充BoxLayout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25302859/

相关文章:

java - 使用 JComponents 的表单中的监听器

java - java聊天服务器中的连接池

java - 如何检查index+1是否没有超出债券范围?

java - 在 JavaFX 中设置按钮操作时出现 "Cannot find symbol constructor, EventHandler does not take parameters"

java - 从 SurfaceView 和 Canvas 到 libGDX

Java JFrame 操作执行

带 keyListener 的 Java 键输入将不起作用。我不知道我写错了什么

java - 使用 JButton ActionListener 刷新 jFrame

java - jButton 在更改文本标签时调整大小

Java Swing JFrame 布局