我有一个自定义的 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 不会“抗拒”设置颜色。它错误地假设您没有覆盖默认值,因为 UIManager.getColor() 返回 ColorUIResource 的实例。
ColorUIResource 只是实现 UIResource 标记接口(interface)的 Color。根据 Javadoc,L&F“使用此接口(interface)来决定属性值是否已被覆盖”。 Nimbus 检查背景颜色,注意到您没有覆盖它,然后回退到您不期望的一些内部行为。
关于java - 如何在 UIManager 中使用默认的 Nimbus 颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7353618/