问题
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.
回答1:
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.
回答2:
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);
}
}
回答3:
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.
来源:https://stackoverflow.com/questions/2846280/how-to-draw-on-jpanel-on-fixed-position