1  import javafx.application.Application;
  2  import javafx.event.ActionEvent;
  3  import javafx.event.EventHandler;
  4  import javafx.geometry.Pos;
  5  import javafx.scene.Scene;
  6  import javafx.scene.control.Button;
  7  import javafx.scene.layout.BorderPane;
  8  import javafx.scene.layout.HBox;
  9  import javafx.scene.layout.Pane;
 10  import javafx.scene.text.Text;
 11  import javafx.stage.Stage;
 12  
 13  public class AnonymousHandlerDemo extends Application {
 14    @Override // Override the start method in the Application class
 15    public void start(Stage primaryStage) {
 16      Text text = new Text(40, 40, "Programming is fun");
 17      Pane pane = new Pane(text);
 18      
 19      // Hold four buttons in an HBox
 20      Button btUp = new Button("Up");
 21      Button btDown = new Button("Down");
 22      Button btLeft = new Button("Left");
 23      Button btRight = new Button("Right");
 24      HBox hBox = new HBox(btUp, btDown, btLeft, btRight);
 25      hBox.setSpacing(10);
 26      hBox.setAlignment(Pos.CENTER);
 27      
 28      BorderPane borderPane = new BorderPane(pane);
 29      borderPane.setBottom(hBox);
 30      
 31      // Create and register the handler
 32      btUp.setOnAction(new EventHandler<ActionEvent>() {
 33        @Override // Override the handle method
 34        public void handle(ActionEvent e) {
 35          text.setY(text.getY() > 10 ? text.getY() - 5 : 10);
 36        }
 37      });
 38  
 39      btDown.setOnAction(new EventHandler<ActionEvent>() {
 40        @Override // Override the handle method
 41        public void handle(ActionEvent e) {
 42          text.setY(text.getY() < pane.getHeight() ? 
 43            text.getY() + 5 : pane.getHeight());
 44        }
 45      });
 46      
 47      btLeft.setOnAction(new EventHandler<ActionEvent>() {
 48        @Override // Override the handle method
 49        public void handle(ActionEvent e) {
 50          text.setX(text.getX() > 0 ? text.getX() - 5 : 0);
 51        }
 52      });
 53      
 54      btRight.setOnAction(new EventHandler<ActionEvent>() {
 55        @Override // Override the handle method
 56        public void handle(ActionEvent e) {
 57          text.setX(text.getX() < pane.getWidth() - 100?
 58            text.getX() + 5 : pane.getWidth() - 100);
 59        }
 60      });
 61  
 62      // Create a scene and place it in the stage
 63      Scene scene = new Scene(borderPane, 400, 350);
 64      primaryStage.setTitle("AnonymousHandlerDemo"); // Set title
 65      primaryStage.setScene(scene); // Place the scene in the stage
 66      primaryStage.show(); // Display the stage
 67    }
 68    
 69    /**
 70     * The main method is only needed for the IDE with limited
 71     * JavaFX support. Not needed for running from the command line.
 72     */
 73    public static void main(String[] args) {
 74      launch(args);
 75    }
 76  }