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'); ..... }
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.BTW: I recommend not using
EventObject.getSource. Instead add a new listener for every action.So your example code would become:
Unfortunately the boilerplate associated with anonymous inner classes is distinctly verbose, but the intention is clearer.