How can I make a TextArea stretch to fill the content, expanding the parent in the process?

前端 未结 4 832
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 04:27

So I have a TextArea and as the user pastes paragraphs into it, or just writes in it, I want it to expand vertically to reveal all the available text. I.e. not to use a scro

4条回答
  •  春和景丽
    2020-12-31 04:51

    The problem; the height of textArea is wanted to be grown or shrunk while its text is changing by either user's typing or copy-pasting. Here is another approach:

    public class TextAreaDemo extends Application {
    
        private Text textHolder = new Text();
        private double oldHeight = 0;
    
        @Override
        public void start(Stage primaryStage) {
            final TextArea textArea = new TextArea();
            textArea.setPrefSize(200, 40);
            textArea.setWrapText(true);
    
            textHolder.textProperty().bind(textArea.textProperty());
            textHolder.layoutBoundsProperty().addListener(new ChangeListener() {
                @Override
                public void changed(ObservableValue observable, Bounds oldValue, Bounds newValue) {
                    if (oldHeight != newValue.getHeight()) {
                        System.out.println("newValue = " + newValue.getHeight());
                        oldHeight = newValue.getHeight();
                        textArea.setPrefHeight(textHolder.getLayoutBounds().getHeight() + 20); // +20 is for paddings
                    }
                }
            });
    
            Group root = new Group(textArea);
            Scene scene = new Scene(root, 300, 250);
            primaryStage.setScene(scene);
            primaryStage.show();
    
            //  See the explanation below of the following line. 
            //  textHolder.setWrappingWidth(textArea.getWidth() - 10);  // -10 for left-right padding. Exact value can be obtained from caspian.css
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    

    But it has a drawback; the textarea's height is changing only if there are line breaks (ie Enter keys) between multiple lines, if the user types long enough the text gets wrapped to multiple line but the height is not changing.

    To workaround this drawback I added this line

    textHolder.setWrappingWidth(textArea.getWidth() - 10);
    

    after primaryStage.show();. It works well for long typings where user does not linebreaks. However this generates another problem. This problem occurs when the user is deleting the text by hitting "backspace". The problem occurs exactly when the textHolder height is changed and where the textArea's height is set to new value. IMO it maybe a bug, didn't observe deeper.

    In both case the copy-pasting is handling properly.

提交回复
热议问题