[英]JavaFX - How to check if mouse is has entered and or exited a Pane?
I have a pane in Javafx that a want to animate whenever the mouse has entered its boundaries and I want the animation to stop once the mouse has exited the pane.我在 Javafx 中有一个窗格,它希望在鼠标进入其边界时动画,并且我希望在鼠标退出窗格后动画停止。 I understand this calls for a listener but all the answers I find only seem to concern java.awt
我理解这需要一个听众,但我找到的所有答案似乎只与 java.awt 有关
You can use the methods Node.setOnMouseEntered()
and Node.setOnMouseExited()
to register event handlers, which start or stop your animation.您可以使用
Node.setOnMouseEntered()
和Node.setOnMouseExited()
来注册开始或停止动画的事件处理程序。 Here is a simple example:这是一个简单的例子:
public class MainTest extends Application {
public void start(Stage primaryStage) {
Pane pane = new Pane();
pane.setStyle("-fx-background-color: #ff0000");
pane.setLayoutX(100);
pane.setLayoutY(100);
pane.setPrefSize(300,300);
pane.setOnMouseEntered(event -> startAnimation());
pane.setOnMouseExited(event -> stopAnimation());
Scene scene = new Scene(new Pane(pane), 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
private void stopAnimation() {
System.out.println("stop");
// do whatever you need to start your animation
}
private void startAnimation() {
System.out.println("start");
// do whatever you need to stop your animation
}
}
Or you can make it with chain of *.fxml file and your controller class:或者您可以使用 *.fxml 文件链和您的控制器类来制作它:
onMouseEntered="#onMouseInto" onMouseExited="#onMouseOut"
to make it likeonMouseEntered="#onMouseInto" onMouseExited="#onMouseOut"
使其像<AnchorPane fx:id="rootPane" onMouseEntered="#onMouseInto" onMouseExited="#onMouseOut" prefHeight="400.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="yourPackage.YourControllerClass">
@FXML
public AnchorPane rootPane;
public void onMouseInto(MouseEvent mouseEvent) {
//Your own event when cursor is gonna into the rootPane
rootPane.setStyle("-fx-background-color: #1F292E");
}
public void onMouseOut(MouseEvent mouseEvent) {
//Your own event when cursor is gonna out the rootPane
rootPane.setStyle("-fx-background-color: #C792EA");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.