- 目的:在每个项目中有一个具有不同背景颜色和文本的 JComboBox。
- 我的问题:背景颜色没有改变,文本不是我在setText中设置的,在System.out.println中已经正确显示。getSelectedIndex() 效果很好。
捕获:http: //i.stack.imgur.com/EgfZs.png
以下是我消化并尝试错误后的代码 Dr.Google 显示:
public class ColorCode{
private Color color;
private String alias;
...
}
public class ElectronicColorCode extends JFrame implements ActionListener{
private JComboBox[] selections = new JComboBox[4];
...
public ElectronicColorCode(){
for(int i=0; i<selections.length; i++){
selections[i] = new JComboBox();
for(int j=0; j<tolColorSets.length; j++)
selections[i].addItem(new ComboBoxRenderer(colorSets[j]));
}
selections[i].addActionListener(this);
...
}
}
class ComboBoxRenderer extends JLabel implements ListCellRenderer{
private ColorCode colorCode;
public ComboBoxRenderer(ColorCode colorCode){
super();
this.colorCode = colorCode;
setBackground(colorCode.getColor());
setText(colorCode.getAlias());
System.out.println(colorCode.getAlias());
}
public Component getListCellRendererComponent(JList list, Object obj, int row, boolean isSelected, boolean hasFocus){
return this;
}
}