Unhandled Exception Unhandled Exception - 2 years ago 102
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()
JTextArea textArea1 = new JTextArea(5, 30);
JTextArea textArea2 = new JTextArea(5, 30);

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

JScrollPane scrollPane = new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);

Now, replace these 2 lines :

JScrollPane scrollPane = new JScrollPane();

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 Source

This is wrong:


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:




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.
view - the component to display in the scrollpane's viewport

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download