我在从使用 JavaFX 中的场景生成器创建的 FXML 文件创建 ComboBox 的自定义单元工厂时遇到以下问题: 我创建了一个自定义标签单元工厂。当用户单击项目时它工作正常。 y 显示在“按钮”区域中。但是,当用户想要单击另一个项目时,先前单击的项目就会消失。
这是组合框单元工厂的代码:
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;
}
});
我认为细胞工厂有问题,但我不知道它在哪里。
我使用以下代码从 fxml 中提取组合框:
@FXML private ComboBox idCardOnlineStatusComboBox;
然后我用这个填充组合框:
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))
);
最佳答案
消失的行为可能是一个错误。您可以将其归档到 JavaFX Jira,然后让 Oracle 人员进一步决定。此外,您可以调查 ComboBox.setCellFactory(...)
源代码以了解此行为的原因并找到解决方法。但我的建议是使用 ComboBox Cell 的 (ListCell
) 内部 Labeled
组件,而不是您的:
@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 语句时的所有用例。
关于java - 组合框中的项目消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18796030/