JavaFX example to set action to the "exit" MenuItem

JavaFXObject Oriented ProgrammingProgramming

A menu is a list of options or commands presented to the user, typically menus contain items that perform some action. The contents of a menu are known as menu items.

You can create a menu item by instantiating the javafx.scene.control.MenuItem class.

Setting action to a ContextMenu

The Menu 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.

To set action on a menu you need to −

  • Instantiate the Menu class.

  • Create a MenuItem objects and add them to the Menu.

  • Invoke the setOnAction() method the menu item object.

To the setOnAction() method you need to pass an EventHandler<ActionEvent> object wrapping the code for the action to perform within it. For exit operation, since you need to close the application you can use System.exit(0).

Example

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ExitMenuItemAction extends Application {
   @Override
   public void start(Stage stage) {
      //Creating image view files
      ImageView imgView1 = new ImageView("UIControls/open.png");
      imgView1.setFitWidth(20);
      imgView1.setFitHeight(20);
      ImageView imgView2 = new ImageView("UIControls/Save.png");
      imgView2.setFitWidth(20);
      imgView2.setFitHeight(20);
      ImageView imgView3 = new ImageView("UIControls/Exit.png");
      imgView3.setFitWidth(20);
      imgView3.setFitHeight(20);
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating menu Items
      MenuItem item1 = new MenuItem("Open File", imgView1);
      MenuItem item2 = new MenuItem("Save file", imgView2);
      MenuItem item3 = new MenuItem("Exit", imgView3);
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(item1, item2, item3);
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      menuBar.setTranslateX(200);
      menuBar.setTranslateY(20);
      //Setting action to exit menu item
      item3.setOnAction((ActionEvent t) -> {
         System.exit(0);
      });
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
      stage.setTitle("Menu Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 20-May-2020 10:59:32
Advertisements