3

Im trying to make a java game where when the players health reaches 0 the game should end but currently when my progress bar reaches 0 nothing happens here is my code is there something wrong with it?

JProgressBar healthProgressBar = new JProgressBar();
    lblHealth.setLabelFor(healthProgressBar);
    healthProgressBar.setStringPainted(true);
    healthProgressBar.setValue(100);
    healthProgressBar.setMinimum(0);
    healthProgressBar.setBounds(318, 103, 166, 20);
    mainGame.add(healthProgressBar);

    if(healthProgressBar.getValue() <= healthProgressBar.getMinimum())
    {
        frame5.setVisible(false);
        frame7.setVisible(true);
    }
  • I assume that the main loop of your game is later in your code, so the condition here is evaluated right after adding th bar to the game, not when your game use it, you catn try a `progressBar.setValue(0);` if you want to check if your bar works, but you may have to call your condition inside your main loop somehow... – aveuiller Apr 10 '15 at 15:06
  • 1
    See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) – Andrew Thompson Apr 10 '15 at 15:35

3 Answers3

3

You're calling this code,

if(healthProgressBar.getValue() <= healthProgressBar.getMinimum())

in the same region where you create your JProgressBar and not where the state of the JProgressBar is being changed, so it makes sense that the if block test will never be true. A solution is to call this if test where your JProgressBar is being changed. But also re-think your desire to swap JFrames. Instead the user is much better off if you would re-set a single game JFrame.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
3

You are actually checking it right after setting the value to 100, so it always returns false.

Instead, you can use a listener for example:

healthProgressBar.addChangeListener(e -> {
    if (healthProgressBar.getValue() <= healthProgressBar.getMinimum()) {
        frame5.setVisible(false);
        frame7.setVisible(true);
    }
});

Other way would be changing the frames where you set the value to the healthProgressBar.

Bubletan
  • 3,833
  • 6
  • 25
  • 33
0

You are checking the value only once, when it is still 0

SWdV
  • 1,715
  • 1
  • 15
  • 36