gpt4 book ai didi

javafx 创建 ComboBox TableCell

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:51:18 25 4
gpt4 key购买 nike

我正在尝试在我的 TableView 中创建自定义 TableCell。我希望它显示一个 ComboBox,我可以在其中选择一个 String 值,然后显示 String 值,就好像它是用户输入一样。这个想法是用户不知道哪些是允许的值,因此他可以简单地在 ComboBox 中选择其中一个。

我尝试这样做来制作我自己的“ComboBoxCell”,但它没有按预期工作:

public class ComboBoxCell extends TableCell<ClassesProperty, String> {

private ComboBox<String> comboBox;

public ComboBoxCell() {
}

@Override
public void startEdit() {
super.startEdit();

if (comboBox == null) {
createComboBox();
}

setGraphic(comboBox);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}

@Override
public void cancelEdit() {
super.cancelEdit();

setText(String.valueOf(getItem()));
setContentDisplay(ContentDisplay.TEXT_ONLY);
}

public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);

if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (comboBox != null) {
comboBox.setValue(getString());
}
setGraphic(comboBox);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
} else {
setText(getString());
setContentDisplay(ContentDisplay.TEXT_ONLY);
}
}
}

private void createComboBox() {
// ClassesController.getLevelChoice() is the observable list of String
comboBox = new ComboBox<>(ClassesController.getLevelChoice());
comboBox.setMinWidth(this.getWidth() - this.getGraphicTextGap()*2);
comboBox.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
commitEdit(comboBox.getSelectionModel().getSelectedItem());
} else if (t.getCode() == KeyCode.ESCAPE) {
cancelEdit();
}
}
});
}

private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}

然后在我的“主”应用中:

levelChoice = FXCollections.observableArrayList(
new String("Bla"),
new String("Blo")
);

// Level Column : String value
Callback<TableColumn, TableCell> comboBoxFactory = new Callback<TableColumn, TableCell>() {
@Override
public TableCell call(TableColumn p) {
return new ComboBoxCell();
}
};

levelColumn.setCellValueFactory(
new PropertyValueFactory<ClassesProperty, String>("level")
);
levelColumn.setCellFactory(comboBoxFactory);

有什么想法吗?谢谢!

最佳答案

我找到了解决方案:

levelChoice = FXCollections.observableArrayList("Bla", "Blo");

levelColumn.setCellValueFactory(
new PropertyValueFactory<ClassesProperty, String>("level")
);
levelColumn.setCellFactory(ComboBoxTableCell.forTableColumn(levelChoice));
levelColumn.setOnEditCommit(
new EventHandler<CellEditEvent<ClassesProperty, String>>() {
@Override
public void handle(CellEditEvent<ClassesProperty, String> t) {
((ClassesProperty) t.getTableView().getItems().get(t.getTablePosition().getRow())).setLevel(t.getNewValue());
};
}
);

关于javafx 创建 ComboBox TableCell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21860019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com