My teacher let me do a program where the user is asked for an entry data and according to that data generate "N" agents (threads) and that each agent appears randomly in a window. After they appear, the agents must move randomly either up, down, left or right. My problem is that at the time of calling the function mover
only 1 agent (thread) is the one that moves; the other agents remain static. My agents are printing them in JLabel. Here is the code to see if anyone can help me solve that problem.
import java.util.Random;
import javax.swing.*;
public class Ventana extends JFrame implements Runnable{
JLabel label1;
public Ventana() {
int cantidad=Integer.parseInt(JOptionPane.showInputDialog("Numero de agentes?: "));
Thread hilo[]= new Thread[cantidad];
for(int i=0;i<cantidad;i++) {
hilo= new Thread(this);
hilo.start();
}
}
public void agregalabel(int x1,int y1) {
setLayout(null);
label1=new JLabel("(*)");
label1.setBounds(x1,y1,x1,y1);
add(label1);
}
public void mover(int x1,int y1) {
int dec;
while(true) {
dec = (int)(Math.random()*3)+1;
switch(dec) {
case 1:
System.out.println(dec);
while(x1<getWidth()-30){
x1=x1+10;
label1.setBounds(x1,y1,x1,y1);
try {
Thread.sleep(500);
}catch(Exception e) {
}
}
break;
case 2:
System.out.println(dec);
while(x1>20){
x1=x1-10;
label1.setBounds(x1,y1,x1,y1);
try {
Thread.sleep(500);
}catch(Exception e) {
}
}
break;
case '3':
System.out.println("3");
while(y1<getHeight()-30){
y1=y1+10;
label1.setBounds(x1,y1,x1,y1);
try {
Thread.sleep(500);
}catch(Exception e) {
}
}
break;
case '4':
break;
}
}
}
public static void main(String[] ar) {
Ventana formulario1=new Ventana();
formulario1.setBounds(0,0,1500,400);
//formulario1.setExtendedState(JFrame.MAXIMIZED_BOTH);
// formulario1.setSize(1300,600);
formulario1.setResizable(true);
formulario1.setVisible(true);
}
int x1,y1;
@Override
public void run() {
try {
x1= (int)(Math.random()*500)+300;
y1= (int)(Math.random()*100)+301;
agregalabel(x1,y1);
mover(x1,y1);
System.out.println("X: "+x1+"Y: "+y1);
Thread.sleep(1000);
}catch(Exception e) {
}
}
}