Swing JTextArea: Resize Dialog properly after automatic LineWrap

时光总嘲笑我的痴心妄想 提交于 2019-12-24 15:07:25

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26650992/swing-jtextarea-resize-dialog-properly-after-automatic-linewrap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!