【发布时间】:2011-11-13 07:04:20
【问题描述】:
我有一个自定义 ListCellRenderer,并希望使用默认的 Nimbus 选择背景颜色。我可以通过以下方式查找颜色:
Color selectionBackground = UIManager.getColor("nimbusSelectionBackground");
如果我打印它,它的值与Nimbus default colors 上的值相同。但是当我在 JPanel 上使用它时,我得到了不同的灰色,如何使用 UIManager 中的颜色?
当我这样做时:
setBackground(Color.RED);
JPanels 背景显示为红色,但当我这样做时:
setBackground(selectionBackground);
不使用了“selectionBackground”颜色,而是使用了灰色。
这是一个例子和截图:
背景应该是:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class PanelColor {
public static void main(String[] args) {
// switch to Nimbus Look And Feel
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (Exception e) { e.printStackTrace(); }
break;
}
}
Color selectionBackground = UIManager.getColor("nimbusSelectionBackground");
JPanel panel = new JPanel(new BorderLayout());
panel.setPreferredSize(new Dimension(300,50));
panel.add(new JLabel(selectionBackground.toString()), BorderLayout.NORTH);
// is not showing the selectionBackground color
panel.setBackground(selectionBackground);
JFrame frame = new JFrame();
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
【问题讨论】:
-
以下问题是否可以帮助您使用 Nimbus - stackoverflow.com/questions/5840599/… ?
-
哇,很奇怪。我检查了代码:返回的颜色是 javax.swing.plaf.ColorUIResource 类型。但我不明白这会如何导致任何问题,因为它是 Color 的子类。 ColorUIResource 的代码没有什么特别之处,没有对 UI 的引用什么的。正如乔伊建议的那样,
selectionBackground = new Color(selectionBackground.getRGB());有效。
标签: java swing colors nimbus uimanager