1

I'm a Java beginner and now as I come down to work with interfaces, I want to know what really happens. I suppose a good example is the ActionListener interface.

All I know about interfaces is, that it forces you to implement the methods given by the interface. But what I don't get, where the actionPerformed(ActionEvent e) method is called. And are there any simple examples to show me what happens in the background? Thanks anyway.

WayneEra
  • 133
  • 1
  • 6
  • Take a look at [this](http://docs.oracle.com/javase/tutorial/uiswing/events/intro.html) Oracle tutorial. Keep an eye out for the `actionPerformed` method names. – npinti Apr 01 '15 at 13:44
  • Q: Does Shane Voisard's response answer your question? If you look at his stack traceback, you'll see 1) the Java runtime is always looking for "Events", 2) for each event, it calls "java.awt.EventQueue.dispatchEvent()", 3) which ultimately calls the code (the event hander) you registered with "addActionListener()". – FoggyDay Apr 01 '15 at 16:47

3 Answers3

1

If you want details, log an Exception from inside ActionListener#actionPerformed:

import java.io.*;
import javax.swing.*;
import java.awt.event.*;

public class ListenerTracer extends JPanel {

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() { createAndShowGUI(); }
        });
    }

    public ListenerTracer() {
        JButton b1 = new JButton("Press me");
        b1.setVerticalTextPosition(AbstractButton.CENTER);
        b1.setHorizontalTextPosition(AbstractButton.CENTER);
        b1.addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent event) {
                Exception e = new Exception();
                e.printStackTrace();
            }
        });
        add(b1);

        JTextArea textArea = new JTextArea("actionListener printstacktrace:\n", 50, 50);
        JScrollPane scrollPane = new JScrollPane(textArea);
        add(scrollPane);
        Console.redirectOutput(textArea);
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("ListenerTracer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ListenerTracer contentPane = new ListenerTracer();
        contentPane.setOpaque(true);
        frame.setContentPane(contentPane);
        frame.pack();
        frame.setVisible(true);
    }

    private static class Console implements Runnable {
        JTextArea displayPane;
        BufferedReader reader;

        private Console(JTextArea displayPane, PipedOutputStream pos) {
            this.displayPane = displayPane;
            try {
                PipedInputStream pis = new PipedInputStream(pos);
                reader = new BufferedReader( new InputStreamReader(pis) );
            }
            catch (IOException e) {}
        }

        public void run() {
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    displayPane.append( line + "\n" );
                    displayPane.setCaretPosition(displayPane.getDocument().getLength());
                }
                System.err.println("im here");
            }
            catch (IOException ioe) {
                JOptionPane.showMessageDialog(null, "Error redirecting output : "+ioe.getMessage());
            }
        }

        public static void redirectOutput(JTextArea displayPane) {
            PipedOutputStream pos = new PipedOutputStream();
            System.setErr(new PrintStream(pos, true) );
            Console console = new Console(displayPane, pos);
            new Thread(console).start();
        }
    }
}

Clicking the "Press Me" button produces this output:

actionListener printstacktrace: java.lang.Exception at ListenerTracer$2.actionPerformed(ListenerTracer.java:21) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) at java.awt.Component.processMouseEvent(Unknown Source) at javax.swing.JComponent.processMouseEvent(Unknown Source) at java.awt.Component.processEvent(Unknown Source) at java.awt.Container.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source) at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source) at java.awt.Container.dispatchEventImpl(Unknown Source) at java.awt.Window.dispatchEventImpl(Unknown Source) at java.awt.Component.dispatchEvent(Unknown Source) at java.awt.EventQueue.dispatchEventImpl(Unknown Source) at java.awt.EventQueue.access$400(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.awt.EventQueue$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.awt.EventQueue$4.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source) at java.awt.EventQueue.dispatchEvent(Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source) at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.pumpEvents(Unknown Source) at java.awt.EventDispatchThread.run(Unknown Source)

I borrowed the console redirect code from camickr's answer to redirecting-system-out-to-jtextpane.

Community
  • 1
  • 1
Shane Voisard
  • 1,145
  • 8
  • 12
0

That will be called when the user does something. Click a button, select a menu. Each one of the actionListeners is called for a particular event. I think right now, you need not worry exactly where it is called, just where, and why.

Ayman
  • 11,265
  • 16
  • 66
  • 92
  • Thanks for the answer. Well I know that it is called when the specific element is clicked, I have made little GUIs with swing, and they work. But for me it's hard to comprehend where the specific code is, that invokes actionPerformed(). Is it somewhere in the JButton class? – WayneEra Apr 01 '15 at 13:48
0

In the case of a JButton, its superclass AbstractButton calls the actionPerformed method through the method fireActionPerformed which is a protected method. If you check the source code you'll see that it constructs an ActionEvent object and calls actionPerformed using it as an argument.

TNT
  • 2,900
  • 3
  • 23
  • 34