Reputation: 49
I came across the following problem. I want to have a scrollable JTextArea and create one like that:
JScrollPane scrollableTextArea = new JScrollPane();
JTextArea text = new JTextArea();
scrollableTextArea.add(text);
The result is that I have a grey field that I cannot write into.
If I create the JTextArea like this however it works:
JScrollPane scrollableTextArea = new JScrollPane(new JTextArea());
Where is my mistake that leads to that behaviour?
Upvotes: 0
Views: 5065
Reputation: 324088
If I create the JTextArea like this however it works:
A JScrollPane uses its own custom layout manager. The scrollpane contains areas for:
When you use the following:
scrollableTextArea.add(text);
This will mess up the scroll pane because the component is added to the scroll pane directly and not the viewport of the scroll pane
When you use:
JScrollPane scrollableTextArea = new JScrollPane(new JTextArea(5, 20));
This will create a scroll pane and add the text area to the viewport of the scroll pane.
Read the section from the Swing tutorial on How to Use ScrollPanes for more information on how the scroll pane works.
Upvotes: 1