用 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);
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP