有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将ActionEvent添加到JButton,以便在单击它时触发事件?

我希望能够将ActionListener添加到JButton,但似乎无法使其正常工作

我已经尝试添加ActionListener和ActionEvent,但两个方法都没有触发ActionPerformed方法

我不知道一个奇怪的方面是编译器让我去掉@Override关键字,因为接口是用来创建变量的,而不是实现的

这有区别吗?我相信你可以这样做,但我想我只是有点偏离了目标

代码:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;

public class testInterfaces2 {
    static ActionListener m;
    static ActionEvent me;

    testInterfaces2() {
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println("Mouse Clicked");
    }

    public static void main(String[] args) {
         JFrame f = new JFrame("Test");

         f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
               System.exit(0);
            }
         });

         JButton pButton = new JButton("Print");
         pButton.addActionListener(m);
         //pButton.addActionListener(m.actionPerformed(me));

         f.add("Center", pButton);
         f.pack();
         f.setVisible(true);
    }
}

共 (3) 个答案

  1. # 1 楼答案

    I did not one curious aspect was the the compiler made me take off the @Override keyword since the interface is used to create a variable and not implemented.

    这应该突出显示了您的第一个问题,testInterfaces2类不能重写actionPerformed,因为它未在父类的任何部分或其父类中定义。这是因为testInterfaces2没有直接或间接(通过继承)实现ActionListener

    您的第二个问题是mnull,您从未初始化过它

    更详细地看一下How to write ActionListeners

  2. # 2 楼答案

    我认为最好为每个按钮定义一个新的ActionListener。像这样

    JButton pButton = new JButton();
    
    pButton.addActionListener(new ActionListener() {
    
            @Override
            public void actionPerformed(ActionEvent e) {
                //throw new UnsupportedOperationException("Not supported yet.");
                System.exit(0);
            }
        });
    
  3. # 3 楼答案

    它应该是这样的,并删除不需要的ActionListenerActionEvent变量

    public class testInterfaces2 implements ActionListener{
    
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Mouse Clicked");
        }
    
        ...
        JButton pButton = new JButton("Print");
        pButton.addActionListener(this); 
    }
    
    1. @Override除了对重写的方法进行编译时检查之外,不做任何额外的事情

    2. 简单地说,您需要一个实现ActionListener的类,显然它实现了actionPerformed()方法。只需创建该类的对象并传入addActionListener()方法