Can't create multiple instances of a class in Java

I'm trying to create multiple characters(squares) on the screen that move around randomly. I have already created a CharMove class that creates a square, and moves it around randomly on the screen. However, I tried creating multiple instances of this class in a seperate java file and only 1 instance was created. What is wrong?

CharMove Class:

public class CharMove extends JPanel {
    public static int x = 250;
    public static int y = 250;

    public void paint(Graphics g) {
        Graphics pane = (Graphics2D) g;
        pane.setColor(Color.blue);
        pane.fillRect(x, y, 10, 10); 

    }

    public static void movement(int x, int y, JFrame frame) { 
        CharMove.x = x; 
                CharMove.y = y;
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(1);
                CharMove.x = Getx(CharMove.x,frame); 
                CharMove.y = Gety(CharMove.y,frame);
                frame.repaint();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static int Getx(int a, JFrame frame) { 
        Random rn = new Random();
        int xnum = rn.nextInt(10)-5; 
        a += xnum; 
        System.out.println("x:" + a); 
        return a;
    } 
    public static int Gety(int b, JFrame frame){ 
        Random rn = new Random();
        int ynum = rn.nextInt(10)-5; 
        b += ynum; 
        System.out.println("y:" + b); 
        return b;
    } 
}

World Class

public static void main(String[] args) {
    JFrame game = new JFrame();
    game.setTitle("Matrix");
    game.setSize(500, 500);;
    game.getContentPane().setBackground(Color.white);
    game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    game.setVisible(true);  
    CharMove char1 = new CharMove(); 
    CharMove char2 = new CharMove();
    game.add(char1);   
    game.add(char2);
    char1.movement(100,100,game); 
    char2.movement(250,250,game);
}
Jon Skeet
people
quotationmark

However, I tried creating multiple instances of this class in a seperate java file and only 1 instance was created.

Nope, you're creating multiple instances. However, that doesn't make any difference because you don't have any per-instance state. Your only fields are these:

public static int x = 250;
public static int y = 250;

Those are static fields, which means they're not related to any specific instance of the class. You probably just want to remove the static keyword from the declarations. (I'd also make the fields private and provide public getters/setters if necessary, but that's a different matter.)

You'll also need to make your static methods into instance methods - because they're meant to act on individual instances, right? Basically, I think you should revise the meaning of static via whatever book/tutorial you're using to learn Java. (Also revise Java naming conventions.)

people

See more on this question at Stackoverflow