在 JScrollPane 内的 JPanel 上绘图

Drawing on a JPanel inside JScrollPane

我正在尝试使用覆盖 paintComponent 方法的 class 绘制到 JPanel 中。

重新绘制整个面板时,这可以正常工作。当我向左、向上或向下滚动或调整大小时,它工作正常。将滚动条向右移动整个“页面”似乎也能正常工作。

但是,当我向右滚动时,通过拖动条或单击小调整按钮,绘图似乎稍微向左偏移了它们应该在的位置,这与部分重绘相结合最终一条直线被破坏了。

这个例子重现了这个问题。只需 运行 并稍微拖动水平滚动条即可。

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);
    }

}

这是我得到的:

我做错了什么?

显然这是 OpenJDK 7 中的错误。

完全相同的代码无需重新编译即可在 OpenJDK 8 中运行。