【问题标题】:How to draw on JPanel on fixed position?如何在固定位置上绘制JPanel?
【发布时间】:2011-02-20 05:40:36
【问题描述】:

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

我尝试了以下代码:

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

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

【问题讨论】:

  • 发布 SSCCE:sscce.org,并提出您的问题,以便我们看到确切的问题。例如,您的代码中没有包含 super.paintComponent() 的问题是什么?

标签: java jpanel jscrollpane


【解决方案1】:

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

标准技术是使用JLayeredPane。将JScrollPane 添加到下层,并在其上方添加一个不透明的玻璃面板组件。请参阅 Swing 教程中的How to Use a Layered Pane

【讨论】:

    【解决方案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);
         }
    }
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多