如何在 JavaFX MenuItem 中嵌入节点?
菜单是提供给用户的一系列选项或命令。在 JavaFX 中,菜单由 javafx.scene.control.Menu 类表示,可以通过实例化此类来创建一个菜单。
菜单项是菜单中的一种选项,它由 javafx.scene.control.MenuItem 类表示,此类是 Menu 类的超类。你可以显示文本或图形作为菜单项,并向其添加所需的按钮。
设置节点作为菜单项
MenuItem 类有一个名为 graphic 的属性,其类型为 Node,这指定了当前菜单项的可选图形。你可以使用 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); } }
Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.
输出
广告