我有一個名爲CharMove的類,它是paint(Graphics g)方法和一些自定義方法。班級應創建一個正方形,然後在屏幕上隨機移動該正方形。但是,當我在我的世界級中創建這個類的兩個實例時,只會出現一個方塊。首先廣場不移動,但顯示新的座標。然後5次運行後,廣場開始隨機移動。我認爲該程序被捕獲的Graphics方法,因爲只有一個正方形正在創建,當CharMove類應該創建Graphics.I的另一個實例已經在網上搜索,但無法找到一種方法來創建Graphics.Thanks的不同實例提前。如何讓一個類創建自己的Graphics實例
CharMove類
import java.awt.*;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import java.util.Random;
public class CharMove extends JPanel {
int x = 250;
int y = 250;
public void paint(Graphics g) {
Graphics pane = (Graphics2D) g;
pane.setColor(Color.blue);
pane.fillRect(x, y, 10, 10);
}
public void movement(JFrame frame) {
for (int i=0;i<5;i++) {
try {
TimeUnit.SECONDS.sleep(1);
this.x = Getx(this.x,frame);
this.y = Gety(this.y,frame);
frame.repaint();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public 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 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;
}
}
世界級
import java.awt.*;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import java.util.Random;
public class World {
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(game);
char2.movement(game);
}
}
不是問題,但'Graphics pane =(Graphics2D)g;'不是必須的:只需直接使用'g'。 –
方法名稱不應以大寫字符開頭。你有沒有見過以大寫字母開頭的「get」方法?遵循約定。 – camickr