所以我有一个名为 Note
的类,我需要将每个 Note
放入 JComboBox 中。
每个注释都有一个字符串 ID
和一个字符串标题
。 title
正在向用户显示,id
正在后端使用。
我编写了一个自定义渲染器来实现此功能,但出现编译器错误:错误:注释无法转换为字符串
这是代码:
//Inside of the GUI class
cmbNotes.setRenderer(new NoteListCellRenderer());
//Populate combo box with the title of each note
NoteManager.notes.forEach((id, note) -> { //For-each loop
if (!note.isOpen()) {
cmbNotes.addItem(note); //ERROR: Note cannot be converted to String
}
});
这是我的自定义渲染器:
//In the same file as GUI, but outside of the GUI class
class NoteListCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value instanceof Note) {
value = ((Note) value).getTitle();
}
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
}
}
最佳答案
谢谢Riann Nel帮助我解决这个问题。
我通过设计而不是代码创建了 JComboBox。
设计默认设置Type Parameters
至String
所以我进入设计并单击右侧的代码部分,然后更改 Type Parameters
至<Note>
.
我还必须在我的 Note
中添加一个默认构造函数类。
关于java - 将对象放入 JComboBox 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59496744/