Binding TextArea height to its content


Question

JavaFX: Is it possible to bind TextArea height (row count) to the height of its content?
I would like to dynamically change height of TextArea while writing the text.

1
7
11/1/2013 7:23:03 AM

This is an exact, simple & working solution:

SimpleIntegerProperty count = new SimpleIntegerProperty(20);
int rowHeight = 10;

txtArea.prefHeightProperty().bindBidirectional(count);
txtArea.minHeightProperty().bindBidirectional(count);
txtArea.scrollTopProperty().addListener(new ChangeListener<Number>(){
    @Override
    public void changed(ObservableValue<? extends Number> ov, Number oldVal, Number newVal) {
        if(newVal.intValue() > rowHeight){
            count.setValue(count.get() + newVal.intValue());
        }
    }
});

Alternatively you can use lambdas to simply the syntax even further:

SimpleIntegerProperty count=new SimpleIntegerProperty(20);
int rowHeight = 10;

textArea.prefHeightProperty().bindBidirectional(count);
textArea.minHeightProperty().bindBidirectional(count);
textArea.scrollTopProperty().addListener((ov, oldVal, newVal) -> {
    if(newVal.intValue() > rowHeight){
        count.setValue(count.get() + newVal.intValue());
    }
});
2
9/11/2017 6:46:23 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon