Java 组合框中的项目消失
从使用JavaFX中的场景生成器创建的FXML文件创建组合框的自定义单元格工厂时,我遇到以下问题: 我创建了一个标签的自定义单元格工厂。当用户单击项目时,它可以正常工作。y显示在“按钮”区域。但是,当用户想要单击其他项目时,以前单击的项目将消失。 以下是combobox单元格工厂的代码:Java 组合框中的项目消失,java,combobox,javafx-2,javafx,fxml,Java,Combobox,Javafx 2,Javafx,Fxml,从使用JavaFX中的场景生成器创建的FXML文件创建组合框的自定义单元格工厂时,我遇到以下问题: 我创建了一个标签的自定义单元格工厂。当用户单击项目时,它可以正常工作。y显示在“按钮”区域。但是,当用户想要单击其他项目时,以前单击的项目将消失。 以下是combobox单元格工厂的代码: idCardOnlineStatusComboBox.setCellFactory(new Callback<ListView<Label>, ListCell<Label>&g
idCardOnlineStatusComboBox.setCellFactory(new Callback<ListView<Label>, ListCell<Label>>() {
@Override public ListCell<Label> call(ListView<Label> param) {
final ListCell<Label> cell = new ListCell<Label>() {
@Override public void updateItem(Label item,
boolean empty) {
super.updateItem(item, empty);
if(item != null || !empty) {
setGraphic(item);
}
}
};
return cell;
}
});
然后我用以下内容填充组合框:
idCardOnlineStatusComboBox.getItems().addAll(
new Label(Resource.getStringFor("MainForm.Pane.MenuBar.Vortex.OnlineStatus.Online.Title"), new ImageView(onlineImg)),
new Label(Resource.getStringFor("MainForm.Pane.MenuBar.Vortex.OnlineStatus.Away.Title"), new ImageView(awayImg)),
new Label(Resource.getStringFor("MainForm.Pane.MenuBar.Vortex.OnlineStatus.DoNotDisturb.Title"), new ImageView(doNotDisturbImg)),
new Label(Resource.getStringFor("MainForm.Pane.MenuBar.Vortex.OnlineStatus.Invisible.Title"), new ImageView(offlineImg)),
new Label(Resource.getStringFor("MainForm.Pane.MenuBar.Vortex.OnlineStatus.Offline.Title"), new ImageView(offlineImg))
);
消失的行为可能是一个bug。您可以将其提交给JavaFX Jira,并让Oracle人员进一步决定。此外,您还可以调查
ComboBox.setCellFactory(…)
源代码以了解此行为的原因,并找到解决方法。但是我的建议是使用ComboBox单元格(ListCell
)的内部标记的组件,而不是您的组件:
@Override
public void updateItem(Label item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty) {
setText(item.getText());
setGraphic(item.getGraphic());
} else {
setText(null);
setGraphic(null);
}
}
注意代码的else部分,在编写if语句时涵盖所有用例。您的所有代码都在这里吗?请发布一个我们可以尝试查看错误的地方。我会尝试的。非常感谢。
@Override
public void updateItem(Label item, boolean empty) {
super.updateItem(item, empty);
if (item != null && !empty) {
setText(item.getText());
setGraphic(item.getGraphic());
} else {
setText(null);
setGraphic(null);
}
}