我目前正在尝试ListCellRenderer
为JList
. 不幸的是,几乎所有的例子都只是简单地使用DefaultListCellRenderer
as aJLabel
就可以了。但是,我需要一个JPanel
(因为我需要显示更多信息,而不仅仅是一个图标和一行文本)。
现在我遇到了背景颜色的问题,特别是 Nimbus PLAF。似乎我得到的背景颜色list.getBackground()
是白色,但涂成灰色(或蓝灰色)。输出我得到的颜色会产生以下结果:
背景颜色:DerivedColor(color=255,255,255 parent=nimbusLightBackground offsets=0.0,0.0,0.0,0 pColor=255,255,255
但是,可以看出,这不是画出来的。
它显然适用于所选项目。目前,我什至将我放入JPanel
单元格渲染器返回的每个组件都设置为不透明,并使用正确的前景色和背景色——但无济于事。
有什么想法我在这里做错了吗?
ETA:希望运行的示例代码。
public class ParameterListCellRenderer implements ListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
// some values we need
Border border = null;
Color foreground, background;
if (isSelected) {
background = list.getSelectionBackground();
foreground = list.getSelectionForeground();
} else {
background = list.getBackground();
foreground = list.getForeground();
}
if (cellHasFocus) {
if (isSelected) {
border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = UIManager.getBorder("List.focusCellHighlightBorder");
}
} else {
border = UIManager.getBorder("List.cellNoFocusBorder");
}
System.out.println("Background color: " + background.toString());
JPanel outerPanel = new JPanel(new BorderLayout());
setProperties(outerPanel, foreground, background);
outerPanel.setBorder(border);
JLabel nameLabel = new JLabel("Factory name here");
setProperties(nameLabel, foreground, background);
outerPanel.add(nameLabel, BorderLayout.PAGE_START);
Box innerPanel = new Box(BoxLayout.PAGE_AXIS);
setProperties(innerPanel, foreground, background);
innerPanel.setAlignmentX(Box.LEFT_ALIGNMENT);
innerPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
JLabel label = new JLabel("param: value");
label.setFont(label.getFont().deriveFont(
AffineTransform.getScaleInstance(0.95, 0.95)));
setProperties(label, foreground, background);
innerPanel.add(label);
outerPanel.add(innerPanel, BorderLayout.CENTER);
return outerPanel;
}
private void setProperties(JComponent component, Color foreground,
Color background) {
component.setOpaque(true);
component.setForeground(foreground);
component.setBackground(background);
}
}
奇怪的是,如果我这样做
if (isSelected) {
background = new Color(list.getSelectionBackground().getRGB());
foreground = new Color(list.getSelectionForeground().getRGB());
} else {
background = new Color(list.getBackground().getRGB());
foreground = new Color(list.getForeground().getRGB());
}
它神奇地起作用。所以也许我要去那里可能DerivedColor
有nimbusLightBackground
麻烦?