- 目的: 各項目に異なる背景色とテキストを持つ 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;
}
}