JavaFx添加事件处理addEventHandler(十)
JavaFx添加事件处理addEventHandler(十)
JavaFx从入门到入土系列
有时候我需要给一些元素标签添加事件,例如点击事件、鼠标停留事件、按键输入事件等等,这时我们需要用到addEventHandler
下面是添加一个点击事件:MouseEvent.MOUSE_CLICKED
public class Test03 extends Application {
@Override
public void start(Stage stage) throws Exception {
Label label = new Label("hello world!");
stage.setScene(new Scene(label));
stage.setWidth(400);
stage.setHeight(100);
stage.setTitle("师姐,你好!");
stage.show();
label.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println(mouseEvent.getX());
}
});
}
public static void main(String[] args) {
launch(args);
}
}
接下来添加一个鼠标移动事件:MouseEvent.MOUSE_MOVED
// 鼠标移动事件
label.addEventHandler(MouseEvent.MOUSE_MOVED, new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println(mouseEvent.getX());
}
});
接下来添加一个按键事件:
你以为这样写
label.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
System.out.println(keyEvent.getCharacter());
}
});
实际上这样写按键是没有反应的。按键事件不能添加到一般标签,需要添加到容器类标签。例如改下:
Label label = new Label("hello world!");
Scene scene = new Scene(label);
stage.setScene(scene);
// ...
scene.addEventFilter(KeyEvent.KEY_TYPED, new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent keyEvent) {
System.out.println(keyEvent.getCharacter());
}
});
这样就能拿到按键事件了。
KeyEvent.KEY_PRESSED:任意按键按下时响应
KeyEvent.KEY_RELEASED:任意按键松开时响应
KeyEvent.KEY_TYPED:文字输入键按下松开后响应
还有滑动之类的事件自行摸索,可以反向查看源码可以看到有哪些事件: