通常,按钮在用户界面应用程序中进行控制,单击该按钮将执行相应的操作。您可以通过实例化javafx.scene.control.Button类来创建一个Button 。
Button类从javafx.scene.control.ButtonBase类继承名为onAction的属性,该属性的类型为ObjectProperty <EventHandler <ActionEvent >>。该属性表示每当您按下按钮时调用的操作。您可以使用setOnAction()方法将值设置为此属性。
将动作设置为按钮的一种方法是使用OnAction()方法。
public class ButtonAction extends Application { @Override public void start(Stage stage) { //创建一个按钮 Button button = new Button("Play"); button.setTranslateX(25); button.setTranslateY(150); //创建一个圆 Circle circle = new Circle(150, 150, 30); circle.setFill(Color.BROWN); //设置圆的路径 MoveTo moveTo = new MoveTo(15, 15); LineTo line1 = new LineTo(100, 150); CubicCurveTo cubicCurveTo = new CubicCurveTo(); cubicCurveTo.setControlX1(400.0f); cubicCurveTo.setControlY1(40.0f); cubicCurveTo.setControlX2(175.0f); cubicCurveTo.setControlY2(250.0f); cubicCurveTo.setX(500.0f); cubicCurveTo.setY(150.0f); VLineTo vLine = new VLineTo(); vLine.setY(80); Path path = new Path(); path.getElements().addAll(moveTo, line1, cubicCurveTo, vLine); PathTransition pathTransition = new PathTransition(); pathTransition.setDuration(Duration.millis(1000)); pathTransition.setNode(circle); pathTransition.setPath(path); pathTransition.setOrientation( PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT); pathTransition.setCycleCount(50); pathTransition.setAutoReverse(false); //将操作设置为按钮 button.setOnAction(e -> { pathTransition.play(); }); //设置舞台 Group root = new Group(button, circle); Scene scene = new Scene(root, 595, 220, Color.BEIGE); stage.setTitle("Button Action"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出结果