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

前端 未结 4 842
佛祖请我去吃肉
佛祖请我去吃肉 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:42

    I had a similar problem with creating expanding TextArea. I was creating TextArea that looks like TextField and expand vertically every time when there is no more space in line. I have tested all solutions that I could find on this topic on stack and other sources available. I found few good solutions but neither was good enough.

    After many hours of fighting, I figured out this approach.

    I extended TextArea class, override layoutChildren() method and add a listener on text height.

      @Override
      protected void layoutChildren() {
        super.layoutChildren();
        setWrapText(true);
        addListenerToTextHeight();
      }
    
      private void addListenerToTextHeight() {
        ScrollPane scrollPane = (ScrollPane) lookup(".scroll-pane");
        scrollPane.setHbarPolicy(ScrollBarPolicy.NEVER);
        scrollPane.setVbarPolicy(ScrollBarPolicy.NEVER);
    
        StackPane viewport = (StackPane) scrollPane.lookup(".viewport");
    
        Region content = (Region) viewport.lookup(".content");
    
        Text text = (Text) content.lookup(".text");
        text.textProperty().addListener(textHeightListener(text));
      }
    
      private InvalidationListener textHeightListener(Text text) {
        return (property) -> {
          // + 1 for little margin
          double textHeight = text.getBoundsInLocal().getHeight() + 1;
    
          //To prevent that our TextArena will be smaller than our TextField
          //I used DEFAULT_HEIGHT = 18.0
          if (textHeight < DEFAULT_HEIGHT) {
            textHeight = DEFAULT_HEIGHT;
          }
    
          setMinHeight(textHeight);
          setPrefHeight(textHeight);
          setMaxHeight(textHeight);
        };
      }
    

提交回复
热议问题