JavaFX is a powerful framework for building rich graphical user interfaces (GUIs) in Java. One essential component of GUI design is menus. Menus provide a structured way to organize various commands and options, making it easier for users to interact with your application. In this article, we’ll explore JavaFX menus, demonstrate how to create different types of menus, and provide well-structured code examples.
JavaFX provides several classes to create menus and related components. The core classes include MenuBar, Menu, and MenuItem. Additionally, we have the ContextMenu class for context menus that appear on right-click.
Creating a Simple MenuBar
Let’s start by creating a basic MenuBar with a single menu and a menu item:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private final BorderPane parent = new BorderPane();
@Override
public void start(Stage stage) throws Exception {
this.setupStage(stage);
}
@Override
public void init() throws Exception {
super.init();
this.buildUI();
}
private void buildUI() {
// Create MenuBar
MenuBar menuBar = new MenuBar();
// Create File Menu
Menu fileMenu = new Menu("File");
// Create Menu Item
MenuItem exitMenuItem = new MenuItem("Exit");
// Add Exit Menu Item to the File Menu
fileMenu.getItems().add(exitMenuItem);
// Add File menu to the MenuBar
menuBar.getMenus().add(fileMenu);
// Add MenuBar to the Top of the BorderPane
this.parent.setTop(menuBar);
}
private void setupStage(Stage stage) {
Scene scene = new Scene(this.parent, 640.0, 480.0);
// Sets the stage title
stage.setTitle("JavaFX Menus");
// Set the stage scene
stage.setScene(scene);
// Center stage on screen
stage.centerOnScreen();
// Show stage on screen
stage.show();
}
}
Adding MenuItems and Submenus
A menu can have multiple items, and it can also contain submenus. Let’s create a menu with multiple items and a submenu:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private final BorderPane parent = new BorderPane();
@Override
public void start(Stage stage) throws Exception {
this.setupStage(stage);
}
@Override
public void init() throws Exception {
super.init();
this.buildUI();
}
private void buildUI() {
// Create the MenuBar
MenuBar menuBar = new MenuBar();
// Create the File Menu
Menu fileMenu = new Menu("File");
// Create Menu Items for File Menu
MenuItem openMenuItem = new MenuItem("Open");
MenuItem saveMenuItem = new MenuItem("Save");
MenuItem closeMenuItem = new MenuItem("Close");
// Add Menu Items to the File menu
fileMenu.getItems().addAll(openMenuItem, saveMenuItem, closeMenuItem);
// Create the Edit Menu with a Submenu
Menu editMenu = new Menu("Edit");
// Create Menu Items for Edit Menu
MenuItem cutMenuItem = new MenuItem("Cut");
MenuItem copyMenuItem = new MenuItem("Copy");
MenuItem pasteMenuItem = new MenuItem("Paste");
// Create the Format Menu with Submenu
Menu formatMenu = new Menu("Format");
// Create Format Submenu Items
MenuItem fontMenuItem = new MenuItem("Font");
MenuItem uppercaseMenuItem = new MenuItem("UPPERCASE");
MenuItem lowercaseMenuItem = new MenuItem("lowercase");
// Add Submenu Items to the Format Menu
formatMenu.getItems().addAll(fontMenuItem, uppercaseMenuItem, lowercaseMenuItem);
// Add Menu Items to the Edit menu
editMenu.getItems().addAll(cutMenuItem, copyMenuItem, pasteMenuItem, formatMenu);
// Add both menus to the MenuBar
menuBar.getMenus().addAll(fileMenu, editMenu);
// Add MenuBar to the Top of the BorderPane
this.parent.setTop(menuBar);
}
private void setupStage(Stage stage) {
Scene scene = new Scene(this.parent, 640.0, 480.0);
// Set the stage title
stage.setTitle("JavaFX Menus");
// Set the stage scene
stage.setScene(scene);
// Center the stage on the screen
stage.centerOnScreen();
// Show the stage on the screen
stage.show();
}
}
Handling Menu Item Actions
Menu items can trigger actions when selected by the user. Let’s update the previous example to handle the action of the “Exit” menu item:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private final BorderPane parent = new BorderPane();
@Override
public void start(Stage stage) throws Exception {
this.setupStage(stage);
}
@Override
public void init() throws Exception {
super.init();
this.buildUI();
}
private void buildUI() {
// Create MenuBar
MenuBar menuBar = new MenuBar();
// Create File Menu
Menu fileMenu = new Menu("File");
// Create Menu Item with action
MenuItem exitMenuItem = new MenuItem("Exit");
exitMenuItem.setOnAction(e -> {
// Show a confirmation dialog before exiting
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Exit");
alert.setHeaderText("Confirm Exit");
alert.setContentText("Are you sure you want to exit?");
alert.showAndWait().ifPresent(response -> {
if (response == ButtonType.OK) {
// Close application
Platform.exit();
}
});
});
fileMenu.getItems().add(exitMenuItem);
// Add File menu to the MenuBar
menuBar.getMenus().add(fileMenu);
// Add MenuBar to the Top of the BorderPane
this.parent.setTop(menuBar);
}
private void setupStage(Stage stage) {
Scene scene = new Scene(this.parent, 640.0, 480.0);
// Set the stage title
stage.setTitle("JavaFX Menus");
// Set the stage scene
stage.setScene(scene);
// Center the stage on the screen
stage.centerOnScreen();
// Show the stage on the screen
stage.show();
}
}
Context Menus
Context menus appear when the user right-clicks on a node. Let’s see an example of creating a context menu for a Button:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private final BorderPane parent = new BorderPane();
@Override
public void start(Stage stage) throws Exception {
this.setupStage(stage);
}
@Override
public void init() throws Exception {
super.init();
this.buildUI();
}
private void buildUI() {
// Create a Button
Button button = new Button("Right-click me!");
// Create a ContextMenu
ContextMenu contextMenu = new ContextMenu();
// Create MenuItem for the context menu
MenuItem item1 = new MenuItem("Item 1");
MenuItem item2 = new MenuItem("Item 2");
MenuItem item3 = new MenuItem("Item 3");
// Add MenuItems to the ContextMenu
contextMenu.getItems().addAll(item1, item2, item3);
// Attach the context menu to the button
button.setContextMenu(contextMenu);
this.parent.setCenter(button);
}
private void setupStage(Stage stage) {
Scene scene = new Scene(this.parent, 640.0, 480.0);
// Set the stage title
stage.setTitle("JavaFX Menus");
// Set the stage scene
stage.setScene(scene);
// Center the stage on the screen
stage.centerOnScreen();
// Show the stage on the screen
stage.show();
}
}
Accelerators and Mnemonics
JavaFX menus support accelerators (keyboard shortcuts) and mnemonics (keyboard shortcuts for menu items). Let’s see an example of adding an accelerator to a menu item and a mnemonic to a menu:
import javafx.application.Application;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private final BorderPane parent = new BorderPane();
@Override
public void start(Stage stage) throws Exception {
this.setupStage(stage);
}
@Override
public void init() throws Exception {
super.init();
this.buildUI();
}
private void buildUI() {
// Create MenuBar
MenuBar menuBar = new MenuBar();
// Create the File Menu with mnemonic (Alt+F)
Menu fileMenu = new Menu("_File");
fileMenu.setMnemonicParsing(true);
// Create Menu Item with action
MenuItem exitMenuItem = new MenuItem("Exit");
exitMenuItem.setAccelerator(KeyCodeCombination.keyCombination("Ctrl+X"));
exitMenuItem.setOnAction(e -> {
// Show a confirmation dialog before exiting
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Exit");
alert.setHeaderText("Confirm Exit");
alert.setContentText("Are you sure you want to exit?");
alert.showAndWait().ifPresent(response -> {
if (response == ButtonType.OK) {
// Close application
Platform.exit();
}
});
});
fileMenu.getItems().add(exitMenuItem);
// Add File menu to the MenuBar
menuBar.getMenus().add(fileMenu);
// Add MenuBar to the Top of the BorderPane
this.parent.setTop(menuBar);
}
private void setupStage(Stage stage) {
Scene scene = new Scene(this.parent, 640.0, 480.0);
// Set the stage title
stage.setTitle("JavaFX Menus");
// Set the stage scene
stage.setScene(scene);
// Center the stage on the screen
stage.centerOnScreen();
// Show the stage on the screen
stage.show();
}
}
Customizing Menu Appearance
You can customize the appearance of menus using CSS to match your application’s style. Below is a simple example of changing the font and background color of a menu:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class Main extends Application {
private final BorderPane parent = new BorderPane();
@Override
public void start(Stage stage) throws Exception {
this.setupStage(stage);
}
@Override
public void init() throws Exception {
super.init();
this.buildUI();
}
private void buildUI() {
// Create MenuBar
MenuBar menuBar = new MenuBar();
// Styling the MenuBar
menuBar.setStyle("-fx-background-color: cornflowerblue;");
// Create File Menu
Menu fileMenu = new Menu("File");
// Styling the File Menu
fileMenu.setStyle("-fx-font-family: Arial; -fx-font-size: 20px;");
// Add File menu to the MenuBar
menuBar.getMenus().add(fileMenu);
// Add MenuBar to the Top of the BorderPane
this.parent.setTop(menuBar);
}
private void setupStage(Stage stage) {
Scene scene = new Scene(this.parent, 640.0, 480.0);
// Set the stage title
stage.setTitle("JavaFX Menus");
// Set the stage scene
stage.setScene(scene);
// Center the stage on the screen
stage.centerOnScreen();
// Show the stage on the screen
stage.show();
}
}
Conclusion
JavaFX menus are essential for organizing and presenting various options and actions in your application. With the examples provided in this article, you should now have a good understanding of how to create different types of menus, add menu items and submenus, handle menu item actions, create context menus, and customize the menu appearance. Explore further and experiment with JavaFX menus to build intuitive and user-friendly graphical interfaces for your Java applications.
I hope you found this code informative and useful. If you would like to receive more content, please consider subscribing to our newsletter!