ComboBox有自己的对象

时间:2016-05-26 15:37:08

标签: java swing combobox

我试图使用JComboBox在我自己编写的类的不同实例之间进行选择,我已经实现了一个渲染器类:

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;
}

当我尝试初始化ComboBox时,如下所示:

 //backMan.getArrayJobs returns an Array of BackupJobs
 comboBoxJobs = new JComboBox(backMan.getArrayJobs());
 comboBoxJobs.setRenderer(new BackupJobRenderer());
 comboBoxJobs.setMaximumRowCount(3);
 comboBoxJobs.setEnabled(true);

ComboBox保持为空,但根据调试器,Array的元素似乎出现在ComboBox" dataModel"。

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

创建 DefaultComboBoxModel 并将数组放入此模型,如下所示。

DefaultComboBoxModel model = new DefaultComboBoxModel<>(yourObjectArray);
JComboBox<Object> combo = new JComboBox<>(model);
combo.setRenderer(new BackupJobRenderer());

您的Renderer类应该是:

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;
}
}