How to add the slider to a menu item in JavaFX?

JavaFX slider

JavaFX provides a class known as Slider, this represents a slider component that displays a continuous range of values. This contains a track on which the number values are displayed. Along the track, there is a thumb pointing to the numbers. You can provide the maximum, minimum, and initial values of the slider.

In JavaFX you can create a slider by instantiating the javafx.scene.control.Slider class.

Menu Item

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, you can create a menu by instantiating this class.

A menu item is an option in the menu it is represented by the javafx.scene.control.MenuItem class, a superclass of the Menu class. You can display a text or a graphic as a menu item and add the desired cation to it.

Setting slider as menu item −

The MenuItem class has a property named graphic this is of the type Node; this specifies the optional graphic for the current menu-item. You can set the value to this property using the setGraphic() method.

To add slider as a menu item create a slider object, invoke the setGrapic() method by passing this object as a parameter.


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.Slider;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SliderAsMenuItem extends Application {
   public void start(Stage stage) {
      //Creating a slider
      Slider slider = new Slider(0, 100, 0);
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating menu item
      MenuItem item = new MenuItem();
      //Setting slider as a menu item
      //Adding all the menu items to the menu
      //Creating a menu bar and adding menu to it.
      MenuBar menuBar = new MenuBar(fileMenu);
      //Setting the stage
      Group root = new Group(menuBar);
      Scene scene = new Scene(root, 595, 200, Color.BEIGE);
   public static void main(String args[]){