下面是一个示例代码,展示了如何在按下按钮后执行按钮操作,并使用动画效果:
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import javafx.util.Duration;
public class ButtonAnimationExample extends Application {
@Override
public void start(Stage primaryStage) {
Button button = new Button("点击我");
button.setOnAction(event -> {
// 创建一个动画效果,使按钮缩放
Timeline timeline = new Timeline(
new KeyFrame(Duration.seconds(0), new KeyValue(button.scaleXProperty(), 1)),
new KeyFrame(Duration.seconds(0), new KeyValue(button.scaleYProperty(), 1)),
new KeyFrame(Duration.seconds(0.5), new KeyValue(button.scaleXProperty(), 0.8)),
new KeyFrame(Duration.seconds(0.5), new KeyValue(button.scaleYProperty(), 0.8)),
new KeyFrame(Duration.seconds(1), new KeyValue(button.scaleXProperty(), 1)),
new KeyFrame(Duration.seconds(1), new KeyValue(button.scaleYProperty(), 1))
);
timeline.play();
// 按钮操作
System.out.println("执行按钮操作");
});
StackPane root = new StackPane();
root.getChildren().add(button);
Scene scene = new Scene(root, 200, 200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
在这个示例中,我们创建了一个按钮,并设置了按钮的事件处理程序。在按钮的事件处理程序中,我们创建了一个Timeline
对象,通过一系列KeyFrame
和KeyValue
来定义按钮的缩放动画效果。然后,我们通过调用timeline.play()
来启动动画。
在按钮的事件处理程序中,我们还可以执行其他的按钮操作。在这个示例中,我们只是简单地打印了一条消息:“执行按钮操作”。
你可以运行这段代码,并观察按钮在被按下时的动画效果和按钮操作的执行。