早上好,请您介意帮我确定为什么这个 ListCellRenderer 类没有在组合框单元格上设置图像图标: 这是 ListCellRenderer 类:
class MyComboRendere implements ListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
JLabel label = new JLabel();
label.setOpaque(true);
label.setText(value.toString());
label.setIcon(new ImageIcon("/pics/Color-icon.png"));
if (isSelected)
if (index == 0)
label.setBackground(Color.RED);
else if (index == 1)
label.setBackground(Color.GREEN);
else
label.setBackground(Color.BLUE);
return label;
}
}
这是设置组合框的方法:
public void setComboColor(){
Vector<String> colors=new Vector<>();
comboPanel=new JPanel(new BorderLayout());
colors.add("RED");
colors.add("GREEN");
colors.add("BLUE");
colorCombo=new JComboBox(colors);
colorCombo.setRenderer(new MyComboRendere());
comboPanel.add(colorCombo,BorderLayout.BEFORE_FIRST_LINE);
}
最佳答案
似乎 label.setIcon(new ImageIcon("/pics/Color-icon.png"));
没有获取图标的实际路径,因为它总是返回 null,但是它不会抛出异常。所以我尝试使用这个:
java.net.URL imgURL = getClass().getResource("/pics/Color-icon.png");
label.setIcon(icon);
并且工作正常
关于java - 带有文本和 ImageIcon 的 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15020679/