Prc
Prc

Reputation: 49

JTextArea not editable

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

Answers (2)

camickr
camickr

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:

  1. horizontal/vertical scrollbars
  2. a "Row Header" and "Column Header"
  3. components at the top/right and top/left of the scroll pane
  4. the "viewport" which is used to contain the component that you want to scroll

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

Hitesh Ghuge
Hitesh Ghuge

Reputation: 823

simply use text.setEditable(true)

Upvotes: 1

Related Questions