将对象放入 JComboBox 中
Put Objects Inside a JComboBox
所以我有一个名为 Note
的 class,我需要将每个 Note
放在一个 JComboBox 中。
每个音符都有一个 String id
和一个 String title
。 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
class.
中添加默认构造函数
所以我有一个名为 Note
的 class,我需要将每个 Note
放在一个 JComboBox 中。
每个音符都有一个 String id
和一个 String title
。 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
class.