我試圖在隨機移動的屏幕上創建多個字符(方塊)。我已經創建了一個創建正方形的CharMove類,並在屏幕上隨機移動它。然而,我試圖在一個單獨的java文件中創建這個類的多個實例,並且只創建了一個實例。哪裏不對?無法在Java中創建一個類的多個實例
CharMove類:
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;
}
}
世界級
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);
}
哪裏錯誤?什麼是預期的輸出?什麼是「不起作用」? –
我想問題是你並不是想讓x和y變成靜態的。刪除「靜態」,它會按照您期望的方式工作。 – Arsen
問題是隻有一個正方形出現,因此無論是隻創建一個實例還是正在創建兩個相同的實例。預期的輸出是在屏幕上隨機移動的兩個正方形。 – Ninjaman494