javaFX:带有单选按钮的 ListView

标签 java javafx scenebuilder

我有一个包含项目的列表,其中应该带有带有列表项的 RadioButton

ListView 是一个可观察的ArrayList,其中包含我想为 ListView 中的每个项目添加单选按钮的数据。

最佳答案

创建自定义ListCell并将 ListCell 的图形设置为 RadioButton。如果需要,您可以在 updateItem() 中添加更多功能。

输出

enter image description here

完整示例

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class RadioButtonListView extends Application {

    public static final ObservableList names =
            FXCollections.observableArrayList();
    private ToggleGroup group = new ToggleGroup();

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("List View Sample");

        final ListView listView = new ListView();
        listView.setPrefSize(200, 250);
        listView.setEditable(true);

        names.addAll(
                "Adam", "Alex", "Alfred", "Albert",
                "Brenda", "Connie", "Derek", "Donny",
                "Lynne", "Myrtle", "Rose", "Rudolph",
                "Tony", "Trudy", "Williams", "Zach"
        );

        listView.setItems(names);
        listView.setCellFactory(param -> new RadioListCell());

        StackPane root = new StackPane();
        root.getChildren().add(listView);
        primaryStage.setScene(new Scene(root, 200, 250));
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private class RadioListCell extends ListCell<String> {
        @Override
        public void updateItem(String obj, boolean empty) {
            super.updateItem(obj, empty);
            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                RadioButton radioButton = new RadioButton(obj);
                radioButton.setToggleGroup(group);
                // Add Listeners if any
                setGraphic(radioButton);
            }
        }
    }
}

关于javaFX:带有单选按钮的 ListView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30027953/

相关文章:

java - 如何让图表内容区域占据其可用的最大区域?

JavaFX-InitationTargetException

JavaFX 如何添加元素,例如。从存储在数据库 Mysql 中的项目动态创建的按钮?

javafx - 陷入事件处理 Java FX - Controller - 场景生成器

java - 弹出窗口删除javafx中的主节点

javascript - 在 MarkLogic 9 中出现 XDMP-EXPNTREECACHEFULL 错误

java - JBoss EAP6 - 无法创建 JDBC 数据源 (Microsoft SQL Server)

java - SWT 中不同大小的 View

java - 对于参数化类来说,使用类(而不是接口(interface))作为类型是一种不好的做法吗?

java - JavaFX 稍后运行不起作用