I have a Custom JPanel that does not call super.paintComponent() in its overridden paintComponent method. I know that this is in many situations not recommended, but I wonder why the following occures:
When I start two threads that each create a JFrame and Custom Panel, the Panels somehow mix their contents. This example program will create two Frames that each show a Panel with "ONE" and "TWO" as content. But I expected to have one frame with "ONE" and one frame with "TWO" as content.
public class CustomPanel extends JPanel implements Runnable {
public static void main(String[] args) {
//create two threads constantly repainting the custom panel
//expected two panels with different content
//but got two panels with same content
new Thread(new CustomPanel("ONE", 20)).start();
new Thread(new CustomPanel("TWO", 40)).start();
}
/** creates a frame and adds the custom panel with specified text **/
public CustomPanel(String text, int y) {
setPreferredSize(new Dimension(200,50));
this.text = text;
this.y = y;
JFrame f = new JFrame(text);
f.add(this);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
private String text;//the text to draw
private int y;//where to draw
/** draw the component **/
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawString("Hello " + text, 50, y);//this line will be drawn twice on each panel (with text and y from the other)
g.dispose();
}
/** constantly repaint the custom panels **/
@Override
public void run() {
while (true) {
this.repaint();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Result
Frame1 Frame2
++++++++++++++++++ ++++++++++++++++++
+ Hello ONE + + Hello ONE +
+ Hello TWO + + Hello TWO +
++++++++++++++++++ ++++++++++++++++++
Expected Result
Frame1 Frame2
++++++++++++++++++ ++++++++++++++++++
+ Hello ONE + + +
+ + + Hello TWO +
++++++++++++++++++ ++++++++++++++++++
So how on earth are two panels painted in the same manner?
Side note 1: call super.paint() in paint() will make the Custom Panels look different
Side note 2: Moving a frame two a different screen, will make its panel draw as expected (only its own text will be shown), whereas the other will remain the same.
Update This test was done on Windows 8.1 and jre 1.7