Search code examples
javaswingjframejpaneljscrollpane

JScrollPane does not show the JPanel


So I was trying to make a browser in java. I wanted to make the user be able to scroll the content of the website. I tried the put a JPanel in a JScrollPane, but the JPanel did not show up. After I got that problem I made a new java project to test this problem on, the problem still occurred. Here is the code of the test project:

package exp;

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class test {
    public static void main(String[] args) {
        JFrame f = new JFrame("test");
        JScrollPane s = new JScrollPane();
        JPanel p = new JPanel();
        s.add(p);
        f.add(s);
        f.setVisible(true);
        f.setSize(800, 600);
        p.setBackground(Color.WHITE);
        p.getGraphics().drawString("test", 50, 50);

    }
}

This is what it displayed: This is what the code dipslayed


Solution

  • JScrollPane s = new JScrollPane();
    JPanel p = new JPanel();
    s.add(p);
    

    Don't add components directly to a scroll pane. The component needs to be added to the viewport of the scroll pane. You do this by using:

    JPanel p = new JPanel();
    JScrollPane s = new JScrollPane(p);
    

    or

    JPanel p = new JPanel();
    JScrollPane s = new JScrollPane();
    s.setViewportView( p );
    

    Don't use the getGraphics(...) method to do painting:

    // p.getGraphics().drawString("test", 50, 50);
    

    You should be overriding the paintComponent() method of a JPanel and add the panel to the frame. Read the section from the Swing tutorial on Custom Painting for more information and working examples.

    Keep a link to the tutorial handy for all the Swing basics.