javaFX:带有单选按钮的listview [英] javaFX:listview with Radio Button
本文介绍了javaFX:带有单选按钮的listview的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,其中包含带有列表项的 RadioButton
的项目。
I have a list with items which should carry RadioButton
with list items.
ListView
是一个可观察的 ArrayList
,其中包含我希望添加单选按钮的数据单元格列表视图中的每个项目。
the ListView
is an observable ArrayList
with data I want to add radio Button with each item in list View.
推荐答案
创建自定义 ListCell
并将ListCell的图形设置为 RadioButton
。如果需要,您可以在 updateItem()
中添加更多功能。
Create a custom ListCell
and set the graphic of the ListCell to a RadioButton
. You can add more functionality inside updateItem()
if required.
输出
完整示例
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文