【发布时间】:2014-03-18 13:48:25
【问题描述】:
我正在尝试在我的 TableView 中创建一个自定义 TableCell。我希望它显示一个组合框,我可以在其中选择一个字符串值,然后将字符串值显示为用户输入。这个想法是用户不知道哪些是允许的值,因此他可以简单地在 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);
有什么想法吗? 谢谢!
【问题讨论】:
标签: java combobox javafx tablecell