调度事件后不调用 processEvent

processEvent is not called after dispatching an event

如果我向 JButton 发送一个(操作)事件,则不会调用按钮的 processEvent 方法。

在下面的示例中,我认为将执行以下步骤

  1. b1 将事件分派给 b2dispatchEvent 被调用)
  2. b2 处理事件 (processEvent 被调用)
  3. b2 执行其动作侦听器

但是第2步和第3步不会执行。谁能解释为什么?

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

public class JavaApplication {

  public static void main(String[] args) {
    final JFrame frame = new JFrame();
    final JPanel panel = new JPanel();
    final JButton b2 = new JButton("b2") {
      @Override
      public void processEvent(AWTEvent evt) {
        System.out.println("action event will be processed" + evt.toString());
        super.processEvent(evt);
      }
    };

    b2.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println("b2 clicked");
      }
    });

    final JButton b1 = new JButton("b1");

    b1.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        System.out.println("b1 clicked");
        final ActionEvent e2 = new ActionEvent(e.getSource(), e.getID(), "Redispatch-Event");
        b2.dispatchEvent(e2);

      }
    });

    panel.add(b1);
    panel.add(b2);
    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}

您可能希望发送按钮 MouseEvent:

MouseEvent e2 = new MouseEvent(
    (Component)e.getSource(), MouseEvent.MOUSE_CLICKED, e.getWhen(), 0, 1,1, 1, false );