Search code examples
javaswingjoptionpane

Message dialog reappears over and over


We made a method that will determine where our image is in our frame. If the image is in a certain part of the frame it will show a message dialog and we will return to our main JPanel ( we're making a minigolf game ;) )

The problem is that when the message dialog appears, it keeps reappearing after he switched to our main Panel. Here's the code:

    package Project;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class Blackhole 
{
Image blackhole;
int xblack;
int yblack;
public final int breedte=75;
public final int hoogte=75;
public String afbeelding2;
public Atoom atoom;
public Frame venster;
public SpelPaneel x;

public Blackhole(int xblack, int yblack, String afbeelding2)
{
    this.xblack = xblack;
    this.yblack = yblack;
    blackhole = new ImageIcon(getClass().getResource(afbeelding2)).getImage();
}

public void tekenblackhole(Graphics g)
{
    g.drawImage(blackhole,xblack,yblack,75,75,null);
}

public boolean gameover(Atoom atoom) 
{
    return ((atoom.xpositie +atoom.BREEDTE > this.xblack) && (atoom.xpositie < this.xblack + this.breedte) && (atoom.ypositie + atoom.HOOGTE>this.yblack && atoom.ypositie<this.yblack+this.hoogte )) ;  

}

And this is the method we call upon in our class where the playing happens.

    if (blackhole.gameover(atoom))
    {

        JOptionPane.showMessageDialog(null, "You're Goneee in The Black Hole !!");
        venster.switchPanel();
    }

Solution

  • You need to have a boolean variable which will tell you if the message has already been shown. Something like

    if (blackhole.gameover(atoom) && !messageHasBeenShown)
    {
            messageHasBeenShown = true;
            JOptionPane.showMessageDialog(null, "You're Goneee in The Black Hole !!");
            venster.switchPanel();
    }
    

    and messageHasBeenShown = true; somewhere before.