0

I have made a JButton:

JButton button = new JButton("Button");

Then added it to a JPanel:

panel.add(button, BorderLayout.CENTER);

Photo of the Button:

JButton

I have noticed 2 different types of JButtons:

thin thick

I like the button titled "OK", is there any way I can set this as the preferred style of the button? Or if this can not be done, is there a way to make a panel with a fixed height, and add it to the center of another panel?

Thanks.

Jake Chasan
  • 6,290
  • 9
  • 44
  • 90

4 Answers4

1

Overrride getPreferredSize() method but I never suggest you to use it. It's required only in case of custom painting in AWT and Swing.

JButton btn = new JButton(){
    @Override
    public Dimension getPreferredSize(){
        return new Dimension(40, 40);
    }
};
Braj
  • 46,415
  • 5
  • 60
  • 76
  • Beware of this kind of [pitfall](http://stackoverflow.com/a/12532237/230513) when substituting an arbitrary size for the UI delegate's preferred size. – trashgod May 25 '14 at 16:50
1
  1. You could just set the margins of the button, and let the layout manager determine the preferred size for you.

    button.setMargin(new Insets(0, 30, 0, 30));
                        // top, left, bottom, right
    
  2. Make sure the container you add the button to, has a layout manager that respects preferred sizes of its components. See here to see which layouts will and wont respect the preferred sizes

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
1

Use a layout that respects the preferred size calculated by the button's UI delegate. In this example, each button is added to a panel having FlowLayout; the button retains its preferred size. In contrast, this example adds buttons to a GridLayout; resize the enclosing container to see the effect. A helpful guide is cited here.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
0

This is not a style. You have to define size of JButton.

JButton btn = new JButton(String.valueOf(i));
btn.setPreferredSize(new Dimension(40, 40));
unknown
  • 4,859
  • 10
  • 44
  • 62
  • 1
    Don't use `setPreferredSize()` method. – Braj May 25 '14 at 15:24
  • 1
    Read it here [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – Braj May 25 '14 at 15:25