Java 如何在UIManager中使用默认的Nimbus颜色?

Java 如何在UIManager中使用默认的Nimbus颜色?,java,swing,colors,nimbus,uimanager,Java,Swing,Colors,Nimbus,Uimanager,我有一个自定义ListCellRenderer,希望使用默认的Nimbus选择背景色。我可以使用以下选项查找颜色: Color selectionBackground = UIManager.getColor("nimbusSelectionBackground"); 如果我打印它,它的值与上的值相同。但是,当我在JPanel上使用它时,我会得到不同的灰色,如何使用UIManager提供的颜色 当我这样做时: setBackground(Color.RED); JPanels回退显示为红色,

我有一个自定义ListCellRenderer,希望使用默认的Nimbus选择背景色。我可以使用以下选项查找颜色:

Color selectionBackground = UIManager.getColor("nimbusSelectionBackground");
如果我打印它,它的值与上的值相同。但是,当我在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显然拒绝在其他地方使用它的颜色。不久前我也偶然发现了这一点,当时我最好的解决方案是使用组件(您可以查询)创建一个新的
颜色
,并使用它。当然,即使L&F改变了,你也要坚持使用这种颜色

我知道这就是你从UIManager那里得到的
DerivedColor
的全部要点。不过,我还没有找到更好的解决办法

这同样适用于其他L&F和其他事情。例如,GTK L&F会很乐意为您提供您想要的图标,但它们不会在您自己的控件中绘制。我想部分原因是Swing(a)非常复杂,(b)没有一家L&F公司真正遵守合同,即使是Nimbus,尽管它是最新最酷的一家。

我不认为Nimbus“抵制”设置颜色。它错误地假设您没有重写默认值,因为UIManager.getColor()返回ColorUIResource的实例


ColorUIResource只是一种实现UIResource标记接口的颜色。根据Javadoc,L&Fs“使用此接口来决定属性值是否已被覆盖”。Nimbus检查背景颜色,注意到您没有覆盖它,并依赖于一些您不期望的内部行为。

以下问题是否可能帮助您使用Nimbus-?哇,非常奇怪。我签入了代码:返回的颜色是javax.swing.plaf.ColorUIResource类型。但我不认为这会导致任何问题,因为它是颜色的一个子类。ColorUIResource的代码中没有什么特别之处,也没有对UI或任何东西的引用。正如乔伊所建议的,
selectionBackground=new Color(selectionBackground.getRGB())有效。DerivedColor在哪里定义?你是说?