我已經搜索並試圖實現一個自己的計時器,並不能爲我的生活弄清楚。所以我想要做的就是每隔五秒鐘,我想讓隨機圓圈變成一個新的隨機位置。這似乎很簡單,但我不能讓它工作。給我的代碼添加一個定時器
public class BounceThread implements Runnable {
JFrame frame;
int myX = 500/2;
int myY = 500/2;;
int X;
int Y;
Canvas canvas;
BufferStrategy bufferStrategy;
BufferStrategy bufferStrategy2;
boolean running = true;
Random rand = new Random();
Random rand2 = new Random();
int n = rand.nextInt(450) + 1;
int n2 = rand.nextInt(450) + 1;
public BounceThread() {
frame = new JFrame("Basic Game");
JPanel panel = (JPanel) frame.getContentPane();
panel.setPreferredSize(new Dimension(500, 500));
panel.setLayout(null);
canvas = new Canvas();
canvas.setBounds(0, 0, 500, 500);
canvas.setIgnoreRepaint(true);
panel.add(canvas);
canvas.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent evt) {
moveIt(evt);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
canvas.requestFocus();
}
public void run() {
while (running = true) {
Paint();
if ((myX == n || myX == n) && (myY == n2 || myY == n2)) {
n = rand.nextInt(450) + 1;
n2 = rand.nextInt(450) + 1;
n2 = 10 * (Math.round(n/10));
n = 10 * (Math.round(n/10));
Paint();
}
}
}
public static void main(String[] args) {
BounceThread ex = new BounceThread();
new Thread(ex).start();
}
public void Paint() {
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g.clearRect(0, 0, 500, 500);
Graphics2D e = (Graphics2D) bufferStrategy.getDrawGraphics();
e.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
e.clearRect(0, 0, 500, 500);
Paint(g, e);
bufferStrategy.show();
}
protected void Paint(Graphics2D g, Graphics2D e) {
n2 = 10 * (Math.round(n/10));
n = 10 * (Math.round(n/10));
g.fillOval(myX, myY, 30, 30);
g.setColor(Color.red);
e.fillOval(n, n2, 30, 30);
e.setBackground(Color.white);
}
public void moveIt(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DOWN:
if (myY >= 450) {
break;
} else {
myY += 10;
break;
}
case KeyEvent.VK_UP:
if (myY <= 30) {
break;
} else {
myY -= 10;
break;
}
case KeyEvent.VK_LEFT:
if (myX <= 30) {
break;
} else {
myX -= 10;
break;
}
case KeyEvent.VK_RIGHT:
if (myX >= 450) {
break;
} else {
myX += 10;
break;
}
}
}
}
爲什麼重寫'repaint()'而不是'paintComponent()'? – durron597
@ durron597因爲這樣我可以重用OP的大部分代碼。 –