JavaFX MenuItem generic EventHandler

Introduction

To Create generic EventHandler for MenuItem in JavaFX

// Create a handler for the tool bar buttons.
EventHandler<ActionEvent> btnHandler = new EventHandler<ActionEvent>() {
  public void handle(ActionEvent ae) {
    response.setText(((MenuItem) ae.getTarget()).getText());
  }//from w  ww. ja  va 2s .  com
};

// Set the tool bar button action event handlers.
cut.setOnAction(btnHandler);
copy.setOnAction(btnHandler);
paste.setOnAction(btnHandler);

Full source

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.input.ContextMenuEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {
  //Create a label that will report the selection.
  private Label response = new Label("Menu Demo");

  public static void main(String[] args) {
    launch(args);//w ww  .j  a v  a  2  s . co  m
  }
  public void start(Stage myStage) {    myStage.setTitle("Menus from java2s.com");

    // Use a BorderPane for the root node.
    BorderPane rootNode = new BorderPane();

    Scene myScene = new Scene(rootNode, 300, 300);

    myStage.setScene(myScene);

    // Create the edit context menu items.
    MenuItem cut = new MenuItem("Cut");
    MenuItem copy = new MenuItem("Copy");
    MenuItem paste = new MenuItem("Paste");

    // Create a context (i.e., pop up) menu that shows edit options.
    ContextMenu editMenu = new ContextMenu(cut, copy, paste);
    // Create a handler for the tool bar buttons.
    EventHandler<ActionEvent> btnHandler = new EventHandler<ActionEvent>() {
      public void handle(ActionEvent ae) {
        response.setText(((MenuItem) ae.getTarget()).getText());
      }
    };

    // Set the tool bar button action event handlers.
    cut.setOnAction(btnHandler);
    copy.setOnAction(btnHandler);
    paste.setOnAction(btnHandler);
 
    rootNode.setCenter(response);

    // Add the context menu to the entire scene graph.
    rootNode.setOnContextMenuRequested(new EventHandler<ContextMenuEvent>() {
      public void handle(ContextMenuEvent ae) {
        // Popup menu at the location of the right click.
        editMenu.show(rootNode, ae.getScreenX(), ae.getScreenY());
      }
    });
    
    myStage.show();
  }
}



PreviousNext

Related