Can't seem to add JTextArea to JScrollPane?

2019-09-08 12:31发布

问题:

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

回答1:

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.

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

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


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