import java.awt.*;
import javax.swing.*;

public class ScrollDemo extends JFrame {
    private RectPanel rp;
    
    public ScrollDemo() {
        setSize(100, 100);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        rp = new RectPanel(50, 200);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane(rp), BorderLayout.CENTER);
    }
    
    private class RectPanel extends JPanel {
        private int rW, rH;
        
        public RectPanel(int rW, int rH) {
            super();
            this.rW = rW;
            this.rH = rH;
        }
        
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.blue);
            g.fillRect(0, 0, rW, rH/3);
            g.setColor(Color.yellow);
            g.fillRect(0, rH/3, rW, rH/3);
            g.setColor(Color.red);
            g.fillRect(0, 2*rH/3, rW, rH/3);
        }
        
        public Dimension getPreferredSize() {
            return new Dimension(rW, rH);
        }
    }
    
    public static void main(String[] args) {
        ScrollDemo sd = new ScrollDemo();
        sd.setVisible(true);
    }
}
