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);
Minesweeper clone http://grab.by/1y9z
BUTTON2 = Middle Click and MouseEvent. BUTTON3 = Right Click.
The JButton class is used to create a labeled button that has platform independent implementation. The application result in some action when the button is pushed. It inherits AbstractButton class.
JButton class provided by Swing is totally different from Button which is provided by AWT. It is used to add platform independent button in swing application. Swing buttons are extended from the AbstractButton class that is derived from JComponent.
Button can't be pressed by right click. Add such a lines to you mouse listener
mousePressed:
if(isRightButtonPressed) {underlyingButton.getModel().setPressed(true));
mouseReleased:
if(needReset) {underlyingButton.getModel().setPressed(false));
or do there whatever want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With