我在Javafx中有一个窗格,每当鼠标进入边界时都希望对其进行动画处理,并且我希望动画一旦鼠标退出窗格就停止。我知道这需要侦听器,但我发现的所有答案似乎都只涉及到java.awt
答案 0 :(得分:5)
您可以使用方法Node.setOnMouseEntered()
和Node.setOnMouseExited()
注册事件处理程序,以启动或停止动画。这是一个简单的示例:
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
}
}
答案 1 :(得分:3)
或者您可以通过* .fxml文件链和控制器类来实现它:
onMouseEntered="#onMouseInto" onMouseExited="#onMouseOut"
添加到您的in fxml文件到Pane字符串中,使它像<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");
}