JavaFX - 事件处理程序



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

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

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

添加和删除事件处理程序

要向节点添加事件处理程序,需要使用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);

示例

以下程序是一个示例,演示了使用事件处理程序在 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 轴旋转。如果您再次单击该框,则旋转停止。

示例

让我们看看另一个可以使用事件处理程序的场景。在此示例中,我们正在创建一个 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 窗口,显示一个带有淡入淡出过渡的圆形。

Text Field
广告