1

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

我尝试了以下代码:

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

但它只会在整个 JPanel 的大小发生更改时重新绘制矩形。

4

3 回答 3

2

IIRC,JScrollPane会尽量减少滚动重绘的数量,所以它不会总是导致你的组件被更新。

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

于 2010-05-17T02:20:40.947 回答
2

也许是这样的:

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);
     }
}
于 2010-05-17T03:33:04.060 回答
0

试试setLocation方法。访问setLocation了解更多信息。

于 2010-05-17T02:20:02.707 回答