我在编写JComboBox
时遇到了问题。我正在尝试更改某些组合框项目的颜色。组合框如果连接到文件并通过选择其中一个项目,则会在该文件中获取一行。如果行包含零,我希望项目的颜色不同。
问题是,如果使用ComboBoxRenderer
或CellRenderer
,我无法获得。
这是我的代码:
JComboBox combo = new JComboBox(industryName);
combo.setSelectedItem(null);
combo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
String selectedString = (String) combo.getSelectedItem();
try {
CSVReader reader = new CSVReader(new FileReader(myFile));
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
if(nextLine[1].equals(industry) ){
x= nextLine;
x2 = Arrays.toString(nextLine);
break;
}
}
reader.close();
} catch (FileNotFoundException e1) {
System.out.println("File not fount");
e1.printStackTrace();
} catch (IOException e3) {
e3.printStackTrace();
}
catch (NullPointerException e2){
JOptionPane.showMessageDialog(frame.getComponent(0), "Please choose ...");
}
}
});
ComboBoxRenderer renderer = new ComboBoxRenderer(comboBoxIndustry, x2);
comboBoxIndustry.setRenderer(renderer);
class ComboBoxRenderer extends JPanel implements ListCellRenderer{
private static final long serialVersionUID = -1L;
private String[] x2;
private String[] strings;
JLabel text;
public ComboBoxRenderer(JComboBox combo, String[] x2) {
this.x2 = x2;
text = new JLabel();
text.setOpaque(true);
text.setFont(combo.getFont());
}
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (isSelected)
{
setBackground(list.getSelectionBackground());
}
else
{
setBackground(Color.WHITE);
}
text.setBackground(getBackground());
text.setText(value.toString());
for(int i = 0; i <x2.length; i++){
String[] disable = x2[0].split(",");
if(Double.parseDouble((String) disable[2]) == 0.000000){
//combo.getEditor().getEditorComponent().setBackground(Color.YELLOW);
text.setForeground(Color.YELLOW);
// ((JTextField) comboBoxIndustry.getEditor().getEditorComponent()).setBackground(Color.YELLOW);
}
}
return text;
}
}