JavaFX 制作鼠标双击或者多击事件需要用到 getClickCount() 方法, 这个方法需要添加 addEventHandler() 方法, addEventHandler() 是事件方法.
- scene.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
- @Override
- public void handle(MouseEvent event) {
- int times=event.getClickCount();
- if(times==2) {
- System.out.println("2 次");
- }
- }
- });
在这段代码中, scene 知识为了测试用的, 基本所有控件都有此方法, 比如按钮等等.
我们要注意的是后面的 2 个参数, 要填入的是你要监听的东西, 不如鼠标事件就是 MouseEvent, 后面是具体事件 MOUSE_CLICKED.
第二个参数是一个对象, 里面可以实现你的方法了!
- package text1;
- import javafx.application.Application;
- import javafx.event.EventHandler;
- import javafx.scene.Group;
- import javafx.scene.Scene;
- import javafx.scene.input.MouseEvent;
- import javafx.stage.Stage;
- public class Main extends Application {
- @Override
- public void start(Stage stage) throws Exception {
- Group root=new Group();
- Scene scene=new Scene(root);
- stage.setWidth(500);
- scene.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
- @Override
- public void handle(MouseEvent event) {
- int times=event.getClickCount();
- if(times==2) {
- System.out.println("2 次");
- }
- }
- });
- stage.setScene(scene);
- stage.show();
- }
- public static void main(String[] args) {
- launch(args);
- }
- }
来源: http://www.bubuko.com/infodetail-3344207.html