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.

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.Slider;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class SliderAsMenuItem extends Application {
   @Override
   public void start(Stage stage) {
      //Creating a slider
      Slider slider = new Slider(0, 100, 0);
      slider.setShowTickLabels(true);
      slider.setShowTickMarks(true);
      slider.setMajorTickUnit(25);
      slider.setBlockIncrement(10);
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating menu item
      MenuItem item = new MenuItem();
      //Setting slider as a menu item
      item.setGraphic(slider);
      //Adding all the menu items to the menu
      fileMenu.getItems().addAll(item);
      //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");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 19-May-2020

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements