如何使用 JavaFX 创建单选框?
单选框包含一小套多项选择,并且允许你只选择其中一项。它将有两个状态:显示和不显示。在显示时,你可以在单选框中看到选择列表,而在不显示时,则显示当前选择。默认情况下,单选框中没有选择任何选项。
在 JavaFX 中,单选框由类javafx.scene.control.ChoiceBox<T>表示。你可以通过实例化此类来创建单选框。
此类有一个名为items的属性,它属于ObservableList<T>类型,并且包含要在单选框中显示的选择列表。你可以使用getItems()方法检索此列表。
实例化ChoiceBox 类后,你需要获取可观察列表,并使用add()或addAll()方法向其中添加所有必需的选择。
示例
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
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 ChoiceBoxExample extends Application {
public void start(Stage stage) {
//Creating a choice box
ChoiceBox<String> choiceBox = new ChoiceBox<String>();
choiceBox.setValue("English");
//Retrieving the observable list
ObservableList<String> list = choiceBox.getItems();
//Adding items to the list
list.add("English");
list.add("Hindi");
list.add("Telugu");
list.add("Tamil");
//Setting the position of the choice box
choiceBox.setTranslateX(200);
choiceBox.setTranslateY(15);
//Setting the label
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);
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP