JavaFX如何制作鼠标多击事件?

JavaFX制作鼠标双击或者多击事件需要用到getClickCount()方法,这个方法需要添加addEventHandler()方法,addEventHandler()是事件方法。

 1 scene.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
 2 
 3             @Override
 4             public void handle(MouseEvent event) {
 5                 int times=event.getClickCount();
 6                 if(times==2) {
 7                     System.out.println("2次"); 8  } 9  } 10 });
在这段代码中,scene知识为了测试用的,基本所有控件都有此方法,比如按钮等等。
我们要注意的是后面的2个参数,要填入的是你要监听的东西,不如鼠标事件就是 MouseEvent,后面是具体事件MOUSE_CLICKED
第二个参数是一个对象,里面可以实现你的方法了!
 1 package text1;
 2 
 3 import javafx.application.Application;
 4 import javafx.event.EventHandler;
 5 import javafx.scene.Group;
 6 import javafx.scene.Scene;
 7 import javafx.scene.input.MouseEvent; 8 import javafx.stage.Stage; 9 10 public class Main extends Application { 11 12  @Override 13 public void start(Stage stage) throws Exception { 14 Group root=new Group(); 15 Scene scene=new Scene(root); 16 stage.setWidth(500); 17 scene.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() { 18 19  @Override 20 public void handle(MouseEvent event) { 21 int times=event.getClickCount(); 22 if(times==2) { 23 System.out.println("2次"); 24  } 25  } 26  }); 27  stage.setScene(scene); 28  stage.show(); 29  } 30 31 public static void main(String[] args) { 32  launch(args); 33  } 34 35 }

猜你喜欢

转载自www.cnblogs.com/modulecode/p/12079392.html
今日推荐