I am trying to write a Minesweeper clone in Java for fun. I have a grid of JButtons whose labels I will change to represent the danger count, flags, etc.
My problem is, I don't know how to get a right click on a JButton to depress the button. I've done the following:
button.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
boolean mine = field.isMine(x, y);
if (e.isPopupTrigger()) {
button.setText("F");
}
else {
if (mine) {
button.setText("X");
}
}
}
});
This doesn't seem to be working at all; the "F" is never shown, only the "X" part. But more importantly, this does nothing for depressing the button.
EDIT: Macs have popup trigger happen on mousePress, not mouseClick.
EDIT: Here's the solution I worked out based off of accepted answer:
button.addMouseListener(new MouseAdapter(){
boolean pressed;
@Override
public void mousePressed(MouseEvent e) {
button.getModel().setArmed(true);
button.getModel().setPressed(true);
pressed = true;
}
@Override
public void mouseReleased(MouseEvent e) {
//if(isRightButtonPressed) {underlyingButton.getModel().setPressed(true));
button.getModel().setArmed(false);
button.getModel().setPressed(false);
if (pressed) {
if (SwingUtilities.isRightMouseButton(e)) {
button.setText("F");
}
else {
button.setText("X");
}
}
pressed = false;
}
@Override
public void mouseExited(MouseEvent e) {
pressed = false;
}
@Override
public void mouseEntered(MouseEvent e) {
pressed = true;
}
});
add(button);
I wouldn't use isPopupTrigger
but directly check for the right button:
button.addMouseListener(new MouseAdapter(){ public void mouseClicked(MouseEvent e){ boolean mine = field.isMine(x, y); if (e.getButton() == MouseEvent.BUTTON2) { button.setText("F"); } ...