将鼠标悬停事件添加到ComboBox项目

时间:2018-01-09 19:27:15

标签: javafx combobox imageview

我怎么能有一个组合框,当鼠标光标悬停在组合框项目上时,特定图像会出现在JavaFX中的指定图像视图上? 这就是我所拥有的:

    Image myImage1 = new Image("MyImage1.jpg");
    Image myImage2 = new Image("MyImage2.jpg");
    Image myImage3 = new Image("MyImage3.jpg");
    ImageView myImageView = new ImageView();
    ComboBox myComboBox = new ComboBox();
    myComboBox.getItems().addAll("Item1","Item2","Item3");
    //
    // Mouse Hover for ComboBox items here ...
    //
    // If Item1 Hovered -> ImageView.setImage(myImage1);
    // If Item2 Hovered -> ImageView.setImage(myImage2);
    // If Item3 Hovered -> ImageView.setImage(myImage3);

感谢。

1 个答案:

答案 0 :(得分:1)

在组合框中使用单元工厂:

Image myImage1 = new Image("MyImage1.jpg");
Image myImage2 = new Image("MyImage2.jpg");
Image myImage3 = new Image("MyImage3.jpg");
ImageView myImageView = new ImageView();
ComboBox<String> myComboBox = new ComboBox<>();
myComboBox.getItems().addAll("Item1","Item2","Item3");

Map<String, Image> images = new HashMap<>();
images.put("Item1", myImage1);
images.put("Item2", myImage2);
images.put("Item3", myImage3);

myComboBox.setCellFactory(lv -> {
    ListCell<String> cell = new ListCell<String>() {
        @Override
        protected void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            setText(item);
        }
    };
    cell.hoverProperty().addListener((obs, wasHovered, isNowHovered) -> {
        if (cell.isEmpty()) {
            myImageView.setImage(null);
        } else {
            myImageView.setImage(images.get(cell.getItem());
        }
    });
    return cell ;
});