Question

I am pretty new to programming and am trying to make a Minesweeper GUI. The game worked perfectly right clicking a JToggleButton displayed a "B" for bomb on the button, but when I replaced the setText() with setIcon() in the mouselistener it shows the icon when both left and right clicking occurs. I didn't have this problem when setText().

    public void mousePressed(MouseEvent e){
        if(e.isMetaDown())
            if(btnPresses == 0)
            {
                startTime = System.currentTimeMillis();
                btnPresses++;
            }
            //if(btn[y][x].getText().equals("B"))
            if(btn[y][x].getIcon()==flag)
            {
                //btn[y][x].setText("");
                btn[y][x].setIcon(null);
                if(bombs[y][x]!=BOMB)
                    markers++;
            }
            else
            {
                //btn[y][x].setText("B");
                btn[y][x].setIcon(flag);
                if(bombs[y][x]==BOMB)
                    markers++;
                else
                    markers--;
            }

I added a btn[y][x].setIcon(null) to the actionlistener, which causes the flag icon to appear only briefly when left clicking but I'd rather it not appear at all.

Was it helpful?

Solution

You need to distinguish between a left mouse button click, MouseEvent.BUTTON3, and a right mouse button click, MouseEvent.BUTTON3, and then act accordingly. For example, when I did something like this, I set the "flag" boolean in my model (using MVC) via:

@Override
public void mousePressed(MouseEvent e) {
   if (e.getButton() == MouseEvent.BUTTON3) {
      model.upDateButtonFlag();
   }
}

The MouseListener should be used only to set or unset the flag. Otherwise you should have your JButton respond via its ActionListener for left button clicks.

OTHER TIPS

Add a System.err.println("" + System.currentTimeMillis() + " " + e); to the beginning of your handler. I strongly suspect your code is being called more times than you think - as a single click can generate multiple events. Once you know what is going on, it should be easy to fix.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top