Search code examples
javaswingjpaneljscrollpanepreferredsize

How to set JPanel fixed size such that the JScrollPane (scrolling) appears?


I'm working on a little code. JFrame containing a JPanel with specific dimensions. Here is my code:

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

public class ScrollPane extends JFrame { 

    public ScrollPane() {
        super("Title");
        setLayout(new BorderLayout());
        setSize(320,240);

        JScrollPane scroller = new JScrollPane(new DrawingPane()); 
        scroller.setPreferredSize(new Dimension(320,240)); 

        add(scroller); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    } 

    private class DrawingPane extends JPanel {
        public DrawingPane(){
            super();
            setSize(640,480);
            setMinimumSize(new Dimension(320,240));
        }

    }

    public static void main(String[] args) {
        new ScrollPane();
    } 
}

Even with a minimum size set for the JPanel, the scrolls don't appear.


Solution

  • All components are responsible for determining there preferred size so layout managers can work properly. When doing custom painting you need to override the getPreferredSize() of your custom component to return the Dimension of your component.

    Read the section from the Swing tutorial on Custom Painting for more information and working examples.