Detect mouse click on SELECTION Editable ComboBox JavaFX

Deadly 提交于 2021-02-08 07:32:45

问题


The question may seem pretty easy at first, but I've already had troubles with it for a few days.

So, my problem is that I would like to detect mouse click AND the selection when the ComboBox selection is open and the mouse click is made to choose the option.

So, what it should do is detect the MOUSE CLICK on the selection and also get the selected value as well:

PS: The code for my ComboBox can be seen here: Select JavaFX Editable Combobox text on click

Feel free to ask additional questions.


回答1:


Just use a cell factory, and register a handler with the cell:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ListCell;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class ComboBoxMouseClickOnCell extends Application {

    @Override
    public void start(Stage primaryStage) {
        ComboBox<String> combo = new ComboBox<>();
        combo.getItems().addAll("One", "Two", "Three");
        combo.setCellFactory(lv -> {
            ListCell<String> cell = new ListCell<String>() {
                @Override
                protected void updateItem(String item, boolean empty) {
                    super.updateItem(item, empty);
                    setText(empty ? null : item);
                }
            };
            cell.setOnMousePressed(e -> {
                if (! cell.isEmpty()) {
                    System.out.println("Click on "+cell.getItem());
                }
            });
            return cell ;
        });

        Scene scene = new Scene(new StackPane(combo), 300, 180);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


来源:https://stackoverflow.com/questions/39875100/detect-mouse-click-on-selection-editable-combobox-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!