【问题标题】:How to get JButton to fill BoxLayout vertically?如何让 JButton 垂直填充 BoxLayout?
【发布时间】:2014-08-14 07:57:36
【问题描述】:

用图片最容易解释,所以就这样吧。这就是它现在的样子:

我正在尝试让所有 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 的大小都相同,并且全部都向左移动?

【问题讨论】:

  • @andrew thompsons 感谢您的编辑。
  • 不能说我是BoxLayout 的特别粉丝,我更喜欢GridBagLayout

标签: java swing jbutton layout-manager boxlayout


【解决方案1】:

问题是BoxLayout 将尊重单个组件的preferredSize,您最好使用为您提供更多控制的布局管理器,例如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 名声望。
  • 我会这样做 :-)
  • 如果一段时间后没有更好的结果并且答案让您满意,请考虑通过单击答案旁边的勾号小轮廓来接受答案...
  • @MadProgrammer 做到了!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-22
  • 1970-01-01
  • 2023-03-09
  • 2022-12-15
相关资源
最近更新 更多