How to embed nodes in a JavaFX MenuItem?

JavaFXObject Oriented ProgrammingProgramming

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 a node as a 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 embed a node as a menu item you need to create an object of it by instantiating the respective class and pass it as a parameter to the setGraphic() Method.

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.scene.paint.PhongMaterial;
import javafx.scene.shape.CullFace;
import javafx.scene.shape.DrawMode;
import javafx.scene.shape.Sphere;
import javafx.stage.Stage;
public class NodeAsMenuItem extends Application {
   @Override
   public void start(Stage stage) {
      //Drawing a Sphere
      Sphere sphere = new Sphere();
      sphere.setRadius(12.0);
      sphere.setDrawMode(DrawMode.LINE);
      //Setting other properties
      sphere.setCullFace(CullFace.BACK);
      sphere.setDrawMode(DrawMode.FILL);
      PhongMaterial material = new PhongMaterial();
      material.setDiffuseColor(Color.BROWN);
      sphere.setMaterial(material);
      //Creating menu
      Menu fileMenu = new Menu("File");
      //Creating menu item
      MenuItem item = new MenuItem("Open");
      //Setting slider as a menu item
      item.setGraphic(sphere);
      //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

raja
Published on 20-May-2020 10:27:10
Advertisements