本文概述
JavaFX使我们能够使用事件处理程序来处理由键盘操作, 鼠标操作以及更多源节点生成的事件。
事件处理程序用于在事件冒泡阶段中处理事件。一个节点可以有多个事件处理程序。
我们还可以将单个处理程序用于多个节点和多种事件类型。在本教程的这一部分中, 我们将讨论如何将事件处理程序用于处理事件。
添加事件处理程序
必须为节点注册事件处理程序, 以便在事件冒泡阶段处理事件。事件处理程序是EventHandler接口的实现。接口的handle()方法包含触发事件时执行的逻辑。
要注册EventHandler, 请使用addEventHandler()。在此方法中, 传递了两个参数。一种是事件类型, 另一种是EventHandler对象。
addEventHandler()的语法如下。
node.addEventHandler(<EventType>, new EventHandler<Event-Type>()
{
public void handle(<EventType> e)
{
//handling code
}
});
例
在下面的示例中, 使用两个不同的按钮注册了相同的事件处理程序。事件源在handle()方法中进行区分。单击“播放”按钮时, 圆圈开始沿正X方向平移;单击“暂停”按钮时, 圆圈暂停。
package application;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
public class JavaFX_EventHandler extends Application{
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
//Creating Circle and setting the color and stroke in the circle
Circle c = new Circle(100, 100, 50);
c.setFill(Color.GREEN);
c.setStroke(Color.BLACK);
//creating play button and setting coordinates for the button
Button btn = new Button("Play");
btn.setTranslateX(125);
btn.setTranslateY(200);
// creating pause button and setting coordinate for the pause button
Button btn1 = new Button("Pause");
btn1.setTranslateX(175);
btn1.setTranslateY(200);
//Instantiating TranslateTransition class to create the animation
TranslateTransition trans = new TranslateTransition();
//setting attributes for the TranslateTransition
trans.setAutoReverse(true);
trans.setByX(200);
trans.setCycleCount(100);
trans.setDuration(Duration.millis(500));
trans.setNode(c);
//Creating EventHandler
EventHandler<MouseEvent> handler = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
// TODO Auto-generated method stub
if(event.getSource()==btn)
{
trans.play(); //animation will be played when the play button is clicked
}
if(event.getSource()==btn1)
{
trans.pause(); //animation will be paused when the pause button is clicked
}
event.consume();
}
};
//Adding Handler for the play and pause button
btn.setOnMouseClicked(handler);
btn1.setOnMouseClicked(handler);
//Creating Group and scene
Group root = new Group();
root.getChildren().addAll(c, btn, btn1);
Scene scene = new Scene(root, 420, 300, Color.WHEAT);
primaryStage.setScene(scene);
primaryStage.setTitle("EventHandler example");
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
删除EventHandler
当我们不再需要EventHandler处理节点或事件类型的事件时, 可以使用removeEventHandler()方法删除EventHandler。此方法带有两个参数, 事件类型和EventHandler对象。
node.removeEventHandler(<EventType>, handler);
评论前必须登录!
注册