I want to repaint two pictures by using Thread, but it always only repaints pan2. The Screen show me blue background and only one picture. I expected there are two fish swimming.
import java.awt.*;
import java.util.Random;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
public class demo {
public static void main(String args[]) throws IOException{
JFrame frm = new JFrame("sea");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
drawPanel pan = new drawPanel(50,50,1);
drawPanel pan2 = new drawPanel(100,100,2);
pan.newThread.start();
pan2.newThread.start();
frm.add(pan);
frm.add(pan2);
frm.setSize(300, 300);
frm.setVisible(true);
}
}
class drawPanel extends JPanel implements Runnable{
int X,Y,moveX,moveY,dirX=1,dirY=1;
private Image img_icon;
Thread newThread;
int a;
static int width = 300;
static int height = 300;
drawPanel (int x,int y,int num) throws IOException {
File file = new File("fish"+num+".png");
a= num;
img_icon = ImageIO.read(file);
X = x;
Y = y;
newThread = new Thread(this);
}
public void paintComponent( Graphics g ) {
super.paintComponent( g );
this.setBackground( Color.blue );
g.drawImage(img_icon, X, Y,this);
}
public void stop(){
newThread = null;
}
pan1 & pan2s' Thread are working correctly, but pan1s' repaint doesn't work.
public void run() {
while(newThread != null)
{
repaint();
try
{
Thread.sleep(50);
}
catch(InterruptedException E){ }
moveX = dirX*((int)(Math.random()*100)%3);
moveY = dirY*((int)(Math.random()*100)%3);
X = X + moveX;
Y = Y + moveY;
}
}
Your problem has nothing to do with threading or painting and all to do with layout managers. Your adding both components in a default fashion to a BorderLayout-using container, the JFrame's contentPane, and so the 2nd component will cover the first.
A solution: change the layout of the container, say to GridLayout.
Note that if you want the fish to be swimming together in the same region, then your set up is wrong -- you should only have one drawing panel, and the fish should be logical constructs that are drawn on that single drawing JPanel, not GUI constructs.
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.