tags:

views:

153

answers:

2

I have a problem with my actionListener. It seems that the actionListener runs automatically before I click the button? The "This should not appear in the console before button click" appear in the console before I click the button".... This is strange.

.... 
button1.addActionListener(this); 
button2.addActionListener(this);
....
public void actionPerformed(ActionEvent e) {

   System.out.println("This should not appear in the console before button click");

   if (e.getSource()==button1)
      System.out.println ("answer1");

   else if (e.getSource()==button2)
      System.out.println ("answer2");
   .....
}
+4  A: 

You can tell where methods are being called from by calling Thread.dumpStack(). That will print the stack trace to the error stream (possibly the Java console). Alternatively use a debugger and place a break point on the first line of the method.

public void actionPerformed(ActionEvent e) {
   Thread.duumpStack();
   System.out.println("This should not appear in the console before button click");
   ...

BTW: I recommend not using EventObject.getSource. Instead add a new listener for every action.

So your example code would become:

button1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        System.out.println("answer1");
    } 
});
button2.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        System.out.println("answer2");
    } 
});

Unfortunately the boilerplate associated with anonymous inner classes is distinctly verbose, but the intention is clearer.

Tom Hawtin - tackline
I am very new to Java...I dont understand what do you mean by ..Instead add a new listener for every action ...
Jessy
@Tom: I know of several people who find it cleaner to have only one inner class instead of multiple anonymous classes. It seems like mainly a style issue to me.
Michael Myers
@mmyers: They're wrong.
Tom Hawtin - tackline
@Tom: Just plain wrong? No if's, and's, or but's? I personally tend to prefer the anonymous class version, but I don't see why it makes such a big difference.
Michael Myers
Using separate listeners means that you don't need to use ifs or switches, which makes your code cleaner. Also, if you need to add or remove a button, you do everything right there rather than having to add a case statement somewhere else (which may be several pages down).
James
Thanks a lot...will try that method.
Jessy
@Tom, @mmyers you are both wrong - non anonymous inner classes is the right way. Remember there are no absolutes... in the case of android the if is preferred for example.
TofuBeer
A: 

Also make sure that you have not added 'this' as an ActionListener to any other components that might be use before you click either of the buttons. You could also search your code for doClick() calls to make sure you dont call it programatically.

willcodejavaforfood