DarkDust
DarkDust

Reputation: 92384

Editable multiline cell in TableView

(There already is a question regarding this but it has no answer and the comment isn't helpful either.)

I've got a TableView and I'd like to have a column with multiline labels that I can edit. Ideally, the behaviour would be like a TextFieldTableCell but with multiline support:

I haven't found a solution for this yet. The only workaround I've got right now is put a TextArea as the cell's "graphic":

    descriptionTableColumn.setCellFactory(param -> new TableCell<Attachment, String>() {
        @Override
        protected void updateItem(String item, boolean empty) {
            if (empty) {
                setGraphic(null);
            } else {
                TextArea area = new TextArea(item);
                area.setMinHeight(USE_COMPUTED_SIZE);
                area.setPrefHeight(USE_COMPUTED_SIZE);
                area.setMaxHeight(USE_COMPUTED_SIZE);
                setGraphic(area);
            }
        }
    });

(Code to listen to the text changes is missing here; it doesn't trigger the OnEditCommit event.)

However, the TextArea is always rendered as a normal TextArea with a border and white background. I can live with that. But the area also always renders with a certain height (about 180px) even when it's empty, even though I set USE_COMPUTED_SIZE.

So the question is:

Upvotes: 4

Views: 4118

Answers (1)

eckig
eckig

Reputation: 11154

Ok, the basic idea is to copy the TextFieldTableColumn and adjust its behavior to create a TextAreaTableColumn. I hacked a small working example implementation together: https://gist.github.com/eckig/30abf0d7d51b7756c2e7

Usage:

TableColumn<?, ?> column = new TableColumn<>();
column.setCellValueFactory(...);
column.setCellFactory(TextAreaTableCell.forTableColumn()); // add StringConverter if neccessary
tableView.getColumns().add(column);

But, there are still some things left which need to be implemented / some tuning:

  1. Adjust prefRowCount to show only the necessary amount of rows.
  2. Maybe adjust prefColumnCount?
  3. Because the "Enter" Key gets consumed for a new-line, I had to add a Save Button to commit the edit. This is somewhat ugly, but for now I do not have a better idea.

But hopefully you get the idea ;-)

Upvotes: 12

Related Questions