Reputation: 1
I'm trying to use a JComboBox to select between different Instances of a class written by myself, for which i have already implemented a renderer Class:
class BackupJobRenderer extends JLabel implements ListCellRenderer {
private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
public BackupJobRenderer() {
setOpaque(true);
setHorizontalAlignment(CENTER);
setVerticalAlignment(CENTER);}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
BackupJob bjob = (BackupJob) value;
setText(bjob.getName());
if (isSelected) {
setBackground(HIGHLIGHT_COLOR);
setForeground(Color.white);
} else {
setBackground(Color.white);
setForeground(Color.black);
}
return this;
}
When I'm trying to initialize the ComboBox like the following:
//backMan.getArrayJobs returns an Array of BackupJobs
comboBoxJobs = new JComboBox(backMan.getArrayJobs());
comboBoxJobs.setRenderer(new BackupJobRenderer());
comboBoxJobs.setMaximumRowCount(3);
comboBoxJobs.setEnabled(true);
the ComboBox stays empty, although, according to the debugger, the Array's elements seem to be present in the ComboBox's "dataModel".
What am i doing wrong here?
Upvotes: 0
Views: 114
Reputation: 919
Create DefaultComboBoxModel and put the array to this model like the following.
DefaultComboBoxModel model = new DefaultComboBoxModel<>(yourObjectArray);
JComboBox<Object> combo = new JComboBox<>(model);
combo.setRenderer(new BackupJobRenderer());
Your Renderer class should be :
class BackupJobRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(......) {
JLabel label = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
if(value !=null && value instanceof BackupJob) {
BackupJob backup = (BackupJob) value;
label.setText(backup.getName());
if (isSelected) {
label.setBackground(HIGHLIGHT_COLOR);
label.setForeground(Color.white);
} else {
label.setBackground(Color.white);
label.setForeground(Color.black);
}
}
return label;
}
}
Upvotes: 1