Java – JPanel freezes my entire application when trying to draw

I'm writing the school project of Oregon Trail, and I'm implementing the hunting mini game We are using a model view demonstrator with a card layout When huntingpanel switches to it, run is called and joptionpane appears, but then the whole application freezes and I have to force exit I wrote the whole hunting game in a separate project and just brought the file to the Oregon Trail game It works well with its own JFrame in its own project I don't know what to do

I call this the initialization panel, switch to it, and then run the game

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

This is my run method

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();
}

The following are other methods used

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();
    }
}

Solution

You must implement javax swing. Timer instead of thread Sleep (int), because this line of code freezes all GUIs during EDT until thread Sleep (int) ends This is a demonstration if thread. Is passed during EDT Sleep (int) what happens when the GUI is delayed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>