起初这个问题似乎很简单,但是几天来我已经遇到了麻烦。
所以,我的问题是,当打开ComboBox选择并单击鼠标以选择选项时,我想检测鼠标单击和选择。
因此,它应该做的是检测所选内容上的MOUSE CLICK并获取所选值:
PS:我的ComboBox的代码可以在这里看到:
Select JavaFX Editable Combobox text on click
随时提出其他问题。
最佳答案
只需使用一个单元工厂,并在该单元中注册一个处理程序即可:
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);
}
}