JavaFX支持三种菜单项,即-检查菜单项,自定义菜单项和单选菜单项。
RadioMenuItem是一个特殊的MenuItem,具有类似于复选框的复选标记(勾号)。这有两个状态处于选中状态(带有选中标记)和未选中状态(没有选中标记)。它由javafx.scene.control.RadioMenuItem类表示。
您可以将多个单选菜单项添加到切换组,就像切换按钮或单选按钮一样。
以下JavaFX示例演示了广播菜单项切换组的创建
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.RadioMenuItem; import javafx.scene.control.SeparatorMenuItem; import javafx.scene.control.ToggleGroup; import javafx.scene.paint.Color; import javafx.stage.Stage; public class RadioMenuItem_Toggle extends Application { @Override public void start(Stage stage) { //Creating a menu Menu fileMenu = new Menu("File"); //Creating menu Items Menu view = new Menu("Align"); MenuItem edit = new MenuItem("Edit"); MenuItem exit = new MenuItem("Exit"); //Creating menu items for the sub item edit RadioMenuItem sub1 = new RadioMenuItem("Right"); RadioMenuItem sub2 = new RadioMenuItem("Left"); RadioMenuItem sub3 = new RadioMenuItem("Center"); //Adding the Sub menu items to a toggle group ToggleGroup group = new ToggleGroup(); sub1.setToggleGroup(group); sub2.setToggleGroup(group); sub3.setToggleGroup(group); //Adding toggle group to the view menu item view.getItems().addAll(sub1, sub2, sub3); //Creating a separator SeparatorMenuItem sep = new SeparatorMenuItem(); //Adding all the menu items to the menu fileMenu.getItems().addAll(edit, view, sep, exit); //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 Example"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
输出结果