Wednesday 16 May 2018

JavaFX: Label: Event handling

JavaFX provides many setOn* methods to handle mouse, keyboard events.

For example,
                  label1.setOnMouseEntered((MouseEvent e) -> {
                           label1.setScaleX(1.5);
                           label1.setScaleY(1.5);
                  });

                  label1.setOnMouseExited((MouseEvent e) -> {
                           label1.setScaleX(1);
                           label1.setScaleY(1);
                  });

LabelApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import java.io.FileNotFoundException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class LabelApp extends Application {
 @Override
 public void start(Stage primaryStage) throws FileNotFoundException {

  Label label1 = new Label("Hello World");
  label1.setFont(new Font("Arial", 30));
  label1.setRotate(300);
  label1.setTranslateY(60);

  label1.setOnMouseEntered((MouseEvent e) -> {
   label1.setScaleX(1.5);
   label1.setScaleY(1.5);
  });

  label1.setOnMouseExited((MouseEvent e) -> {
   label1.setScaleX(1);
   label1.setScaleY(1);
  });
  
  VBox vBox = new VBox(10, label1);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 400, 400);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Label Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(LabelApp.class, args);
 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment