When multiple JFrames are queued for repaint, the Swing Repaint Event paints the contents of all frames onto all frames, as though it is sharing the JPanels with the other frames.
In the example below, 'Frame 1' should only paint the square, and 'Frame 2' should only paint the oval. Instead, their graphics are somehow overlapping. The JPanels are not shared in any way, shape or form, so this should be impossible.
What I want to see is this:
For some reason, this only happens when the frames are being drawn in a loop (e.g. at 60 FPS).
I'm running Java 1.8.0_25 on Windows 10 x64.
I've been at it for hours now, and I couldn't find anything online about this... Does anyone know of a way to avoid this issue? Or if there is a work-around?
Here's the code:
JFrame frame1 = new JFrame("Frame 1");
frame1.setSize(256, 256);
frame1.setLocation(0, 0);
JPanel panel1 = new JPanel() {
public void paintComponent(Graphics g) {
g.fillRect(32, 32, 32, 32);
}
};
frame1.add(panel1);
frame1.setVisible(true);
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(256, 256);
frame2.setLocation(300, 0);
JPanel panel2 = new JPanel() {
public void paintComponent(Graphics g) {
g.fillOval(66, 32, 32, 32);
}
};
frame2.add(panel2);
frame2.setVisible(true);
while(true) {
Thread.sleep(16);
panel1.repaint();
panel2.repaint();
}
Solution (thanks MadProgrammer):
I did not add super.paintComponent(g)
right after overriding the paintComponent()
method. This fixed the issue. Unfortunately this also erases the previous graphics contents of the JPanel.