我遇到了一个问题,在尝试了大约 2 小时后我无法开始工作。我想要一个循环执行两种方法(绘制和更新),但也监听鼠标/键盘事件。我有一个绘制和更新的循环,但在循环之外不执行任何操作(监听事件)我尝试了很多东西,但没有任何效果。请帮忙?
我尝试使用可运行线程,使用不同的顺序,使用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);
}
}
最佳答案
This tutorial应该提供一些关于如何构建您的程序的见解。和this one对鼠标监听器很有帮助。
您应该解决的问题:
1) 你正在使用 paint
方法做一些可疑的事情。你为什么要在那里调用t.run()
?线程t
已经在运行并循环不断地调用paint()
方法来重绘屏幕。删除此调用,看看您会得到什么。
1) 你的线程/应用程序的破坏很差。上面的第一个示例提供了一种更好的方法来实现这一点
2)您在 mousePressed()
上有 System.Exit(0)
,并带有注释 //on mouse click
但没有任何内容mouseClicked()
...它可以工作,但它的约定不好
3)将类命名为 main
是一种非常糟糕的约定,既令人困惑又不切实际。将您的类重命名为“Game”或类似名称。
4) 如果不使用 Screen
为什么要声明它?
关于Java Applet 游戏循环停止鼠标/键盘输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6628663/