3

I would like to reduce the vertical size of a JButton. The following code works fine for K > 1 but I can't seem to reduce the size. Any suggestions?

JButton button = /* ... get button here ... */
Dimension d = button.getPreferredSize();
d.setSize(d.getWidth(), d.getHeight()*K);
button.setPreferredSize(d);

edit: I'm using JavaBuilders + MigLayout. It looks like I have to do button.setMaxSize(d); instead of setPreferredSize(), not sure why.

Jason S
  • 184,598
  • 164
  • 608
  • 970

3 Answers3

5

A few options:

import java.awt.*;

public class FrameTest {
    public static void main(String[] args) {
        JFrame jf = new JFrame("Demo");
        jf.getContentPane().setLayout(new FlowLayout());

        // Ordinary button
        jf.add(new JButton("button 1"));

        // Smaller font
        jf.add(new JButton("button 2") {{ setFont(getFont().deriveFont(7f)); }});

        // Similar to your suggestion:
        jf.add(new JButton("button 3") {{
            Dimension d = getPreferredSize();
            d.setSize(d.getWidth(), d.getHeight()*.5);
            setPreferredSize(d);
        }});

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.pack();
        jf.setVisible(true);
    }
}

Produces

enter image description here

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • 1
    Caveat: [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing](http://stackoverflow.com/q/7229226/230513)? – trashgod Apr 14 '13 at 11:38
5

As an alternative, some L&Fs (e.g. Nimbus, Aqua) support a JComponent.sizeVariant, as discussed in Resizing a Component and Using Client Properties. Several variations are illustrated here.

image

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Any chance of getting one of your lovely Aqua PLAF images for [this answer](https://stackoverflow.com/a/54822330/418556)? I might have asked you to submit an answer, but it's been closed. – Andrew Thompson Feb 22 '19 at 10:32
4

Maybe just play with the Border of the button:

Insets insets = button.getInsets();
insets.top = 0;
insets.bottom = 0;
button.setMargin( insets );
camickr
  • 321,443
  • 19
  • 166
  • 288