Re: AWT ScrollPane

From: ak (spam_at_imagero.com)
Date: 05/30/04


Date: Sun, 30 May 2004 11:37:03 +0200


> Is there any way I have missed to use an AWT ScrollPane and have just
> vertical or just horizontal scrolling?
>
> Going to JScrollPane makes me lose unsigned Applet cut and paste.
>

public class CustomScrollPane extends Container {

    Scrollbar vscroll;
    Component child;
    Container contentPane;

    //set to line height
    int unitSize = 20;

    public CustomScrollPane(Component child) {
        super.setLayout(new BorderLayout());
        vscroll = new Scrollbar(Scrollbar.VERTICAL);
        this.child = child;
        contentPane = new Container();
        add(vscroll, BorderLayout.EAST);
        add(contentPane, BorderLayout.CENTER);
        contentPane.add(this.child);

        vscroll.addAdjustmentListener(new AdjustmentVHandler());
        vscroll.setUnitIncrement(unitSize);

        ComponentHandler componentHandler = new ComponentHandler();
        contentPane.addComponentListener(componentHandler);

        //little hack to set width of child
        contentPane.addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent e) {
                Component child0 = CustomScrollPane.this.child;
                Dimension d = contentPane.getSize();
                Dimension d0 = child0.getSize();
                child0.setSize(d.width, d0.height);
            }
        });

        child.addComponentListener(componentHandler);
    }

    private class ComponentHandler extends ComponentAdapter {
        public void componentResized(ComponentEvent e) {
            int maximum = CustomScrollPane.this.child.getSize().height;
            int visibleAmount = vscroll.getSize().height;
            vscroll.setMaximum(maximum);
            vscroll.setVisibleAmount(visibleAmount);
            vscroll.setBlockIncrement(visibleAmount);
        }
    }

    private class AdjustmentVHandler implements AdjustmentListener {
        public void adjustmentValueChanged(AdjustmentEvent e) {
            Point location = child.getLocation();
            location.y = -vscroll.getValue();
            child.setLocation(location);
        }
    }

    public static void main(String[] args) {
        Canvas c = new Canvas() {
            public void paint(Graphics g) {
                super.paint(g);
                Dimension d = getSize();
                Paint paint = new GradientPaint(0,0, Color.red, d.width,
d.height, Color.blue);
                ((Graphics2D)g).setPaint(paint);
// g.setClip(getParent().getBounds());
                g.fillRect(0,0,d.width, d.height);
            }
        };
        c.setSize(200, 600);
        CustomScrollPane pane = new CustomScrollPane(c);
        Frame frame = new Frame();
        frame.add(pane);
        frame.pack();
        frame.show();
    }
}

-- 
http://uio.dev.java.net
http://reader.imagero.com