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();
}
}
上面的代碼生成以下結果。
重用事件處理程序
以下代碼定義了一個事件處理程序對象并重用它添加事件處理程序。
// 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();
}
}
更多建議: