Can't seem to add JTextArea to JScrollPane?

别来无恙 提交于 2019-12-25 18:33:36

问题


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.



来源:https://stackoverflow.com/questions/13431578/cant-seem-to-add-jtextarea-to-jscrollpane

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!