gpt4 book ai didi

java - JPanel 在尝试绘制时卡住了我的整个应用程序

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:34:08 25 4
gpt4 key购买 nike

我正在为一个学校项目编写 Oregon Trail 代码,并且正在实现狩猎小游戏。我们正在使用带有卡片布局的模型 View 展示器。当 HuntingPanel 切换到它调用运行时,JOptionPane 出现,但随后整个应用程序卡住,我不得​​不强制退出。我在一个单独的项目中编写了整个狩猎游戏的代码,并且刚刚将文件带到了 Oregon Trail 游戏中。它使用自己的 JFrame 在自己的项目中运行良好。我不知道该怎么办。

我调用它来初始化面板,切换到它,然后运行游戏。

    public void initialize(int ammo) {
player.setBullets(ammo);
bulletLabel.setText("Bullets: "+player.getBullets());
presenter.switchToPanel(OregonTrailPresenter.HUNTING_PANEL);
run();
}

这是我的运行方法。

public void run() {
// starting message
JOptionPane.showMessageDialog(null, "You have reached a nearby field to hunt. You will stay\nhere until " +
"you run out of ammunition or click Return to Trail.");
// while the player has bullets or doesn't click return to trail
while (player.getBullets() > 0 && stillHunting) {
// creates random animals
checkForAnimal();
// moves and updates screen
repaint();
update();

try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
endHunting();
}

这里还有其他方法。

private void checkForAnimal() {
int x = 0;
int y = rand.nextInt(MAX_Y)-40;
int rand1 = rand.nextInt(100);
String str = null;
if (rand1 < 50) {
str = "left";
x = MAX_X-40;
}
else if (rand1 >= 50) {
str = "right";
x = 0;
}

double gen = rand.nextGaussian(); // gen is a number from -inf to +inf
gen = Math.abs(gen); // gen is now a number from 0 to inf
if (gen >= 1.9 && gen < 2.1) { //1.19%
animalList.add(new Bunny(x,y,str));
}
if(gen >= 2.1 && gen < 2.2) { //0.9%
animalList.add(new Bear(x,y,str));
}
if (gen >= 2.2 && gen < 2.3) {
animalList.add(new Deer(x,y,str));
}

}

public void update() {
for (int i = 0; i < animalList.size(); i++) {
animalList.get(i).move();
}
}

最佳答案

您必须实现 javax.swing.Timer而不是 Thread.sleep(int),因为此代码行在 EDT 期间卡住所有 GUI直到 Thread.sleep(int) 结束。这是 demonstrations如果 GUI 在 EDT 期间被 Thread.sleep(int)

延迟会发生什么

关于java - JPanel 在尝试绘制时卡住了我的整个应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8371436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com