首页 文章

检测鼠标单击SELECTION Editable ComboBox JavaFX

提问于
浏览
1

这个问题起初可能看起来很简单,但我已经有几天麻烦了 .

所以,我的问题是,当我打开ComboBox选项并单击鼠标选择该选项时,我想检测鼠标单击和选择 .

那么,它应该做的是检测选择上的MOUSE CLICK并同时获取所选值:

enter image description here

PS:我的ComboBox的代码可以在这里看到:Select JavaFX Editable Combobox text on click

随意提出其他问题 .

1 回答

  • 4

    只需使用单元工厂,并在单元格中注册处理程序:

    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);
        }
    }
    

相关问题