简体   繁体   中英

Drawing on a JPanel inside JScrollPane

I'm trying to draw into a JPanel using a class that overrides the paintComponent method.

This works fine when the whole panel is repainted. It works fine when I scroll to the left, up, or down, or resize. Moving the scroll bar by whole "pages" to the right also appears to work fine.

But, when I scroll right, by dragging the bar, or by clicking the small-adjustment button, the drawing seems to be offset slightly to the left of where they ought to be, which when combined with the partial redraw end up with a straight line getting corrupted.

This example reproduces the problem. Just run it and drag the horizontal scroll bar around a bit.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class test {

    private class MyPanel extends JPanel {
        public MyPanel() {
            super();
        }

        public Dimension getPreferredSize() {
            return new Dimension(2000, 200);
        }

        public void paintComponent(Graphics g) {
            super.paintComponent(g);

            g.drawLine(0, 0, 2000, 200);
            g.drawLine(0, 200, 2000, 0);
        }
    }

    private JFrame frame;
    private JScrollPane sp;
    private MyPanel mp;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    test window = new test();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public test() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        mp = new MyPanel();
        sp = new JScrollPane(mp);
        frame.add(sp);
    }

}

This is what I get:

屏幕截图

What am I doing wrong?

Apparently this was a bug in OpenJDK 7.

The exact same code works, without recompilation, in OpenJDK 8.

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