import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollDemo2 extends JFrame {
    private RectPanel rp;
    private JButton expand;
    
    public ScrollDemo2() {
        setSize(100, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        rp = new RectPanel(50, 200);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(new JScrollPane(rp), BorderLayout.CENTER);
        expand = new JButton("Expand");
        expand.addActionListener(rp);
        getContentPane().add(expand, BorderLayout.NORTH);
    }
    
    private class RectPanel extends JPanel implements ActionListener {
        private int rW, rH;
        
        public RectPanel(int rW, int rH) {
            super();
            this.rW = rW;
            this.rH = rH;
        }
        
        public void actionPerformed(ActionEvent e) {
            rW += 10;
            rH += 10;
            repaint();
        }
        
        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);
            revalidate();
        }
        
        public Dimension getPreferredSize() {
            return new Dimension(rW, rH);
        }
    }
    
    public static void main(String[] args) {
        ScrollDemo2 sd = new ScrollDemo2();
        sd.setVisible(true);
    }
}
