0

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!

A few pointers, please?

Thanks!! Baggio

4

1 回答 1

4

问题是您将首选大小设置为textArea比显示文本所需的区域更小的大小,因此不会出现滚动条。

最好不要设置首选大小,而是让JScrollPane确定子组件的大小。滚动条将按预期出现。

你可以使用这个构造函数:JTextArea(int rows, int columns)


旁注:StringBuilder在进行String连接以提高性能时更好地使用。

于 2012-11-18T13:11:46.523 回答