用 JavaScript 设置按钮行为
在用户界面应用程序中按钮控件一般情况下会在单击按钮时执行相应操作。你可以通过实例化javafx.scene.control.Button 类来创建一个按钮。
Button 类继承了 javafx.scene.control.ButtonBase 类的名为 onAction 的属性,类型为 ObjectProperty<EventHandler<ActionEvent>>。此属性表示每当你按下按钮就会调用的操作。你可以使用 setOnAction() 方法为此属性设置值。
使用 OnAction() 方法将操作设置到按钮的方法之一。
示例
public class ButtonAction extends Application { @Override public void start(Stage stage) { //Creating a Button Button button = new Button("Play"); button.setTranslateX(25); button.setTranslateY(150); //Creating a circle Circle circle = new Circle(150, 150, 30); circle.setFill(Color.BROWN); //Setting path to the circle 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); //Setting action to the button button.setOnAction(e -> { pathTransition.play(); }); //Setting the stage 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); } }
输出
广告