9
我想在我的TableView中创建一个自定义TableCell。我希望它显示一个ComboBox,我可以选择一个String值,然后显示String值,就像它是一个用户输入一样。这个想法是,用户不知道哪些是允许的值,所以他可以简单地在组合框中选择其中的一个。javafx创建ComboBox TableCell
我想这样做使我自己的“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);
任何想法? 谢谢!
在'''handle'''线也可以是:'''t.getRowValue()setLevel(t.getNewValue());' ''这可以避免演员阵容。 –