views:

57

answers:

3

I have JPanel wrapped in JScrollPane and I want the rectangle to be drawn always on the same position = moving with scrollbars wont affect the visibility of the rectangle.

I tried following code:

    public void paintComponent(Graphics g) {
        g.setColor(Color.red);
        g.drawRect(50, (int)getVisibleRect().getY(), 20 , 20);
    }

but it only repaints the rectangle when size of whole JPanel is changed.

A: 

Try setLocation method. Visit http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html#setLocation%28int,%20int%29 for more info.

RaviG
+1  A: 

IIRC, JScrollPane will try to minimise the amount of redrawing done scrolling, so it wont always cause your component to be updated.

The standard technique is to use a JLayeredPane. Add you JScrollPane to a lower layer, and a non-opaque glass panel component above it. See How to Use a Layered Pane in the Swing tutorial.

Tom Hawtin - tackline
I've even done an HUD using JLayeredPane.
Tim Williscroft
A: 

Maybe something like this:

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

public class ScrollPanePaint extends JFrame
{
    public ScrollPanePaint()
    {
        JPanel panel = new JPanel();
        panel.setOpaque( false );
        panel.setPreferredSize( new Dimension(400, 400) );

        JViewport viewport = new JViewport()
        {
            public void paintComponent(Graphics g)
            {
                super.paintComponent(g);
                g.setColor( Color.BLUE );
                g.drawArc( 100, 100, 80, 80, 0, 360);
            }
        };

        viewport.setView( panel );
        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewport( viewport );
        scrollPane.setPreferredSize( new Dimension(300, 300) );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        JFrame frame = new ScrollPanePaint();
        frame.setDefaultCloseOperation( DISPOSE_ON_CLOSE );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
     }
}
camickr