如何在固定位置上绘制JPanel?

我将JSanel包装在JScrollPane中,我希望矩形始终在同一位置绘制=使用滚动条移动不会影响矩形的可见性。

我试过以下代码:

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

但它只在整个JPanel的大小改变时重新绘制矩形。

IIRC, JScrollPane将尽量减少重绘滚动的数量,因此它不会总是导致您的组件更新。

标准技术是使用JLayeredPane 。 将JScrollPane添加到较低层,并在其上方添加非不透明玻璃面板组件。 请参阅Swing教程中的如何使用分层窗格 。

也许是这样的:

 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); } } 

尝试使用setLocation方法。 有关详细信息,请访问http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Component.html#setLocation%28int,%20int%29