JavaFX ComboBox图像
我正在尝试创建一个ComboBox
,它将显示所选Image
的预览,但ComboBox
会显示字符串值。
唯一可行的方法是创建Node
ComboBox
,但这会导致一旦选定的选项从下拉菜单中消失,如果有人有任何建议,将会很感激。
我的代码如下:
String notOnLine = "file:Java1.png"; String onLine = "file:Java2.png"; ObservableList options = FXCollections.observableArrayList(); options.addAll(notOnLine, onLine); final ComboBox comboBox = new ComboBox(options); comboBox.setCellFactory(c -> new StatusListCell());
和ListCell
:
public class StatusListCell extends ListCell { protected void updateItem(String item, boolean empty){ super.updateItem(item, empty); setGraphic(null); setText(null); if(item!=null){ ImageView imageView = new ImageView(new Image(item)); imageView.setFitWidth(40); imageView.setFitHeight(40); setGraphic(imageView); setText("a"); } } }
一旦列表关闭,我希望图像显示在ComboBox
。 现在它只是显示URL(例如file:Java1.png
)。
您可以指定ComboBox
的buttonCellProperty
:
comboBox.setButtonCell(new StatusListCell());
按钮单元格用于渲染ComboBox“按钮”区域中显示的内容。