Javafx 简明教程

JavaFX - Event Handlers

事件处理程序使你能够在事件处理的事件冒泡阶段处理事件。

事件路由的冒泡阶段是事件从目标节点传到舞台节点的阶段。与事件过滤器一样,一个节点可以具有一个或多个处理程序,或者根本没有处理程序来处理事件。如果节点不包含处理程序,则事件将到达根节点且处理过程将完成。否则,如果事件分派链中的一个节点包含处理程序,则将执行处理程序。

单个处理程序可用于多个节点和多个事件类型。如果子节点的事件处理程序并未使用事件,则父节点的事件处理程序使父节点能够在子节点处理事件后对其执行操作,并为多个子节点提供通用的事件处理。

Adding and Removing Event Handlers

若要向节点添加事件处理程序,你需要使用 Node 类的 addEventHandler() 方法注册此处理程序,如下所示:

//Creating the mouse event handler
EventHandler<javafx.scene.input.MouseEvent> eventHandler =
   new EventHandler<javafx.scene.input.MouseEvent>() {

   @Override
   public void handle(javafx.scene.input.MouseEvent e) {
      System.out.println("Hello World");
      circle.setFill(Color.DARKSLATEBLUE);
   }
};
//Adding the event handler
circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler);

同样,你可以使用 removeEventHandler() 方法删除事件处理程序,如下所示:

circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler);

Example

以下程序演示了如何在 JavaFX 中使用事件处理程序进行事件处理的示例。

使用 EventHandlersExample.java 名称将此代码保存在文件中。

import javafx.animation.RotateTransition;
import javafx.application.Application;
import javafx.event.EventHandler;

import javafx.scene.Group;
import javafx.scene.PerspectiveCamera;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.paint.Color;
import javafx.scene.paint.PhongMaterial;

import javafx.scene.shape.Box;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.transform.Rotate;
import javafx.stage.Stage;
import javafx.util.Duration;

public class EventHandlersExample extends Application {

   @Override
   public void start(Stage stage) {
      //Drawing a Box
      Box box = new Box();

      //Setting the properties of the Box
      box.setWidth(150.0);
      box.setHeight(150.0);
      box.setDepth(100.0);

      //Setting the position of the box
      box.setTranslateX(350);
      box.setTranslateY(150);
      box.setTranslateZ(50);

      //Setting the text
      Text text = new Text("Type any letter to rotate the box,
         and click on the box to stop the rotation");

      //Setting the font of the text
      text.setFont(Font.font(null, FontWeight.BOLD, 15));

      //Setting the color of the text
      text.setFill(Color.CRIMSON);

      //setting the position of the text
      text.setX(20);
      text.setY(50);

      //Setting the material of the box
      PhongMaterial material = new PhongMaterial();
      material.setDiffuseColor(Color.DARKSLATEBLUE);

      //Setting the diffuse color material to box
      box.setMaterial(material);

      //Setting the rotation animation to the box
      RotateTransition rotateTransition = new RotateTransition();

      //Setting the duration for the transition
      rotateTransition.setDuration(Duration.millis(1000));

      //Setting the node for the transition
      rotateTransition.setNode(box);

      //Setting the axis of the rotation
      rotateTransition.setAxis(Rotate.Y_AXIS);

      //Setting the angle of the rotation
      rotateTransition.setByAngle(360);

      //Setting the cycle count for the transition
      rotateTransition.setCycleCount(50);

      //Setting auto reverse value to false
      rotateTransition.setAutoReverse(false);

      //Creating a text filed
      TextField textField = new TextField();

      //Setting the position of the text field
      textField.setLayoutX(50);
      textField.setLayoutY(100);

      //Handling the key typed event
      EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() {
         @Override
         public void handle(KeyEvent event) {
            //Playing the animation
            rotateTransition.play();
         }
      };
      //Adding an event handler to the text feld
      textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField);

      //Handling the mouse clicked event(on box)
      EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox =
         new EventHandler<javafx.scene.input.MouseEvent>() {

         @Override
         public void handle(javafx.scene.input.MouseEvent e) {
            rotateTransition.stop();
         }
      };
      //Adding the event handler to the box
      box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox);

      //Creating a Group object
      Group root = new Group(box, textField, text);

      //Creating a scene object
      Scene scene = new Scene(root, 600, 300);

      //Setting camera
      PerspectiveCamera camera = new PerspectiveCamera(false);
      camera.setTranslateX(0);
      camera.setTranslateY(0);
      camera.setTranslateZ(0);
      scene.setCamera(camera);

      //Setting title to the Stage
      stage.setTitle("Event Handlers Example");

      //Adding scene to the stage
      stage.setScene(scene);

      //Displaying the contents of the stage
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

使用以下命令,从命令提示符编译并执行已保存的 java 文件。

javac --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersExample.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersExample

执行后,上述程序将生成一个 JavaFX 窗口,其中显示一个文本字段和一个 3D 框,如下所示:

text field

在此,如果你在文本字段中键入一个字母,3D 框将开始沿着 x 轴旋转。如果你再次单击该框则停止旋转。

Example

让我们看看另一个可以使用事件处理程序的场景。在此示例中,我们创建一个 JavaFX 对象,如圆,并对其应用淡入淡出转换。使用事件处理程序,我们指定了需要播放和暂停转换的时间;即通过单击按钮。

将此代码保存在名为 EventHandlersButton.java 的文件中。

import javafx.animation.ScaleTransition;
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 EventHandlerButton 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(150, 125, 50);
      c.setFill(Color.RED);
      c.setStroke(Color.BLACK);

      //creating play button and setting coordinates for the button
      Button btn = new Button("Play");
      btn.setTranslateX(100);
      btn.setTranslateY(250);

      // creating pause button and setting coordinate for the pause button
      Button btn1 = new Button("Pause");
      btn1.setTranslateX(150);
      btn1.setTranslateY(250);

      //Instantiating TranslateTransition class to create the animation
      ScaleTransition st = new ScaleTransition();

      //setting attributes for the TranslateTransition
      st.setNode(c);
      st.setDuration(Duration.millis(1000));
      st.setByX(1);
      st.setByY(1);
      st.setAutoReverse(true);

      st.setCycleCount(50);

      //Creating EventHandler
      EventHandler<MouseEvent> handler = new EventHandler() {
         @Override
         public void handle(MouseEvent event) {
            // TODO Auto-generated method stub
            if(event.getSource()==btn) {
               st.play(); //animation will be played when the play button is clicked
            }
            if(event.getSource()==btn1) {
               st.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 Object
      Group root = new Group();
      root.getChildren().addAll(c, btn, btn1);

      // Creating Scene Object
      Scene scene = new Scene(root, 300, 300);
      primaryStage.setScene(scene);

	  // Adding Title to Application
      primaryStage.setTitle("EventHandler Button");
      primaryStage.show();
   }
   public static void main(String[] args) {
      launch(args);
   }
}

使用以下命令,从命令提示符编译并执行已保存的 java 文件。

javac --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersButton.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls EventHandlersButton

执行上述程序,将会生成一个 JavaFX 窗口,该窗口显示一个具有淡入淡出过渡效果的圆。

eventhandler button