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
廣告