简体   繁体   中英

Painting on a JPanel inside a JScrollPane doesn't paint in the right location

So I have a JPanel that's inside a JScrollPane . Now I am trying to paint something on the panel, but it's always in same spot. I can scroll in all directions but it's not moving. Whatever I paint on the panel does not get scrolled.

I already tried:

  1. A custom JViewPort
  2. switching between Opaque = true and Opaque = false

Also I considered overriding the paintComponent method of the panel but that would be really hard to implement in my code.

public class ScrollPanePaint{

public ScrollPanePaint() {
    JFrame frame = new JFrame();
    final JPanel panel = new JPanel();
    panel.setPreferredSize(new Dimension(1000, 1000));
    //I tried both true and false
    panel.setOpaque(false);
    JScrollPane scrollPane = new JScrollPane(panel);
    frame.add(scrollPane);
    frame.setSize(200, 200);
    frame.setVisible(true);
    //To redraw the drawing constantly because that wat is happening in my code aswell because
    //I am creating an animation by constantly move an image by a little
    new Thread(new Runnable(){
        public void run(){
            Graphics g = panel.getGraphics();
            g.setColor(Color.blue);
            while(true){
                g.fillRect(64, 64, 3 * 64, 3 * 64);
                panel.repaint();
            }
        }
    }).start();
}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            new ScrollPanePaint();
        }
    });
}

}

The mistake I make is probably very easy to fix, but I just can't figure out how.

How to implement the paintComponent() on JPanel ?

Override getPreferredSize() method instead of using setPreferredSize()

final JPanel panel = new JPanel(){
    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        // your custom painting code here
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(40, 40);
    }
};

Some points:

  1. Override JComponent#getPreferredSize() instead of using setPreferredSize()

    Read more Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

  2. Use Swing Timer instead of Java Timer that is more suitable for Swing application.

    Read more How to Use Swing Timers

  3. Set default look and feel using UIManager.setLookAndFeel()

    Read more How to Set the Look and Feel

  4. How to fix animation lags in Java?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM