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.