首页 > 解决方案 > Main 必须是抽象的,Listener 的 ActionPerformed 方法问题

问题描述

这个程序只是为了自学Java。在进行编码时,我遇到了以下问题:当我在 Main 类中实现的按钮使用侦听器时出现错误(红色下划线)。

由于我是学习 Java 的新手,如果解决方案很明显,请原谅。我已经尝试将 main 和actionPerfomed方法都抽象化,但这会导致进一步的问题。@Override之前的actionPerformed方法我也试过。

这是代码:

// Java program to create a blank text
// field of definite number of columns.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Main extends JFrame implements ActionListener {
    // JTextField
    static JTextField t;

    // JFrame
    static JFrame f;

    // JButton
    static JButton b;

    // label to diaplay text
    static JLabel l;

    // default constructor
    Main()
    {
    }

    // main class
    public static void main(String[] args)
    {
        // create a new frame to stor text field and button
        f = new JFrame("textfield");

        // create a label to display text
        l = new JLabel("nothing entered");

        // create a new button
        b = new JButton("submit");

        // create a object of the text class
        Main te = new Main();

        // addActionListener to button
        b.addActionListener(te);

        // create a object of JTextField with 16 columns
        t = new JTextField(16);

        // create a panel to add buttons and textfield
        JPanel p = new JPanel();

        // add buttons and textfield to panel
        p.add(t);
        p.add(b);
        p.add(l);

        l.setOpaque(true);
        // add panel to frame
        f.add(p);

        // set the size of frame
        f.setSize(300, 300);

        p.setBackground(Color.cyan);

        f.show();
    }

    // if the button is pressed
    public void actionPerformed(java.awt.event.ActionEvent e, JPanel p)
    {
        String s = e.getActionCommand();
        if (s.equals("submit")) {
            // set the text of the label to the text of the field
            if(t.getText().equals("hue")) {

                p.setBackground(changeColor());
            }
            l.setText(t.getText());

            // set the text of field to blank
            t.setText(" ");
        }
    }
    public Color changeColor() {
        int r = (int)(Math.random())*256;
        int g = (int)(Math.random())*256;
        int b = (int)(Math.random())*256;
        Color color = new Color(r,g,b);
        return color;
    }
}

标签: javaswingjframejbuttonactionlistener

解决方案


这里:

public void actionPerformed(java.awt.event.ActionEvent e, JPanel p)

应该

public void actionPerformed(java.awt.event.ActionEvent e)

您必须完全匹配预期的签名!您不能只向您应该覆盖的方法添加更多参数!

最后,您会看到,单击按钮时调用该方法的不是您的代码。Swing 框架会做到这一点。你告诉它:当这个东西发生一个动作时,然后回调我的代码。你怎么期望这个框架知道你想要传递一个额外的参数?!

除此之外:将@Override放在您希望覆盖方法的任何方法前面(就像在这种情况下,您正在实现该接口的方法)成为您的习惯。因为那时编译器可以告诉你什么时候犯这样的错误!

但是,当然,您添加了该参数以便侦听器可以使用它。所以:让侦听器知道它,例如通过向您在构造函数中初始化的 Main 类添加一个字段!因此,在为 Main 实例执行new时,不要将面板传递给那个方法(它不能去的地方) 。


推荐阅读