Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a MenuBar in JavaFX?
A menu bar is a user interface element that holds all the menus, it is usually placed on the top. In JavaFX the javafx.scene.control.MenuBar class represents a menu bar. You can create a menu bar by instantiating this class.
A menu is a list of options or commands presented to the user. In JavaFX a menu is represented by the javafx.scene.control.Menu class.
Adding menus to the MenuBar
The MenuBar class contains an observable list which holds all the menus, you can get this list by invoking the getMenus() method.
You can create the required number of menus and add them to the observable list using the addAll() method as −
menuBar.getMenus().addAll(file, fileList, skin);
You can also pass them as parameters to the constructor while instantiating the MenuBar class as −
MenuBar menuBar = new menuBar(menu1, menu2, menu3);
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.paint.Color;
import javafx.stage.Stage;
public class MenuBarExample extends Application {
public void start(Stage stage) {
//Creating file menu
Menu file = new Menu("File");
//Creating file menu items
MenuItem item1 = new MenuItem("Add Files");
MenuItem item2 = new MenuItem("Start Converting");
MenuItem item3 = new MenuItem("Stop Converting");
MenuItem item4 = new MenuItem("Remove File");
MenuItem item5 = new MenuItem("Exit");
//Adding all the menu items to the file menu
file.getItems().addAll(item1, item2, item3, item4, item5);
//Creating FileList menu
Menu fileList = new Menu("File List");
//Creating fileList menu items
MenuItem item6 = new MenuItem("Select All");
MenuItem item7 = new MenuItem("Invert Selection");
MenuItem item8 = new MenuItem("Remove");
//Adding all the items to File List menu
fileList.getItems().addAll(item6, item7, item8);
//Creating Skin menu
Menu skin = new Menu("_Skin");
//Creating skin menu items
MenuItem item9 = new MenuItem("Blue");
MenuItem item10 = new MenuItem("Red");
//Adding all elements to Skin menu
skin.getItems().addAll(item9, item10);
//Creating a menu bar
MenuBar menuBar = new MenuBar();
menuBar.setTranslateX(200);
menuBar.setTranslateY(20);
//Adding all the menus to the menu bar
menuBar.getMenus().addAll(file, fileList, skin);
//Setting the stage
Group root = new Group(menuBar);
Scene scene = new Scene(root, 595, 200, Color.BEIGE);
stage.setTitle("Menu Bar Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
Output

Advertisements