Search code examples
javaswingjbuttonlayout-managerboxlayout

How to get JButton to fill BoxLayout vertically?


It's easiest to explain with a picture, so here it goes. This is how it looks right now:

image

I am trying to get all JButtons to to be same size, i.e to fill out the BoxLayout completely vertically.

Here is my code:

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

    }

}
}

What do I need to do so the JButtons all are the same size, and all of them going all the way to the left?


Solution

  • The problem is BoxLayout will honour the preferredSize of the individual components, you'd be better off with a layout manager that provided you with more control, like GridBagLayout, for example...

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

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