1

I know there are some other questions similar to this but I haven't seen my specific question answered. I want to change the size of a JButton WITHOUT changing the look. For example if I use setPreferredSize, I lose the white background color and rounded corners. I just want to remove the surrounding padding so the button is only slightly bigger then it's label.

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame jFrame = new JFrame("Label");
    jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.insets = new Insets(10, 10, 10, 10);
    JPanel jPanel = new JPanel(new GridBagLayout());

    JButton jButtonUp = new JButton("Upd");
    //jButtonUp.setPreferredSize(new Dimension(30, 20));
    jPanel.add(jButtonUp, gbc);

    gbc.gridy = 1;
    JButton jButtonDn = new JButton("Del");
    //jButtonDn.setPreferredSize(new Dimension(30, 20));
    jPanel.add(jButtonDn, gbc);

    jFrame.add(jPanel);
    jFrame.pack();
    jFrame.setVisible(true);

Using Mac OSX Sierra.

What I have is this: enter image description here

What I get with setPreferredSize is this: enter image description here

What I want is this: enter image description here

John Smith
  • 3,493
  • 3
  • 25
  • 52
  • updated with code – John Smith Sep 20 '17 at 21:34
  • 1
    I can't reproduce your error. Can you show complete code? And make two buttons please so it's easier to compare them. What Look and Feel do you use and what OS and version are you on? – markspace Sep 20 '17 at 21:48
  • Both of these buttons have the same look for me on Windows 10 and Java 8. I'm on the latest update for both. Sorry but it seems it might be Mac specific. (BTW, both buttons are the same size and tiny on my screen. There's a reason why we normally don't set the size of GUI components directly and it's because screen sizes, pixel density and default font sizes differ on each machine. Might be best to not set the size at all.) – markspace Sep 20 '17 at 22:05
  • You updated your code to a full example, but the created button is neither white, nor has round edges when I copy the code in a main method. – Thomas Böhm Sep 20 '17 at 22:06
  • Yes. That's the problem of setPreferredSize. Comment it out. – John Smith Sep 20 '17 at 22:07
  • Did that, still blue with edgy edges. – Thomas Böhm Sep 20 '17 at 22:08
  • Must be mac look and feel is different. – John Smith Sep 20 '17 at 22:14

1 Answers1

0

Check this answer here, Simply do

After the line:

JButton jButtonUp = new JButton("Upd");

Add:

jButtonUp.setBorder(null);
jButtonUp.setMargin(new Insets(0,0,0,0));

Then add the button to the panel:

jPanel.add(jButtonUp, gbc);
Minwu Yu
  • 311
  • 1
  • 6
  • 24