简体   繁体   English

Swing JTextArea:自动LineWrap后正确调整对话框大小

[英]Swing JTextArea: Resize Dialog properly after automatic LineWrap

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: 无论如何,我有一个带有文本的JTextArea ,带有自动换行符:

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. 如果我通过推入\\n选择换行符,它会很高兴地调整大小,但是使用自动换行时,它只是保持原来的大小。

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. 我正在通过XML文件接收文本,并且换行后,它的范围在0到30行之间。 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: 编辑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! 重述问题后,他们解决我面临的问题的关键显然不是调整JTextArea的大小,而是确保对话框知道它的大小!

So, here is the link back to the solution I ended up using: An automatic resizing Text above a button? 因此,这是我最终使用的解决方案的链接: 在按钮上方自动调整文本大小?

You need to wrap JTeatArea with JScrollPane like next new JScrollPane(area); 您需要像下一个new JScrollPane(area);一样,用JScrollPane包装JTeatArea new JScrollPane(area); and then add JScrollPane to your JFrame . 然后将JScrollPane添加到您的JFrame

Also you create JTextArea with empty constructor, use JTextArea(int rows, int cols) to specify count of rows and columns. 另外,您还可以使用空构造函数创建JTextArea ,并使用JTextArea(int rows, int cols)指定行数和列数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM