Wondering how one goes about testing which button was clicked in an actionperformed method. For example if I have 2 buttons named button1 and button2, and create an if statement what is the proper syntax, ive tried this but get errors. Where am i going wrong?

//declaring buttons
Panel buttonPanel = new Panel();
Button button1 = new Button("go");
Button button2 = new Button("stop");

//action performed method
public void actionPerformed(ActionEvent e)
{
    if(button1)
    {
       //what button1 will do
     }
    else
    {
       //what button2 will do
     }
}

check out the getSource() method for ActionEvents

Just as JamesCherrill said, your actionPerformed should look like this

public void actionPerformed (ActionEvent e) {
             if(e.getSource()==button1) {
                        //do stuff
                 }
              if(e.getSource()==button2) {
                      // do other stuff
                  }
}

@yancuto:
This is DaniWeb. We try to help people to learn Java skills here. That's why my post pointed him in the right direction, but left him to do his own research.
You gave him the complete code ready to copy & paste. So he copies it, cheats on his homework, and learns nothing. Please do NOT give complete solutions to homework questions here.

Sorry, won't do it again :P

@yancuto:
This is DaniWeb. We try to help people to learn Java skills here. That's why my post pointed him in the right direction, but left him to do his own research.
You gave him the complete code ready to copy & paste. So he copies it, cheats on his homework, and learns nothing. Please do NOT give complete solutions to homework questions here.

I totally get that, I didnt want the answer as just as you said I wont learn that way. Im very excited in learning all that i can as a java programmer. My textbook has no mention of the getSource method as far as what has been covered thus far.That being said, i actually found my issue and im almost embarrassed to say what it was, lol. I had not added any actionlistener to any of the buttons!!

button1.addActionListener(this)
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.