[英]How to get rid of the space around buttons in Nimbus LAF?
我需要將一些JButton放在一個很小的地方,問題是Nimbus LAF會在它們周圍自動放置一些空間,結果,這些按鈕看上去比實際的要小。
在下面的示例程序中,我使用水平和垂直間隙為0的FlowLayout,並且我希望按鈕緊緊地坐着,並且它們之間沒有任何間隙。 如果我注釋掉Nimbus LAF的設置,它們的行為將達到預期。
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;
}
}
如您所見,在createButton中注釋掉的代碼中,我嘗試了很多事情,但是它們並沒有消除按鈕周圍的空間。
編輯 :基於評論中的討論,似乎不可能刪除按鈕的矩形邊緣和繪制的圓角矩形輪廓之間的空間。 Nimbus將這兩個像素保留為“焦點突出顯示”,並且可能無法更改,除非重新實現許多Nimbus功能。
因此,我接受了guleryuz的trick倆:如果按鈕位於重疊位置和負位置,則它們看起來可能更大。 在實踐中,這個想法似乎可行,但它不是一個很干凈的解決方案,因此,如果您知道更好的(且合理容易實施的)解決方案,請隨時回答...
請注意,如果您設置背景色,然后調用setOpaque(true),則可以看到按鈕彼此相對。 這就是Nimbus繪制按鈕的方式。 我認為您無法更改按鈕的矩形邊緣和繪制的圓角矩形輪廓之間的空間。
如果空間比較寶貴,則可以通過取消注釋UIDefaults行並修改contentMargins屬性來縮小大小(但不要使用0,0,0,0,而是使用2,8,2,8)。
方法1:
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, -4, 0));
方法2:
JPanel p = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
p.add(createButton("aa", 1));
p.add(createButton("bb", 2));
p.add(createButton("cc", 3));
在createButton方法中進行了一些修改
private static JButton createButton(String text, final int s) {
JButton b = new JButton(text){
@Override
public void setLocation(int x, int y) {
super.setLocation(x-(s*4), y);
}
};
return b;
}
方法3
JPanel p = new JPanel(new MigLayout("ins 0, gap -5","[][][]"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.