加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – JPanel在尝试绘制时冻结了我的整个应用程序

发布时间:2020-12-15 08:45:48 所属栏目:Java 来源:网络整理
导读:我正在编写Oregon Trail的学校项目,我正在实施狩猎迷你游戏.我们正在使用具有卡片布局的模型视图演示器.当HuntingPanel切换到它时调用run,并且JOptionPane出现,但随后整个应用程序冻结,我必须强制退出.我在一个单独的项目中编写了整个狩猎游戏,并且刚刚将文
我正在编写Oregon Trail的学校项目,我正在实施狩猎迷你游戏.我们正在使用具有卡片布局的模型视图演示器.当HuntingPanel切换到它时调用run,并且JOptionPane出现,但随后整个应用程序冻结,我必须强制退出.我在一个单独的项目中编写了整个狩猎游戏,并且刚刚将文件带到了Oregon Trail游戏中.它在自己的项目中使用自己的JFrame工作正常.我不知道该怎么做.

我这称之为初始化面板,切换到它,然后运行游戏.

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

这是我的run方法.

public void run() {
    // starting message
    JOptionPane.showMessageDialog(null,"You have reached a nearby field to hunt. You will staynhere 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,str));
    }
    if (gen >= 2.2 && gen < 2.3) { 
        animalList.add(new Deer(x,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如果在EDT期间通过Thread.sleep(int)延迟GUI会发生什么

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读