JavaFX - 使用便捷方法



事件處理程式簡單地定義為事件發生後要執行的操作。這些事件處理程式可以註冊以處理更復雜的事件;並且可以使用便捷方法在 JavaFX 應用程式中註冊事件處理程式。可以建立和註冊事件處理程式以響應滑鼠事件、鍵盤事件、視窗事件等事件。

一些 JavaFX 類定義了事件處理程式屬性,這些屬性提供了一種註冊事件處理程式的方法。將事件處理程式屬性設定為使用者定義的事件處理程式會自動註冊處理程式以接收相應的事件型別。事件處理程式屬性的 setter 方法是註冊事件處理程式的便捷方法。

使用便捷方法進行事件處理

JavaFX 中的一些類定義了事件處理程式屬性。透過使用各自的 setter 方法將值設定為這些屬性,您可以註冊到事件處理程式。這些方法稱為便捷方法。

大多數這些方法存在於 Node、Scene、Window 等類中,並且它們可用於所有其子類。下表描述了可用於不同事件的各種便捷方法

使用者操作 事件型別 事件處理程式屬性
按下、釋放或在鍵盤上鍵入鍵。 KeyEvent

onKeypressed

onKeyReleased

onKeyTyped

移動、點選或拖動滑鼠。 MouseEvent

onMouseClicked

onMouseMoved

onMousePressed

onMouseReleased

onMouseEntered

onMouseExited

按下、拖動和釋放滑鼠按鈕。 MouseDragEvent

onMouseDragged

onMouseDragEntered

onMouseDragExited

onMouseDragged

onMouseDragOver

onMouseDragReleased

從備用方法生成、更改、刪除或提交輸入。 InputMethodEvent onInputMethodTextChanged
執行平臺支援的拖放操作。 DragEvent

onDragDetected

onDragDone

onDragDropped

onDragEntered

onDragExited

onDragOver

滾動物件。 ScrollEvent

onScroll

onScrollStarted

onScrollFinished

旋轉物件。 RotateEvent

onRotate

onRotationFinished

onRotationStarted

向上、向下、向右和向左滑動物件。 SwipeEvent

onSwipeUP

onSwipeDown

onSwipeLeft

onSwipeRight

觸控物件。 TouchEvent

onTouchMoved

onTouchReleased

onTouchStationary

縮放物件。 ZoomEvent

onZoom

onZoomStarted

onZoomFinished

請求上下文選單。 ContextMenuEvent onContextMenuRequested
按下按鈕、顯示或隱藏組合框、選擇選單項。 ActionEvent
編輯列表中的專案。 ListView.EditEvent
編輯表格中的專案。 TableColumn.CellEditEvent
編輯樹中的專案。 TreeView.EditEvent
在媒體播放器中遇到錯誤。 MediaErrorEvent
顯示或隱藏選單。 Event
隱藏彈出視窗。 Event
選擇或關閉選項卡。 Event
顯示、最小化或關閉視窗。 WindowEvent

語法

以下是用於註冊事件處理程式的便捷方法的格式

setOnEvent-type(EventHandler<? super event-class> value)

例如,要向按鈕新增滑鼠事件偵聽器,可以使用便捷方法setOnMouseClicked(),如下所示。

playButton.setOnMouseClicked((new EventHandler<MouseEvent>() { 
   public void handle(MouseEvent event) { 
      System.out.println("Hello World"); 
      pathTransition.play(); 
   } 
}));

示例

以下程式是一個示例,演示了使用便捷方法在 JavaFX 中進行事件處理。

將此程式碼儲存在名為ConvenienceMethodsExample.java的檔案中。

import javafx.animation.PathTransition; 
import javafx.application.Application; 
import static javafx.application.Application.launch; 
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.scene.shape.LineTo; 
import javafx.scene.shape.MoveTo; 
import javafx.scene.shape.Path; 
import javafx.stage.Stage; 
import javafx.util.Duration; 
         
public class ConvenienceMethodsExample extends Application { 
   @Override 
   public void start(Stage stage) {      
      //Drawing a Circle 
      Circle circle = new Circle(); 
      
      //Setting the position of the circle 
      circle.setCenterX(300.0f); 
      circle.setCenterY(135.0f); 
      
      //Setting the radius of the circle 
      circle.setRadius(25.0f);  
      
      //Setting the color of the circle 
      circle.setFill(Color.BROWN); 
      
      //Setting the stroke width of the circle 
      circle.setStrokeWidth(20);      
       
      //Creating a Path 
      Path path = new Path(); 
      
      //Moving to the staring point 
      MoveTo moveTo = new MoveTo(208, 71);               
      
      //Creating 1st line 
      LineTo line1 = new LineTo(421, 161);        
      
      //Creating 2nd line 
      LineTo line2 = new LineTo(226,232); 
      
      //Creating 3rd line 
      LineTo line3 = new LineTo(332,52);        
      
      //Creating 4th line 
      LineTo line4 = new LineTo(369, 250);        
      
      //Creating 5th line 
      LineTo line5 = new LineTo(208, 71);       
      
      //Adding all the elements to the path 
      path.getElements().add(moveTo); 
      path.getElements().addAll(line1, line2, line3, line4, line5);     
      
      //Creating the path transition 
      PathTransition pathTransition = new PathTransition(); 
      
      //Setting the duration of the transition 
      pathTransition.setDuration(Duration.millis(1000));       
      
      //Setting the node for the transition 
      pathTransition.setNode(circle); 
      
      //Setting the path for the transition 
      pathTransition.setPath(path); 
      
      //Setting the orientation of the path 
      pathTransition.setOrientation(
         PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT);
      
      //Setting the cycle count for the transition 
      pathTransition.setCycleCount(50); 
      
      //Setting auto reverse value to true 
      pathTransition.setAutoReverse(false);
      
      //Creating play button 
      Button playButton = new Button("Play"); 
      playButton.setLayoutX(300); 
      playButton.setLayoutY(250); 
       
      circle.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() { 
         @Override 
         public void handle(javafx.scene.input.MouseEvent e) { 
            System.out.println("Hello World"); 
            circle.setFill(Color.DARKSLATEBLUE);             
         } 
      });   
      playButton.setOnMouseClicked((new EventHandler<MouseEvent>() { 
         public void handle(MouseEvent event) { 
            System.out.println("Hello World");  
            pathTransition.play(); 
         } 
      })); 
       
      //Creating stop button 
      Button stopButton = new Button("stop"); 
      stopButton.setLayoutX(250); 
      stopButton.setLayoutY(250); 
      
      stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() { 
         public void handle(MouseEvent event) { 
            System.out.println("Hello World"); 
            pathTransition.stop(); 
         } 
      }));
      //Creating a Group object  
      Group root = new Group(circle, playButton, stopButton); 
         
      //Creating a scene object 
      Scene scene = new Scene(root, 600, 300); 
      scene.setFill(Color.LAVENDER);  
      
      //Setting title to the Stage 
      stage.setTitle("Convenience Methods 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 ConvenienceMethodsExample.java 
java --module-path %PATH_TO_FX% --add-modules javafx.controls ConvenienceMethodsExample

輸出

執行後,上述程式會生成一個如下所示的 JavaFX 視窗。在此,單擊“播放”按鈕以啟動動畫,並單擊“停止”按鈕以停止動畫。

Convenience Method
廣告