Unhandled Exception Unhandled Exception - 5 months ago 33
Java Question

Adding Component to JScrollPane has weird behavior

Executing this code produces very strange behavior.
When running, try resizing and typing to see what I mean.

import java.awt.BorderLayout;
import javax.swing.*;

public class FrameWithScrollPanel extends JFrame {
public static void main(String[] args) {
FrameWithScrollPanel myFrame = new FrameWithScrollPanel();
}


public FrameWithScrollPanel()
{
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
JTextArea textArea1 = new JTextArea(5, 30);
JTextArea textArea2 = new JTextArea(5, 30);

JPanel jPanel = new JPanel();
jPanel.setSize(400,400);
jPanel.setLayout(new BorderLayout());
jPanel.add(textArea1, BorderLayout.NORTH);
jPanel.add(textArea2, BorderLayout.SOUTH);

JScrollPane scrollPane = new JScrollPane();
scrollPane.add(jPanel);
getContentPane().add(scrollPane, BorderLayout.CENTER);
pack();
setVisible(true);
}
}


Now, replace these 2 lines :

JScrollPane scrollPane = new JScrollPane();
scrollPane.add(jPanel);


With this one line and the behavior is as expected.

JScrollPane scrollPane = new JScrollPane(jPanel);


Based on the documentation the JScrollPane constructor accepts a Component and so does the add().
Why the difference in behavior?

Answer

This is wrong:

scrollPane.add(jPanel);

Since you're replacing the JScrollPane's all important viewport with this add, preventing it from functioning. You should instead be adding this to the JScrollPane's viewport as per the JScrollPane tutorial and JScrollPane API:

scrollPane.setViewportView(jPanel);

or

scrollPane.getViewport().add(jPanel);

Moral of the story: when in doubt, read the docs.

Note that if you pass the jPanel into the JScrollPane's constructor,

JScrollPane scrollPane = new JScrollPane(jPanel);

it automatically places the component into the viewport for you.

Per the API:

public JScrollPane(Component view)
Creates a JScrollPane that displays the contents of the specified component, where both horizontal and vertical scrollbars appear whenever the component's contents are larger than the view.
Parameters:
view - the component to display in the scrollpane's viewport