How to detect the origin Button of an ActionEvent?

T

Tom Parson

Assume the user clicked on a button which in turn results in an ActionEvent e.
Is there a way to detect in actionperformed() from which button the click was originally coming?

A statement like

public void actionPerformed(ActionEvent e){
if (e.getComponent() = mybutton2) ...

does not work.

Tom
 
T

Thomas Fritsch

Tom said:
Assume the user clicked on a button which in turn results in an ActionEvent e.
Is there a way to detect in actionperformed() from which button the click was originally coming?

A statement like

public void actionPerformed(ActionEvent e){
if (e.getComponent() = mybutton2) ...
You probably want
if (e.getSource() == mybutton2) ...
does not work.
See also
<http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/ActionEvent.html>
and scroll down to "Methods inherited from class java.util.EventObject"
 
M

Mark

if (e.getSource() == mybutton2)

Also, make sure that you have set up the proper listener for the
selection event, something like:

mybutton2.addActionListener(this);

(Assumes your code is, for example, extending a JFrame, and that the
JFrame is listening for selections of mybutton2, and that the JFrame you
have extended has the actionPerformed() method.)
 
K

klynn47

Yes. You can use getSource(). It will give you a reference to the
object that caused the event.

Remember that when you use == between object references, it determines
if the references point to the same object in memory.
 
C

Christian Kaufhold

Followup-To ignored and reset to clj.gui.

In comp.lang.java.gui Tom Parson said:
Is there a way to detect in actionperformed() from which button the click was originally coming?
A statement like
public void actionPerformed(ActionEvent e){
if (e.getComponent() = mybutton2) ...


getSource()

There are other things in the standard API that can fire ActionEvents,
not just buttons (or components). Which ones?



Christian
 
R

Richard F.L.R.Snashall

Tom said:
Assume the user clicked on a button which in turn results in an ActionEvent e.
Is there a way to detect in actionperformed() from which button the click was originally coming?

A statement like

public void actionPerformed(ActionEvent e){
if (e.getComponent() = mybutton2) ...

does not work.

Did you mean:

public void actionPerformed(ActionEvent e){
if (e.getComponent() == mybutton2) ...

by any chance? If so, does it make a difference to your situation?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top