How to create context menus in JavaFX?


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.

Context Menu

A context menu is a popup menu that appears on interacting with the UI elements in the application. The best example for this is the menu appears in your system when you right-click on the mouse. You can create a context menu by instantiating the javafx.scene.control.ContextMenu class.

Just like a menu, after creating a context menu, you need to add MenuItems to it. You can set ContextMenu to any object of the javafx.scene.control class, using the setContextMenu() method.

Typically, these content menus appear when you “right-click” on the attached control.

Example

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class ContextMenuExample extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating the image view
      Button button = new Button("Hello");
      TextField textField = new TextField();
      //Creating a context menu
      ContextMenu contextMenu = new ContextMenu();
      //Creating the menu Items for the context menu
      MenuItem item1 = new MenuItem("option1");
      MenuItem item2 = new MenuItem("option2");
      contextMenu.getItems().addAll(item1, item2);
      //Adding the context menu to the button and the text field
      textField.setContextMenu(contextMenu);
      button.setContextMenu(contextMenu);
      HBox layout = new HBox(20);
      layout.setPadding(new Insets(15, 15, 15, 100));
      layout.getChildren().addAll(textField, button);
      //Setting the stage
      Scene scene = new Scene(new Group(layout), 595, 150, Color.BEIGE);
      stage.setTitle("CustomMenuItem");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 20-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements