1

I hope I did not miss some duplicate question, I feel like this should be trivial!

Anyway, I have a JTextArea with text in it, with automatic line wraps:

public PleaseResize(){
    super();
    Container cp = this.getContentPane();

    JTextArea area = new JTextArea();
    area.setColumns(20);
    area.setLineWrap(true);
    area.setEditable(false);
    area.setWrapStyleWord(true);
    area.setText("Once upon a midnight dreary, while I pondered, weak and weary, over many a quaint an curious volume of forgotten lore.");
    cp.add(area, BorderLayout.CENTER);

    cp.add(new JButton("Hallo"), BorderLayout.SOUTH);
    this.pack();
}

I want the text area to resize vertically to display the whole text... but it does not. It resizes happily if I choose the line breaks via pushing in \n, but with automatic wrapping, it just remains the size it is.

I somehow feel like I am missing something totally obvious...

Edit: for clarification:

On creation-time, I do not know how many lines the text will have (due to the automatic linebreaks happening). I am receiving Text via an XML-file, and it can vary between 0 and about 30 lines after wrapping. I have the vertical space to display everything, but I do not want to scroll or to have a huge, white area when there is no or only a little text to display.


Edit 2:

After rephrasing the question, they key to the problem I was facing was apparently not resizing the JTextArea, but making sure the dialog knows how big it is!

So, here is the link back to the solution I ended up using: An automatic resizing Text above a button?

Community
  • 1
  • 1
Layna
  • 457
  • 5
  • 19

1 Answers1

2

You need to wrap JTeatArea with JScrollPane like next new JScrollPane(area); and then add JScrollPane to your JFrame.

Also you create JTextArea with empty constructor, use JTextArea(int rows, int cols) to specify count of rows and columns.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
alex2410
  • 10,904
  • 3
  • 25
  • 41
  • I may be missing a bit of information here, but while the scroll pane makes the area scrollable, it does not resize anything. – Layna Oct 30 '14 at 10:53
  • But on creation, I do not know the amount of lines yet... it changes from case to case. *goes edit her question* – Layna Oct 30 '14 at 10:55