W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
事件處理程序允許在事件冒泡階段期間處理事件。
事件處理程序是EventHandler接口的實現(xiàn)。要注冊處理程序,請使用addEventHandler()方法。
scene.addEventHandler(DragEvent.DRAG_ENTERED, new EventHandler<DragEvent>() { public void handle(DragEvent e) { System.out.println("drag enter"); } });
完整的源代碼
import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.input.DragEvent; import javafx.stage.Stage; /*from w w w. j a v a2 s.com*/ public class Main extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { Group root = new Group(); Scene scene = new Scene(root, 300, 250); TextField textBox = new TextField(); textBox.setPromptText("Write here"); // Register an event handler for a single node and a specific event type scene.addEventHandler(DragEvent.DRAG_ENTERED, new EventHandler<DragEvent>() { public void handle(DragEvent e) { System.out.println("drag enter"); } }); root.getChildren().add(textBox); primaryStage.setScene(scene); primaryStage.show(); } }
上面的代碼生成以下結(jié)果。
以下代碼定義了一個事件處理程序?qū)ο蟛⒅赜盟砑邮录幚沓绦颉?/p>
// Define an event handler EventHandler handler = new EventHandler<InputEvent>() { public void handle(InputEvent event) { System.out.println("Handling event " + event.getEventType()); event.consume(); } }; scene.addEventHandler(DragEvent.DRAG_EXITED, handler); scene.addEventHandler(MouseEvent.MOUSE_DRAGGED, handler);
完整的源代碼
import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.input.DragEvent; import javafx.scene.input.InputEvent; import javafx.scene.input.MouseEvent; import javafx.stage.Stage; /*ww w . ja va 2s .c o m*/ public class Main extends Application { public static void main(String[] args) { Application.launch(args); } @Override public void start(Stage primaryStage) { Group root = new Group(); Scene scene = new Scene(root, 300, 250); TextField textBox = new TextField(); textBox.setPromptText("Write here"); // Define an event handler EventHandler handler = new EventHandler<InputEvent>() { public void handle(InputEvent event) { System.out.println("Handling event " + event.getEventType()); event.consume(); } }; scene.addEventHandler(DragEvent.DRAG_EXITED, handler); scene.addEventHandler(MouseEvent.MOUSE_DRAGGED, handler); root.getChildren().add(textBox); primaryStage.setScene(scene); primaryStage.show(); } }
上面的代碼生成以下結(jié)果。
刪除事件處理程序
myNode.removeEventHandler(DragEvent.DRAG_EXITED, handler);
要刪除由方便方法注冊的事件處理程序,傳遞null到便利方法
node.setOnMouseDragged(null);
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: