JavaFX | MenuBar и меню

Опубликовано: 13 Февраля, 2022

Меню - это всплывающее меню, которое содержит несколько пунктов меню, которые отображаются, когда пользователь щелкает меню. Пользователь может выбрать пункт меню, после чего меню переходит в скрытое состояние.

MenuBar обычно размещается в верхней части экрана, который содержит несколько меню. JavaFX MenuBar обычно представляет собой реализацию строки меню.

Конструкторами класса MenuBar являются:

  1. MenuBar () : создает новую пустую строку меню.
  2. MenuBar (Меню… m) : создает новую строку меню с заданным набором меню.

Конструкторами класса Menu являются:

  1. Menu () : создает пустое меню
  2. Menu (String s) : создает меню со строкой в качестве метки.
  3. Меню (String s, Node n) : создает меню и устанавливает отображаемый текст с указанным текстом и устанавливает графический узел для данного узла.
  4. Меню (String s, Node n, MenuItem… i) : создает меню и устанавливает отображаемый текст с указанным текстом, графический узел для данного узла и вставляет данные элементы в список элементов.

Обычно используемые методы:

метод объяснение
getItems () возвращает пункты меню
Спрятать() скрыть меню
Показать() показать меню
getMenus () Меню, отображаемые в этой MenuBar.
isUseSystemMenuBar () Получает значение свойства useSystemMenuBar
setUseSystemMenuBar (логическое значение v) Устанавливает значение свойства useSystemMenuBar.
setOnHidden (обработчик событий v) Устанавливает значение свойства onHidden.
setOnHiding (обработчик событий v) Устанавливает значение свойства onHiding.
setOnShowing (EventHandler v) Устанавливает значение свойства onShowing.
setOnShown (EventHandler v Устанавливает значение свойства onShown.

Below programs illustrate the MenuBar and Menu class:

  1. Java program to create a menu bar and add menu to it and also add menuitems to the menu: This program creates a menubar indicated by the name mb. A menu will be created by name m and 3 menuitems m1, m2, m3 will be added to the menu m and the menu m will be added to menubar mb. The menubar will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a VBox is created, on which addChildren() method is called to attach the menubar inside the scene. Finally, the show() method is called to display the final results.
    // Java program to create a menu bar and add
    // menu to it and also add menuitems to menu
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.*;
    import javafx.stage.Stage;
    import javafx.scene.control.Alert.AlertType;
    import java.time.LocalDate;
    public class MenuBar_1 extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating MenuBar");
      
            // create a menu
            Menu m = new Menu("Menu");
      
            // create menuitems
            MenuItem m1 = new MenuItem("menu item 1");
            MenuItem m2 = new MenuItem("menu item 2");
            MenuItem m3 = new MenuItem("menu item 3");
      
            // add menu items to menu
            m.getItems().add(m1);
            m.getItems().add(m2);
            m.getItems().add(m3);
      
            // create a menubar
            MenuBar mb = new MenuBar();
      
            // add menu to menubar
            mb.getMenus().add(m);
      
            // create a VBox
            VBox vb = new VBox(mb);
      
            // create a scene
            Scene sc = new Scene(vb, 500, 300);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

  2. Java program to create a menu bar and add a menu to it and also add menu items to menu and also add an event listener to handle the events: This program creates a menubar indicated by the name mb. A menu will be created by name m and 3 menuitems m1, m2, m3 will be added to the menu m and the menu m will be added to the menubar mb. The menubar will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a VBox is created, on which addChildren() method is called to attach the menubar inside the scene. Finally, the show() method is called to display the final results. A label will also be created that will show which menuitem is selected. An action event will be created to process the action when the menu item is clicked by the user.
    // Java program to create a menu bar and add menu to
    // it and also add menuitems to menu and also add
    // an event listener to handle the events
    import javafx.application.Application;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.layout.*;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.control.*;
    import javafx.stage.Stage;
    import javafx.scene.control.Alert.AlertType;
    import java.time.LocalDate;
    public class MenuBar_2 extends Application {
      
        // launch the application
        public void start(Stage s)
        {
            // set title for the stage
            s.setTitle("creating MenuBar");
      
            // create a menu
            Menu m = new Menu("Menu");
      
            // create menuitems
            MenuItem m1 = new MenuItem("menu item 1");
            MenuItem m2 = new MenuItem("menu item 2");
            MenuItem m3 = new MenuItem("menu item 3");
      
            // add menu items to menu
            m.getItems().add(m1);
            m.getItems().add(m2);
            m.getItems().add(m3);
      
            // label to display events
            Label l = new Label(" "
                                + "no menu item selected");
      
            // create events for menu items
            // action event
            EventHandler<ActionEvent> event = new EventHandler<ActionEvent>() {
                public void handle(ActionEvent e)
                {
                    l.setText(" " + ((MenuItem)e.getSource()).getText() + 
                                                                   " selected");
                }
            };
      
            // add event
            m1.setOnAction(event);
            m2.setOnAction(event);
            m3.setOnAction(event);
      
            // create a menubar
            MenuBar mb = new MenuBar();
      
            // add menu to menubar
            mb.getMenus().add(m);
      
            // create a VBox
            VBox vb = new VBox(mb, l);
      
            // create a scene
            Scene sc = new Scene(vb, 500, 300);
      
            // set the scene
            s.setScene(sc);
      
            s.show();
        }
      
        public static void main(String args[])
        {
            // launch the application
            launch(args);
        }
    }

    Output:

    Note: The above programs might not run in an online IDE please use an offline converter.

    Reference:

    • https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/Menu.html
    • https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/MenuBar.html

    Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.