【问题标题】:How to fix error in action listener in java?如何修复java中动作监听器中的错误?
【发布时间】:2021-03-02 01:54:22
【问题描述】:

所以我的代码中有一个错误,我不知道为什么会发生,因为我遵循了老师的指示。每当我在addActionListener 中添加参数时,都会出现此错误。

这是我的全部代码

import java.awt.FlowLayout;
import java.awt.event.*;
import java.sql.Date;
import javax.swing.*;

public class DateFrameButton  implements ActionListener{

    public static void main(String[] args) {
        final int FIELD_WIDTH = 20;
        JFrame frame = new JFrame();
        JButton dateButton = new JButton("Date");
        JTextField textField = new JTextField(FIELD_WIDTH);
        String dateAndTime = new Date(FIELD_WIDTH).toString();
        
        
        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                textField.setText(dateAndTime);
            }
        };
        
        dateButton.addActionListener(listener);
        
        frame.add(dateButton);
        frame.add(textField);
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent event) {
        // TODO Auto-generated method stub
        
    }

}

这是我得到错误的地方:

dateButton.addActionListener(listener);

错误提示

The method addActionListener(java.awt.event.ActionListener) in the type AbstractButton is not applicable for the arguments (ActionListener)

我真的不知道为什么会出现这个错误

【问题讨论】:

  • 你的类实现了ActionListener。您还可以在 main 方法中实例化一个新的 ActionListener 并将其添加到按钮中。你不应该两者都做。

标签: java swing jframe actionlistener


【解决方案1】:
dateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(ActionEvent event) {
                textField.setText(dateAndTime);
            }
         });

按钮对传递的参数感到困惑。是你实现的 ActionListener 类吗?创建的实例?它需要一个java.awt.event.ActionListener,,但它收到一个ActionListener

不要创建 ActionListener 的实例,只需确保传递了 java.awt.event.ActionListener

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    相关资源
    最近更新 更多