Reputation: 61
I was wondering if it is possible that if a JButton is pressed twice then a button will disable itself, in other words it will .setEnabled(false);
This is the code i have so far. I want it so that if Respin is pushed twice then btnRespin will be set to false
//This is the code for spinning the wheels once hold is pressed
if (event.getSource() == btnHold1 && "THIS IS WHERE I NEED THE CODE FOR IF THE BUTTON IS PUSHED TWICE")
{
counter = 0;
timer1.stop();
btnHold1.setEnabled(false);
}
Upvotes: 0
Views: 1279
Reputation: 339
Try this :
private class ClickHandler extends MouseAdapter {
@Override
public void mouseClicked( MouseEvent ev ) {
if ( ev.getClickCount() >= 2 ) {
((JButton)ev.getSource).setEnabled( false );
}
}
}
mouseClicked event would handle your key pressed and released event.
Upvotes: 0
Reputation: 4084
If you use an actionListener and increment a counter for each event, you have a problem if the user clicks on the button, then 5 minutes later clicks on it again, it will see that second event as a double-click and disable the button. Presumably you want to disable it only if the user really double-clicks (within the system double-click interval), You can use your own timer to do this, or just use a MouseListener instead, with this code in it:
@Override
public void mousePressed( MouseEvent ev ) {
if ( ev.getClickCount() == 2 ) {
((JButton)ev.getSource).setEnabled( false );
}
}
Note that the user can still use the space bar to push the button, but hitting space twice rapidly will not be seen as a double-click.
Upvotes: 0
Reputation: 73
Yes, what you are trying to achieve is possible. If you want to count the no of clicks in that event you can use:
event.getClickCount() == 2
If you want to disable the button on a second click, ie: click once to enable then once more to disable. This is what appears to me you are trying to do.
event.getSource() == btnHold1 && (counter%2 == 0)
I would suggest to use the click event for that button and have an increment and check your counter. ex:
public counter = 0;
private void functionForButtonClick (Events, handlers etc..){
counter++;
if(counter%2 == 0){
btnHold1.setEnabled(false);
}
}
Upvotes: 0
Reputation: 417
you can use a click counter
like an int i = 0; and increase it every click
and check when it is above 1
Upvotes: 2