开发者

Mouse Events taking random number of clicks in java

开发者 https://www.devze.com 2023-02-19 15:19 出处:网络
The object of the code so far is the trade turns back and forth between player 1 and player 2 and allow the player whoose turn it is to turn one of their pieces invisible (Set icon to null). It works

The object of the code so far is the trade turns back and forth between player 1 and player 2 and allow the player whoose turn it is to turn one of their pieces invisible (Set icon to null). It works right now, turns trade back and forth and pieces turn invisible on click, but sometimes it is not the first click. It might take 3 or 4 clicks on a correct piece before it changes to null. Is there a reason this would be happening?

Robo2 is the icon for the first players pieces, robo1 is the icon for the second players pieces. The pieces are stored in an array of JButtons 开发者_Go百科in the program with the icon set as the image of player 1 or player 2 piece.

public void mouseClicked(MouseEvent me) {
    JButton clicked = (JButton)me.getSource();

    if (player1) {
        if (clicked.getIcon() == Robo2) {
            clicked.setIcon(null);
            player1 = false;
            player2 = true;
        }
        else {
        }
    }
    else if (player2) {
        if (clicked.getIcon() == Robo1) {
            clicked.setIcon(null);
            player1 = true;
            player2 = false;
        }
        else {
        }
    }
}


Figured out a solution, changing the mouse listener to an action listener solved the missing clicks problems. Using the events sent when the button gets clicked rather than detecting clicks themselves on the button. Thanks for the help.


when you double-click (or triple-click, or quadruple-click) something in Java you get this:

  • 1st click: MouseEvent, clickCount = 1
  • 2nd click: MouseEvent, clickCount = 2
  • 3rd click: MouseEvent, clickCount = 3

etc.

so imagine you're double clicking the button by player1. The first event would change the player to player 2; the second event would change it right back to player1!

To remedy this situation - check clickCount (me.getClickCount()) and ignore the event if it isn't 1. Like

if (me.getClickCount() > 1) {
  return;
}
// or else proceed as you do now
0

精彩评论

暂无评论...
验证码 换一张
取 消