如何在 JavaFX 中建立 ButtonBar?


ButtonBar 其實只是可以排列按鈕的 HBox。通常,ButtonBar 上的按鈕是特定於作業系統的。你可以透過例項化 javafx.scene.control.ButtonBar 類來建立一個按鈕欄。

示例

以下示例演示瞭如何建立 ButtonBar

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class ButtonBarExample extends Application {
   @Override
   public void start(Stage stage) {
      //Creating toggle buttons
      ToggleButton button1 = new ToggleButton("Java");
      button1.setPrefSize(60, 40);
      ToggleButton button2 = new ToggleButton("Python");
      button2.setPrefSize(60, 40);
      ToggleButton button3 = new ToggleButton("C++");
      button3.setPrefSize(60, 40);
      //Adding the buttons to a toggle group
      ToggleGroup group = new ToggleGroup();
      button1.setToggleGroup(group);
      button2.setToggleGroup(group);
      button3.setToggleGroup(group);
      //Create a ButtonBar
      ButtonBar buttonBar = new ButtonBar();
      //Adding the buttons to the button bar
      ButtonBar.setButtonData(button1, ButtonData.APPLY);
      ButtonBar.setButtonData(button2, ButtonData.APPLY);
      ButtonBar.setButtonData(button3, ButtonData.APPLY);
      buttonBar.getButtons().addAll(button1, button2, button3);
      //Adding the toggle button to the pane
      HBox box = new HBox(5);
      box.setPadding(new Insets(50, 50, 50, 150));
      box.getChildren().addAll(buttonBar);
      box.setStyle("-fx-background-color: BEIGE");
      //Setting the stage
      Scene scene = new Scene(box, 595, 150);
      stage.setTitle("Button Bar");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新日期:2020 年 5 月 20 日

740 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告