繁体   English   中英

如何使JButton垂直填充BoxLayout?

[英]How to get JButton to fill BoxLayout vertically?

用图片解释是最容易的,所以就到这里了。 现在是这样的:

图片

我正在尝试使所有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 ...

在此处输入图片说明

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM