I am trying to draw a red square over a JScrollPane. The code that I have below does it fine, but sometimes when I scroll the viewport too quickly, the red square jumps up or down.

It seemed strange to me, since the JScrollPane itself is motionless, so I assumed that Swing would not try to move the components painted inside it. I assume that what actually happens is that the red square is associated with a viewport displaying graphics that are moving.
Anyway, how can I prevent the red square from jumping and successfully draw a red list above the list? Maybe I'm wrong at all.
package components; import java.awt.*; import java.util.Vector; import javax.swing.*; import javax.swing.event.*; @SuppressWarnings("serial") public class DialogWithScrollPane extends JFrame { public DialogWithScrollPane() { super(); setResizable(false); Container pane = getContentPane(); Vector<Object> listOfStuff = new Vector<Object>(); for (int i = 0; i < 100; i++) { listOfStuff.add(Integer.toString(i)); } final JScrollPane scrollPane = new JScrollPane() { public void paint(Graphics g) { System.out.println("JScrollPane.paint() called."); super.paint(g); g.setColor(Color.red); g.fillRect(20, 50, 100, 200); } }; JList list = new JList(listOfStuff) { public void paint(Graphics g) { System.out.println("JList.paint() called."); super.paint(g);
source share