DatePicker in javafx TableCell

好久不见. 提交于 2019-12-20 03:41:53

问题


I have implemented a custom datePickerTableCell to show a date picker on cell edit. I am using the ExtFX DatePicker (https://bitbucket.org/sco0ter/extfx/overview). Everything works fine except when I enter the date manually instead of choosing it from picker, I get a NullPointerException on commitEdit().

datePicker.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent t) {
    if (t.getCode() == KeyCode.ENTER) {
        if(getItem() == null) {
            commitEdit(null);
        } else {
            commitEdit(getItem());
        }
    } else if (t.getCode() == KeyCode.ESCAPE) {
        cancelEdit();
    }
}
});

I coudnt find whats going wrong here.


回答1:


Maybe have a look at this example. It uses a color picker but works as well for a date picker:

public class ColorTableCell<T> extends TableCell<T, Color> {    
    private final ColorPicker colorPicker;

    public ColorTableCell(TableColumn<T, Color> column) {
        this.colorPicker = new ColorPicker();
        this.colorPicker.editableProperty().bind(column.editableProperty());
        this.colorPicker.disableProperty().bind(column.editableProperty().not());
        this.colorPicker.setOnShowing(event -> {
            final TableView<T> tableView = getTableView();
            tableView.getSelectionModel().select(getTableRow().getIndex());
            tableView.edit(tableView.getSelectionModel().getSelectedIndex(), column);       
        });
        this.colorPicker.valueProperty().addListener((observable, oldValue, newValue) -> {
            if(isEditing()) {
                commitEdit(newValue);
            }
        });     
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }

    @Override
    protected void updateItem(Color item, boolean empty) {
        super.updateItem(item, empty);  

        setText(null);  
        if(empty) {     
            setGraphic(null);
        } else {        
            this.colorPicker.setValue(item);
            this.setGraphic(this.colorPicker);
        } 
    }
}

If you're on Java 7, replace the lambdas with anonymous inner classes, but it should work as well. Full blog post is here.




回答2:


See if this example helps. It uses Java 8 and the DatePicker control from there.




回答3:


This example may help too. It uses a DatePicker and TableView control with Java 8.




回答4:


I faced a similar issue when using a TextArea as table cells. The issue turns out to be I was using startEdit in the TableCell implementation. Using TableView#edit instead of startEdit resolved the issue.



来源:https://stackoverflow.com/questions/23075139/datepicker-in-javafx-tablecell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!