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
  • 5,918
  • 8
  • 40
  • 84

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
  • 45,615
  • 5
  • 55
  • 73
  • 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
  • 197,959
  • 33
  • 457
  • 689
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
  • 200,320
  • 28
  • 229
  • 974
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,521
  • 9
  • 43
  • 58
  • 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