[英]how to achieve javafx mouse event “push and hold”?
I am developing a JavaFX project and I need something similar to a TouchEvent
that characterizes a "push and hold" event . 我正在开发JavaFX项目,并且需要类似于TouchEvent
东西, TouchEvent
可以描述“按下并保持”事件 。 But It should be mapped as a MouseEvent
because I'm having troubles with touch events on Linux. 但是应该将其映射为MouseEvent
因为我在Linux上遇到触摸事件时遇到了麻烦。 For instance, in Ubuntu, it won't respond to touch events. 例如,在Ubuntu中,它不会响应触摸事件。
Please, let me know if you have any ideas about how to fire a MouseEvent
whenever a "push and hold" occurs on Linux? 请让我知道您是否对在Linux上发生“按下并按住”时如何触发MouseEvent
有任何想法?
Just use a PauseTransition
as a timer for the "hold". 只需将PauseTransition
用作“保持”的计时器。 Start it if the mouse is pressed, stop it if it's released or dragged. 如果按下鼠标,则将其启动;如果释放或拖动,则将其停止。
import javafx.animation.PauseTransition;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class MousePressAndHoldTest extends Application {
@Override
public void start(Stage primaryStage) {
Pane root = new Pane();
addPressAndHoldHandler(root, Duration.seconds(1),
event -> System.out.println("Press and hold"));
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
private void addPressAndHoldHandler(Node node, Duration holdTime,
EventHandler<MouseEvent> handler) {
class Wrapper<T> { T content ; }
Wrapper<MouseEvent> eventWrapper = new Wrapper<>();
PauseTransition holdTimer = new PauseTransition(holdTime);
holdTimer.setOnFinished(event -> handler.handle(eventWrapper.content));
node.addEventHandler(MouseEvent.MOUSE_PRESSED, event -> {
eventWrapper.content = event ;
holdTimer.playFromStart();
});
node.addEventHandler(MouseEvent.MOUSE_RELEASED, event -> holdTimer.stop());
node.addEventHandler(MouseEvent.DRAG_DETECTED, event -> holdTimer.stop());
}
public static void main(String[] args) {
launch(args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.