似乎无法将JTextArea添加到JScrollPane吗

似乎无法将JTextArea添加到JScrollPane吗

本文介绍了似乎无法将JTextArea添加到JScrollPane吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里遇到了一个小问题...我试图创建一个可滚动的文本区域,并且已经使用以下代码片段实现了它,我相当确定这是可以的.如果您能告诉我这是怎么回事,我将不胜感激.

I'm running in to a small snag here...I was trying to create a scrollable text area, and I've implemented it using the following code snippet, which I'm fairly sure is okay. I'd appreciate if you could tell me what's wrong with it?

JTextArea textArea = new JTextArea();
textArea.setBackground(Color.WHITE);
textArea.setPreferredSize(new Dimension(600, 200));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);

JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
String s = "";

for (int i = 0; i < 100; i++) {
    s += "asdflkjas;ldfkjas;lflsdkjfads;kfja;sdlfafsdf\n";
}

textArea.setText(s);

// method to add Component to a JPanel with GridBagLayout
addComponent(scrollPane, 3, 0, 2, 2);

问题很简单-一切正常-文本正常显示,滚动条显示正常,文本已换行...但是我无法滚动!

The problem is simple - everything works fine - the text appears normally, the scroll bars appear okay, the text is wrapped...but I couldn't scroll!

请问一些提示?

谢谢!巴乔

推荐答案

问题是您将textArea的首选大小设置为小于显示文本所需区域的大小,因此没有滚动条出现.

The problem is you are setting the preferred size of textArea to be a smaller size that the area needed to display the text so no scrollbars appear.

此处更好地 not 设置首选大小,并让JScrollPane确定子组件的大小.滚动条将按预期显示.

Better here not to set the preferred size and let the JScrollPane determine the size of the child component. Scrollbars will appear as expected.

您可以使用此构造函数: JTextArea(整数行,整数列)

You could use this constructor: JTextArea(int rows, int columns)

侧面说明:进行String串联时最好使用StringBuilder,以提高性能.

Side note: Better to use StringBuilder when doing String concatenation for improved performance.

这篇关于似乎无法将JTextArea添加到JScrollPane吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:00