我遇到了一个问题,在尝试了大约2个小时后,我无法去工作。我想有一个循环,做2个方法(绘制和更新),但也侦听鼠标/键盘事件。我有一个循环,可以绘制和更新,但在循环之外什么也不做(侦听事件)我尝试了很多方法,但都没有效果。帮帮忙好吗?
我尝试使用Runnable Thread,使用不同的顺序,使用wait()和notify(),我尝试了很多方法。但最基本的是,我想知道如何在运行循环的同时仍然检查用户输入
此外,当我尝试退出程序时,单击红色的"X",它不会退出,但仍然可以工作
代码如下:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class main extends Applet implements MouseListener, Runnable {
public main() {
super();
init();
}
Thread t;
Screen screen = new Screen();
String Text = "Hello";
boolean Running = true;
boolean Click = false;
int R = 0x00;
int G = 0x00;
int B = 0x00;
int xpoints[] = {25, 40, 40, 25, 25};
int ypoints[] = {40, 40, 25, 25, 25};
int npoints = 5;
public void run() {
while (Running) {
GameLoop();
}
}
public void init() {
this.addMouseListener(this);
this.setSize(400, 300); //manually set your Frame's size
t = new Thread(this);
t.start();
}
public void paint(Graphics g) {
g.setColor(new Color(R, B, G));
g.fillPolygon(xpoints, ypoints, npoints);
Running = true;
t.run();
}
public void mousePressed(MouseEvent e) { //On Mouse Click
System.exit(0);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
System.exit(0);
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
public boolean keyDown(Event e, int key) {
return true;
}
public void GameLoop() {
if (Running) {
if (R != 0xff) {
R++;
} else {
if (G != 0xff) {
G++;
} else {
if (B != 0xff) {
B++;
} else {
System.exit(0);
}
}
}
try {
sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
paint(getGraphics());
}
}
public void sleep(int time) throws InterruptedException {
Thread.sleep(time, 0);
}
}发布于 2011-07-09 03:50:53
This tutorial应该提供一些关于您的程序应该如何构建的洞察力。this one对鼠标监听器很有帮助。
您应该解决的问题:
1)您对paint方法做了一些可疑的事情。你为什么打电话给那里的t.run()?线程t已经在运行并不断地调用paint()方法来重新绘制屏幕。删除此调用,看看您会得到什么。
1)您的线程/应用程序的破坏情况较差。上面的第一个示例提供了一种更好的实现方式
2)你的System.Exit(0)在mousePressed()上有评论//on mouse click,但在mouseClicked()里什么都没有...它是有效的,但它的约定很糟糕
3)让你的类命名为main是非常糟糕的约定,既令人困惑又不切实际。将您的类重命名为类似于"Game“或类似的名称。
4)如果不使用Screen,为什么还要声明它?
发布于 2011-07-09 03:16:31
我看到您在初始化时将运行变量定义为true。此变量用于确定游戏是否应停止。但是,我没有看到任何地方可以将这个变量的值修改为false。这就解释了为什么你的游戏永远不会退出。
至于游戏不能运行,请尝试在IDE中调试应用程序。然后,您应该注意抛出的异常(如果有的话)以及您正在质疑的任何变量的值。希望这能让你深入了解你的应用程序的行为。
如果您发现任何新的信息,请不要忘记更新我们,这样我们就可以在此过程中为您提供帮助。
https://stackoverflow.com/questions/6628663
复制相似问题