public class ClickListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
                System.out.println(e.getSource().setText("Changed"));
        }
    }

Eclipse tells me that setText() is undefined for type Object.
This tells me that getSource() doesn't actually return the JButton object. How do should I do this then? How I change the text of the clicked button without having to set up a bunch of if-statements for all possible buttons?

Recommended Answers

All 4 Replies

Here's a link to the API documentation for it:
http://docs.oracle.com/javase/6/docs/api/java/util/EventObject.html#getSource()

As you'll notice its return type is Object, so you'll need to cast to whatever the type of your event source is.
Before doing so it is always a good idea to use the instanceof operator to check if casting is possible.

Example:

Object source = e.getSource();

if (source instanceof JButton) {
    JButton button = (JButton) source;
    button.setText("Changed");
}

let's say you have a class that extends JFrame and implements ActionListener, you may want to do this, if within the actionPerformed you need to have access to class members of the class in which the component to which you'll add the listener is located.

let's now assume you have three buttons in that class, being bA, bB and bC.
to all three, you add that same class as ActionListener:

bA.addActionListener(this);
bB.addActionListener(this);
bC.addActionListener(this);

so, when you click on each of these buttons, you'll run the actionPerformed(ActionEvent event) method of that class, but there is only one such method allowed. so, if you want to run different code based on which button is clicked:

public void actionPerformed(ActionEvent event){
  if ( event.getSource() == bA ){
    // run the code belonging to button bA  
  }
  else if ( event.getSource() == bB ){
    // run the code for button bB
  }
  else if ( event.getSource() == bC ){
    // run the code for button bC
  }
}

If you decide to follow the approach explained in stultuske's post then there's no need to add instanceof checks since the identity comparisons (== on reference types) will guarantee you that the source is a particular object, and you'll know what you can safely cast it to.

Thanks everyone! Casting it worked great.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.