Resize JButtons in a BoxLayout

Glenndisimo picture Glenndisimo · Mar 13, 2013 · Viewed 17.7k times · Source

I'm trying to make a simple menu for my game. I have 4 buttons in the center and I want to make them a little bit bigger and center them.

The last part worked but I can't seem to call any of my JButtons and do a .setSize / .setPreferedSize(new Dimension()) on it.

public class mainMenu extends JFrame {
private JButton start, highscore, help, stoppen;


public mainMenu() {
    super("Master Mind");
    maakComponenten();
    maakLayout();
    toonFrame();
}

private void maakComponenten() {
    start = new JButton("Start");
    start.setBackground(Color.gray);
    highscore = new JButton("Higscores");
    help = new JButton("Help");
    stoppen = new JButton("Stoppen");
}

private void maakLayout() {
    JPanel hoofdmenu = new JPanel();
    hoofdmenu.setLayout(new BoxLayout(hoofdmenu, BoxLayout.Y_AXIS ));
    hoofdmenu.add(start);
    start.setAlignmentX(CENTER_ALIGNMENT);
    hoofdmenu.add(highscore);
    highscore.setAlignmentX(CENTER_ALIGNMENT);
    hoofdmenu.add(help);
    help.setAlignmentX(CENTER_ALIGNMENT);
    hoofdmenu.add(stoppen);
    stoppen.setAlignmentX(CENTER_ALIGNMENT);
    super.add(hoofdmenu);
}

private void toonFrame() {
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    setVisible(true);
    setSize(500,500);

}

public static void main(String[] args) {
    new mainMenu();
}
}

Answer

Java42 picture Java42 · Mar 13, 2013

As an example, to change the size of the "Start" button,

change :

    start1 = new JButton("Start");

to

    start1 = new JButton("Start") {
        {
            setSize(150, 75);
            setMaximumSize(getSize());
        }
    };