我有一个自定义 ListCellRenderer 并且想使用默认的 Nimbus 选择背景颜色。我可以通过以下方式查找颜色:
Color selectionBackground = UIManager.getColor("nimbusSelectionBackground");
如果我打印它,它的值与Nimbus 默认颜色相同。但是当我在 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);
}
}