我编写了一个小程序,让两个棋子在相反的方向上来回移动。如何添加一个按钮,通过单击而不是自动来回移动它们。这是代码:
import java.awt.*;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
public class Checkers extends java.applet.Applet implements Runnable {
Thread runner;
int x1pos;
int x2pos;
Image offscreenImg;
Graphics offscreenG;
private Button move;
public void init()
{
offscreenImg = createImage(this.size().width, this.size().height);
offscreenG = offscreenImg.getGraphics();
}
public void start()
{
if (runner == null); {
runner = new Thread(this);
runner.start();
}
}
public void stop()
{
if (runner != null) {
runner.stop();
runner = null;
}
}
public void run()
{
while (true) {
for (x1pos = 5, x2pos = 105; x1pos <= 105 && x2pos >= 5; x1pos+=4, x2pos -=4)
{
repaint ();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
}
x1pos = 5;
x2pos = 105;
}
}
public void update(Graphics g) {
paint(g);
}
public void paint(Graphics g) {
// Draw background onto the buffer area
offscreenG.setColor(Color.black);
offscreenG.fillRect(0,0,100,100);
offscreenG.setColor(Color.blue);
offscreenG.fillRect(100,0,100,100);
offscreenG.setColor(Color.blue);
offscreenG.fillRect(0,100,100,100);
offscreenG.setColor(Color.black);
offscreenG.fillRect(100,100,100,100);
// Draw checker
offscreenG.setColor(Color.red);
offscreenG.fillOval(x1pos,5,90,90);
offscreenG.setColor(Color.green);
offscreenG.fillOval(x2pos,105,90,90);
// Now, transfer the entire buffer onto the screen
g.drawImage(offscreenImg,0,0,this);
}
public void destroy() {
offscreenG.dispose();
}
}
感谢您的帮助