I need to put some JButtons in a very small place, and the problem is that the Nimbus LAF automatically puts some space around them, and as a result the buttons look smaller than they really are.
In the following example program I use a FlowLayout with 0 horizontal and vertical gaps, and I expected the buttons to sit tightly without any space between them. If I comment out the setting of the Nimbus LAF, they behave as expected.
import javax.swing.*;
import java.awt.FlowLayout;
public class NimbusSpace {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
buildGUI();
}
});
}
private static void buildGUI() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
p.add(createButton("aa"));
p.add(createButton("bb"));
p.add(createButton("cc"));
f.add(p);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static JButton createButton(String text) {
JButton b = new JButton(text);
// b.setBorder(null);
// b.setBorderPainted(false);
// b.setMargin(new Insets(0,0,0,0));
// b.putClientProperty("JComponent.sizeVariant", "large");
// b.putClientProperty("JComponent.sizeVariant", "mini");
// UIDefaults def = new UIDefaults();
// def.put("Button.contentMargins", new Insets(0,0,0,0));
// b.putClientProperty("Nimbus.Overrides", def);
return b;
}
}
As you can see in the commented out code in createButton, I tried quite a few things, but they didn't remove the space around the buttons.
EDIT: Based on the discussions in the comments, it seems that it is not possible to remove the space between the rectangular edges of the button and the drawn rounded-rectangle outline. Nimbus reserves these two pixels for the "focus highlight", and probably this cannot be changed without re-implementing a lot of Nimbus functionality.
So I accepted guleryuz's trick: if the buttons are positioned at overlapping and negative positions, they can look bigger. In practice this idea seems to work, but it is not a very clean solution, so if you know a better (and reasonably easily implemented) solution, don't hesitate to answer...