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!
无论如何,我有一个JTextArea
带有文本,并且带有自动换行符:
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();
}
我希望文本区域垂直调整大小以显示整个文本...但是没有.如果我通过按\n
来选择换行符,它的大小会很合适,但是使用自动换行时,它会保持原来的大小.
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...
进行说明:
在创建时,我不知道文本将有多少行(由于发生自动换行符).我正在通过XML文件接收文本,并且换行后,它的范围在0到30行之间.我有垂直的空间可以显示所有内容,但是当没有或只有很少的文本要显示时,我不想滚动或拥有巨大的白色区域.
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.
重述问题后,他们解决我所面临问题的关键显然不是调整JTextArea的大小,而是确保对话框知道它的大小!
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?
推荐答案
您需要像下一个new JScrollPane(area);
一样用JScrollPane
包装JTeatArea
,然后将JScrollPane
添加到您的JFrame
.
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.
这篇关于Swing JTextArea:自动LineWrap后正确调整对话框大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!