如何在JavaFX MenuItem中嵌入节点?
菜单是提供给用户的选项或命令的列表。在JavaFX中,菜单由javafx.scene.control.Menu类表示,您可以通过实例化该类来创建菜单。
菜单项是菜单中的一个选项,它由javafx.scene.control.MenuItem类(Menu类的超类)表示。您可以将文本或图形显示为菜单项,然后向其中添加所需的阳离子。
将节点设置为菜单项
该菜单项类有一个名为属性的图形,这是类型节点;这指定当前菜单项的可选图形。您可以使用setGraphic()方法将值设置为此属性。
要将节点嵌入为菜单项,您需要通过实例化相应的类来创建其对象,并将其作为参数传递给setGraphic()方法。
示例
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);
}
}输出结果