简体   繁体   中英

Where is the actionperfomed() method called?

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.

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.LightweightDis patcher.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.pumpEv entsForFilter(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 .

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM