How to make a JFrame scrollable in Java?

Joe Lewis picture Joe Lewis · May 29, 2012 · Viewed 63.1k times · Source

I have this code in which I am trying to fit a scrollable Panel (JPanel) but I don't get it. Here is my code:

public class Sniffer_GUI extends JFrame {
Canvas c = new Canvas();
ConnectorPropertiesPanel props;
public Sniffer_GUI() {
    super("JConnector demo");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    getContentPane().setLayout(new GridBagLayout());
    init();

    getContentPane().add(new JLabel("Connectors example. You can drag the connected component to see how the line will be changed"),
                         new GridBagConstraints(0, 0, 2, 1, 1, 0, GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 0, 5), 0, 0));
    getContentPane().add(initConnectors(),
                         new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.BOTH, new Insets(5, 5, 5, 5), 0, 0));
    getContentPane().add(props,
                         new GridBagConstraints(1, 1, 1, 1, 0, 1, GridBagConstraints.NORTHWEST, GridBagConstraints.VERTICAL, new Insets(5, 0, 5, 5), 0, 0));
    setSize(800, 600);
    setLocationRelativeTo(null);

}

Thanks in advance.

I edit to add a code that partially seems to work...

public Sniffer_GUI() {
    super("JConnector demo");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel container = new JPanel();
    JScrollPane scrPane = new JScrollPane(container);
    add(scrPane);
    scrPane.setLayout(new ScrollPaneLayout());
    init();

    add(initConnectors());

    setSize(800, 600);
    setLocationRelativeTo(null);

}

But it isn't still scrollable, at least it makes its function inside a JScrollPane, is a good step.

Answer

Eng.Fouad picture Eng.Fouad · May 29, 2012

Make a JPanel scrollable and use it as a container, something like this:

JPanel container = new JPanel();
JScrollPane scrPane = new JScrollPane(container);
add(scrPane); // similar to getContentPane().add(scrPane);
// Now, you can add whatever you want to the container