JavaFX example to set behavior to a button


A button controls in user interface applications, in general, on clicking the button it performs the respective action. You can create a Button by instantiating the javafx.scene.control.Button class.

The Button class inherits a property named onAction from the javafx.scene.control.ButtonBase class, which is of the type ObjectProperty<EventHandler<ActionEvent>>. This property represents the action that is invoked whenever you press the button. You can set the value to this property using the setOnAction() method.

One of the ways to set the action to a button is using the OnAction() method.

Example

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);
   }
}

Output

Updated on: 16-May-2020

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements