'Setting JButton size

I'm trying to resize JButton to always be a certain size. I have 9 of these buttons. I understand from the API that it JButton inherits setSize(int a, int b) and setSize(Dimension d). I opted to use the second though I tried the other and it didn't fix my problem. Here is the code.

// setup buttons 
        reset = new JButton("Reset");
        square1 = new JButton();
        square2 = new JButton();
        square3 = new JButton();
        square4 = new JButton();
        square5 = new JButton();
        square6 = new JButton();
        square7 = new JButton();
        square8 = new JButton();
        square9 = new JButton();

    //set button size
    Dimension d = new Dimension(100,100);
    square1.setSize(d);
    square2.setSize(d);
    square3.setSize(d);
    square4.setSize(d);
    square5.setSize(d);
    square6.setSize(d);
    square7.setSize(d);
    square8.setSize(d);
    square9.setSize(d);

I've tried several diferent dimensions and none of them make any difference. What am I missing? I'm using a gridLayout(3,3,5,5) for the the JPanel that the buttons are on. The dimensions for the JFrame are (400,425). Thanks for any help!



Solution 1:[1]

Try using square1.setPreferredSize(d) instead of setSize(d).

Solution 2:[2]

You can use setBounds() method as:

Frame f=new Frame();
f.setLayout(null);
Button b=new Button("Dummy");
//setBounds() methods accepts 4 
// integer parameters
/* 1. Location on x axis
2. Location on y axis
3. Width
4. Height */
b.setBounds(20,30,50,30);
f.add(b);

Thats how you set size for a button There are more ways to specify size but i use this one Hope this will help you....

Solution 3:[3]

The setPreferredSize(Dimension d) should work. Your last block of code will look like this:

square1.setPreferredSize(d);
square2.setPreferredSize(d);
square3.setPreferredSize(d);
square4.setPreferredSize(d);
square5.setPreferredSize(d);
square6.setPreferredSize(d);
square7.setPreferredSize(d);
square8.setPreferredSize(d);
square9.setPreferredSize(d);

The rest of your code is the same.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 YCF_L
Solution 2 Priyank
Solution 3 kautom