Java – Setting JButton size

awtjavajbuttonjpanelswing

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!

Best Answer

The layout managers usually don't respect the size of a component, so setting size often has little effect. Instead, the layout managers usually respect the preferred sizes of components. Having said this, it's usually better to not try to set the preferredSizes yourself via setPreferredSize(Dimension d) but rather to let the layout managers and the components do this for you. If you must do it yourself, consider extending the component and overriding getPreferredSize() and adding smart code that returns a decent and proper preferredSize Dimension.

For example, please have a look at my code in my answer to a recent question here. In it, I change the size of the JButton's Font to make it larger, but i never set the sizes or preferredSizes of any component, but rather let the components themselves and the container's layout managers do this work for me.

If you don't believe me, please read some of the posts and comments by kleopatra, one of the smartest and most influential Swing coders that I know of, and one of the authors of the SwingX toolkit. For example her answer here.

Related Topic