我在Oracle文档中遵循了关于TableView的教程,我想做同样的事情,但是我想展示一个RadioButton,而不是显示TextField来修改项目.(我用RadionButton创建了TableView)
我使用了https://docs.oracle.com/javase/8/javafx/user-interface-tutorial/table-view.htm上的教程 (请参阅编辑表中的数据)并对其进行了扩展.作为值的基础,应该通过单选按钮设置,我假设一个枚举.
在我的例子中,我Person用enum 扩展了类Participation(指示列表中的人是否参加虚构事件)......
public static enum Participation {
YES,
NO,
MAYBE;
public String toString() {
return super.toString().toLowerCase();
};
}
...
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private final SimpleObjectProperty<Participation> participation;
...
Run Code Online (Sandbox Code Playgroud)
我实施了一个RadioButtonCell,这需要一个仲裁EnumSet<T>.因此,您可以将它用于每个Enumeration和每个TableColumn,它们应该包含RadioButtons.
public static class RadioButtonCell<S,T extends Enum<T>> extends TableCell<S,T>{
private EnumSet<T> enumeration;
public RadioButtonCell(EnumSet<T> enumeration) {
this.enumeration = enumeration;
}
@Override
protected void updateItem(T item, boolean empty)
{
super.updateItem(item, empty);
if (!empty)
{
// gui setup
HBox hb = new HBox(7);
hb.setAlignment(Pos.CENTER);
final ToggleGroup group = new ToggleGroup();
// create a radio button for each 'element' of the enumeration
for (Enum<T> enumElement : enumeration) {
RadioButton radioButton = new RadioButton(enumElement.toString());
radioButton.setUserData(enumElement);
radioButton.setToggleGroup(group);
hb.getChildren().add(radioButton);
if (enumElement.equals(item)) {
radioButton.setSelected(true);
}
}
// issue events on change of the selected radio button
group.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
@SuppressWarnings("unchecked")
@Override
public void changed(ObservableValue<? extends Toggle> observable,
Toggle oldValue, Toggle newValue) {
getTableView().edit(getIndex(), getTableColumn());
RadioButtonCell.this.commitEdit((T) newValue.getUserData());
}
});
setGraphic(hb);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您现在必须调整特定TableColumn的CellFactory
participationColumn.setCellFactory((param) -> new RadioButtonCell<Person, Participation>(EnumSet.allOf(Participation.class)));
Run Code Online (Sandbox Code Playgroud)
最后像往常一样在提交时更新数据的实际值:
participationColumn.setCellValueFactory(new PropertyValueFactory<Person, Participation>("participation"));
participationColumn.setOnEditCommit(
new EventHandler<CellEditEvent<Person, Participation>>() {
@Override
public void handle(CellEditEvent<Person, Participation> t) {
((Person) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setParticipation(t.getNewValue());
}
}
);
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
3758 次 |
| 最近记录: |