Question

I'm trying to get my buttons to fill the width of my panel, this is my code that makes a buttons and a panel and then just adds the button to the panel.

buttonPane = makeButtonPanel();
button = makeButton("Hello"); 
button2 = makeButton("World");
buttonPane.add(button);
buttonPane.add(button2);

private JButton makeButton(String msg){
    JButton button = new JButton(msg);
    button.setAlignmentX(Component.CENTER_ALIGNMENT); 
    return button;
}

private JPanel makeButtonPanel(){
    JPanel btnPanel = new JPanel();
    btnPanel.setLayout(new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
    btnPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    return btnPanel;
}

This is the output I am getting...

enter image description here

Was it helpful?

Solution

How the button fits it's container depends on the layout of the container. If you want it to stretch you could make the button panel have a BorderLayout and add the button to the north position, or use any of the other layout types whose components attempt to try to occupy as much room as they can (BorderLayout with north is just one example).

For multiple buttons stretched widthwise out as much as they can go, place a container in the North position instead of a single button, where that container contains multiple JButtons. That container should probably be a JPanel with a GridLayout, 1 column, as many rows as you have buttons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top