如何在 JavaFX 中切換選單項?


JavaFX 支援三類選單項,分別是複選框選單項、自定義選單項和單選按鈕選單項。

單選按鈕選單項是一個帶有複選框樣式複選標記的特殊選單項。它有兩種狀態,選中(帶複選標記)和未選中(無複選標記)。它由 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);
   }
}

輸出

更新日期:20-5-2020

607 瀏覽量

開啟你的 職業道路

透過完成課程並獲得認證

開始
廣告