如何在JavaFX中為選擇框新增分隔符?
選擇框
在JavaFX中,選擇框由類**javafx.scene.control.ChoiceBox<T>**表示。您可以透過例項化此類來建立一個選擇框。選擇框包含少量多個選項,並且只允許您選擇其中一個。
它有兩種狀態:
顯示 - 您可以在選擇框中看到選項列表。
不顯示 - 您只能看到選擇框的當前選擇。
分隔符
分隔符是水平或垂直線,用於分隔應用程式的UI元素。在JavaFX中,**javafx.scene.control.Separator**類表示分隔符,要建立分隔符,您需要例項化此類。
向選擇框新增分隔符
選擇框有一個ObservableList,它儲存選項列表。您可以使用add()或addAll()方法將選項新增到此列表中,例如:
choiceBox.getItems().add(item); or, choiceBox.getItems().addAll(item1, item2, item3);
您可以使用**add()**或**addAll()**方法將分隔符新增到選擇框。其中一個add()方法變體允許您指定需要在選項列表中新增專案的索引。
示例
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class ChoiceBoxAddingSeparator extends Application {
public void start(Stage stage) {
//Creating a choice box
ChoiceBox choiceBox = new ChoiceBox();
choiceBox.setValue("English");
//Retrieving the observable list
ObservableList list = choiceBox.getItems();
//Adding items to the list
list.add("English");
list.add("Hindi");
list.add("Telugu");
list.add("Tamil");
//Creating a separator
Separator sep = new Separator();
sep.setMaxWidth(80);
sep.setHalignment(HPos.CENTER);
//Adding separator to the choice box
list.add(2, sep);
//Setting the position of the choice box
choiceBox.setTranslateX(200);
choiceBox.setTranslateY(15);
Label label = new Label("Select Display Language:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
label.setTranslateX(20);
label.setTranslateY(20);
//Adding the choice box to the group
Group root = new Group(choiceBox, label);
//Setting the stage
Scene scene = new Scene(root, 595, 170, Color.BEIGE);
stage.setTitle("Choice Box Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}輸出

廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP