当试图绘制它时,JPanel会冻结我的整个应用程序

whw*_*ght 3 java swing drawing freeze jpanel

我正在编写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 Code Online (Sandbox Code Playgroud)

这是我的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();
}
Run Code Online (Sandbox Code Playgroud)

以下是使用的其他方法.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

mKo*_*bel 5

您必须实现javax.swing.Timer而不是Thread.sleep(int),因为此代码行在EDT期间冻结所有GUI 直到Thread.sleep(int)结束.以下是演示如果GUI在EDT期间被延迟会发生什么Thread.sleep(int)