In Java's swing package, I was wondering how to detect when a JButton is pressed. Is there a function that is called when the button is pressed? Thanks
Asked
Active
Viewed 1.1k times
-1
-
2have you tried reading on eventhandlers? – Francis Fuerte Jul 24 '13 at 02:43
-
1Take a look at [How to use buttons](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html) and [How to write an Action Listener](http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html) – MadProgrammer Jul 24 '13 at 02:44
-
Possible of duplicate http://stackoverflow.com/questions/7505279/test-if-a-javax-swing-jbutton-is-pressed-down – gjman2 Jul 24 '13 at 02:44
-
Do you really mean pressed, or do you mean pressed and released (which most people would refer to as clicked)? – camickr Jul 24 '13 at 02:47
1 Answers
3
Yes, when you deal with button pressing, you want to add what is known as an action listener. First, you must
import java.awt.event.ActionListener;
then you can do the following
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// this makes sure the button you are pressing is the button variable
if(e.getSource() == button) {
// do action necessary code
}
}
});

user2277872
- 2,963
- 1
- 21
- 22
-
1
-
1Not the down voter, but it could possibly be that the question is so simple and lacks any kind of effort by the poster, that people feel that it simple should be answered, or that it shouldn't provide a spoon feed answer. Also, `e.getSource() == button` isn't always the best choice for comparing the source of the event, as you may not have access to the code that registered the listener, instead you should be using `ActionEvent#getActionCommand` or better still, the [Action API](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html) – MadProgrammer Jul 24 '13 at 03:08
-
Well i've never learned the ActionEvent#getActionCommand way of doing that, I've always done getting the source of the object – user2277872 Jul 24 '13 at 03:12