How can I create a JTextArea with a specified width and the smallest possible height required to display all the text?

前端 未结 4 572
青春惊慌失措
青春惊慌失措 2020-12-10 13:47

In all the examples that I can find that use a JTextArea, the height & width is known before constructing the JTextArea, and if the JText

4条回答
  •  天命终不由人
    2020-12-10 14:15

    it uses absolute positioning based on the added component's preferred size.

    Sounds like the job of a layout manager.

    This requires that my JTextArea would return the correct dimensions on getPreferredSize().

    JTextArea textArea = new JTextArea();
    textArea.setLineWrap( true );
    textArea.setWrapStyleWord( true );
    textArea.setText("one two three four five six seven eight nine ten");
    System.out.println("000: " + textArea.getPreferredSize());
    textArea.setSize(100, 1);
    System.out.println("100: " + textArea.getPreferredSize());
    textArea.setSize( textArea.getPreferredSize() );
    

提交回复
热议问题