Button上的Java Actionlistener

Kar*_*ski 3 java actionlistener

import java.awt.*;

public class TestButton {
  private Frame f;
  protected Button b;

  public TestButton() {
    f = new Frame("Test");
    b = new Button("Press Me!");
    b.setActionCommand("ButtonPressed");
  }

  public void launchFrame() {
    b.addActionListener(new ButtonHandler());
    f.add(b, BorderLayout.CENTER);
    f.pack();
    f.setVisible(true);
  }

  public static void main(String args[]) {
    TestButton guiApp = new TestButton();
    guiApp.launchFrame();
  }
}

import java.awt.*;
import java.awt.event.*;

public class ButtonHandler extends TestButton implements ActionListener {
  public void actionPerformed(ActionEvent e) {
      Object source = e.getSource();
      if(source==b)
      {
            System.out.println("Action occurred");
            System.out.println("Button's command is: "
                               + e.getActionCommand());
      }
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试在按下按钮b但不使用getSource时调用ActionEvent.

Hov*_*els 8

你滥用继承权.ButtonHandler类不应扩展TestButton类,因为处理程序类中的b变量引用与显示的对象完全不同的Button对象.我建议:

  • 使用Swing库,而不是AWT库
  • 您可以从ActionEvent的getSource()方法中获取JButton 并直接使用它.
  • 如果需要在处理程序中引用GUI,请在处理程序的构造函数中传入引用.
  • 不要滥用继承来解决不涉及继承问题的问题.

例如:

import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class TestButton extends JPanel {
   private JButton btn = new JButton(new ButtonAction("Press Me!", "ButtonPressed"));

   public TestButton() {
      add(btn);
   }

   private static void createAndShowGUI() {
      TestButton testButton = new TestButton();

      JFrame frame = new JFrame("TestButton");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(testButton  );
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

@SuppressWarnings("serial")
class ButtonAction extends AbstractAction {
   public ButtonAction(String name, String actionCommand) {
      super(name);
      putValue(ACTION_COMMAND_KEY, actionCommand);
   }

   @Override
   public void actionPerformed(ActionEvent evt) {
      System.out.println("Button's actionCommand is: " + evt.getActionCommand());
   }
}
Run Code Online (Sandbox Code Playgroud)