How to add a separator to a Menu in JavaFX?

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.

To add a separator to a menu, JavaFX provides a special class named javafx.scene.control.Separator. Using this class, you can create a MenuItem that embeds a horizontal separator within it. This comes handy whenever you need to separate menu items.

Once you create a SeperatorMenuItem you can add its object to the menu using the add() or, addAll() method, along with the other menu items.

Example

import javafx.application.Application;
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.control.SeparatorMenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SeperatorsToMenu extends Application {
   public void start(Stage stage) {
      //Creating a menu
      Menu fileMenu = new Menu("File");
      //Creating menu Items
      fileMenu.setMnemonicParsing(true);
      MenuItem item1 = new MenuItem("Add Files");
      MenuItem item2 = new MenuItem("Remove File");
      MenuItem item3 = new MenuItem("Start Converting");
      MenuItem item4 = new MenuItem("Stop Converting");
      MenuItem item5 = new MenuItem("Exit");
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(item1, item2, item3, item4, item5);
      //Creating separator menu items
      SeparatorMenuItem sep = new SeparatorMenuItem();
      //Adding separator objects to menu
      fileMenu.getItems().add(4, sep);
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      menuBar.setTranslateX(200);
      menuBar.setTranslateY(20);
      //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:52:04
Advertisements