How to draw on JPanel on fixed position?

◇◆丶佛笑我妖孽 提交于 2020-01-21 18:58:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!