这个问题解决了问题:带有图像和文字的ChocieBox: JavaFX: ChoiceBox with image and text 但是当我在ChoiceBox中添加一个Separator时,我得到了一个Exception。 这是代码:
statusComboBox.setItems(FXCollections.observableArrayList("open",new Separator(), "save", "exit"));
statusComboBox.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
public ListCell<String> call(ListView<String> p) {
return new ListCell<String>() {
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(item);
if (item == null || empty) {
setGraphic(null);
} else {
Image icon;
try {
int iconNumber = this.getIndex() + 1;
String iconPath = "/icon_" + iconNumber + ".png";
icon = new Image(getClass().getResourceAsStream(iconPath));
} catch (NullPointerException ex) {
// in case the above image doesn't exist, use a default one
String iconPath = "/icon_na.png";
icon = new Image(getClass().getResourceAsStream(iconPath));
}
ImageView iconImageView = new ImageView(icon);
iconImageView.setFitHeight(30);
iconImageView.setPreserveRatio(true);
setGraphic(iconImageView);
}
}
};
}
});
,这是例外:
Exception in thread "JavaFX Application Thread" java.lang.ClassCastException: javafx.scene.control.Separator cannot be cast to java.lang.String
at dumaisoft.SampleController$2$1.updateItem(SampleController.java:49)
at javafx.scene.control.ListCell.updateItem(ListCell.java:471)
at javafx.scene.control.ListCell.indexChanged(ListCell.java:330)
at javafx.scene.control.IndexedCell.updateIndex(IndexedCell.java:116)
at com.sun.javafx.scene.control.skin.VirtualFlow.setCellIndex(VirtualFlow.java:1957)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCell(VirtualFlow.java:1797)
at com.sun.javafx.scene.control.skin.VirtualFlow.getCellLength(VirtualFlow.java:1879)
at com.sun.javafx.scene.control.skin.VirtualContainerBase.getVirtualFlowPreferredHeight(VirtualContainerBase.java:101)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.getListViewPrefHeight(ComboBoxListViewSkin.java:530)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin.access$300(ComboBoxListViewSkin.java:57)
at com.sun.javafx.scene.control.skin.ComboBoxListViewSkin$3.computePrefHeight(ComboBoxListViewSkin.java:472)
at javafx.scene.Parent.prefHeight(Parent.java:935)
at javafx.scene.layout.Region.prefHeight(Region.java:1435)
我该如何解决?