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 RadioMenuItem 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 and a menu bar holds multiple menus.
JavaFx supports three kinds of menu items namely − check menu item, custom menu item, and, radio menu item.
RadioMenuItem
A RadioMenuItem is a special MenuItem that has a checkmark (tick) similar to a checkbox. This has two states selected (with a checkmark) and unselected (without checkmark). It is represented by the javafx.scene.control.RadioMenuItem class.
You can add a bunch of radio-menu-items to a toggle group just like a toggle button or a radio button. If not added, it acts like a CheckMenuItem.
To add a CheckMenuItem in the menu −
Instantiate the Menu class.
Instantiate the RadioMenuItem class.
Add all the created check menu menu-item to the menu as −
menu.getItems().add(item);
Create a menu bar by instantiating the MenuBar class.
Add the menu to the menu bar as −
menuBar.getMenus().add(menu);
Add the menu bar to the scene.
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.RadioMenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class RadioMenuItemExample extends Application {
@Override
public void start(Stage stage) {
//Creating a menu
Menu fileMenu = new Menu("File");
//Creating menu Items
Menu view = new Menu("Align");
MenuItem edit = new MenuItem("Edit");
MenuItem exit = new MenuItem("Exit");
//Creating menu items for the sub item edit
RadioMenuItem sub1 = new RadioMenuItem("Right");
RadioMenuItem sub2 = new RadioMenuItem("Left");
RadioMenuItem sub3 = new RadioMenuItem("Center");
//Adding toggle group to the view menu item
view.getItems().addAll(sub1, sub2, sub3);
//Creating a separator
SeparatorMenuItem sep = new SeparatorMenuItem();
//Adding all the menu items to the menu
fileMenu.getItems().addAll(edit, view, sep, exit);
//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
