类abstractButton中的方法addActionListener不能应用于给定的类型

时间:2014-02-11 19:51:57

标签: java swing

我正在尝试使用swing制作一个计算器,但是当我编译它时我遇到了一个问题,这是一个错误,类AbstractButton中的方法addActionListener无法应用于给定的类型。

我的代码是

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

public class Calculator extends JFrame implements ActionListener {
    private String str = "0";
    JTextField l_tf = new JTextField(100);
    JButton button[] = new JButton[31];
    Northwindow panelNorth = new Northwindow();
    Centerwindow panelCenter = new Centerwindow();

    Calculator(String l_s) {
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add("North", panelNorth);
        getContentPane().add("Center", panelCenter);

        setSize(300, 400);
        setVisible(true);
    }

    //Northwindow

    class Northwindow extends JPanel {
        public Northwindow() {
            Dimension textf = new Dimension(50, 50);
            setLayout(new GridLayout(0, 1));
            setBackground(new Color(230, 230, 255));
            l_tf.setPreferredSize(textf);
            add(l_tf);
        }
    }


    class Centerwindow extends JPanel {
        public Centerwindow() {
            setLayout(new GridLayout(0, 4));
            String key[] = {"ON", "Del", "C", "+/-", "1/x", "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+", "Sqrt", "Sqr", "Sin", "Cos", "^", "log", "ln", "tan", "(", ")", "pie"};

            Dimension but = new Dimension(80, 30);
            for (int i = 0; i < button.length; i++) {

                button[i] = new JButton(key[i]);
                button[i].setPreferredSize(but);
                add(button[i]);
                button[i].addActionListener(this);

                //before the on button is not clicked

                for (i = 0; i < button.length; i++)
                    button[i].setEnable(false);
                l_tf.setEditable(false);

            }
        }
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource == button[0])  // ON button
        {
            l_tf.setBackground(color.white);
            button[0].setLabel("OFF");
            for (i = 0; i < button.length; i++)
                button[i].setEnable(true);
            l_tf.setEditable(true);
            l_tf.setText(str);
        }
        if (e.getSource == button[1]) {
        }
    }

    public static void main(String... s) {
        Calculator c = new Calculator("Calculator");
    }
}

1 个答案:

答案 0 :(得分:4)

button[i].addActionListener(this);

这显示在Centerwindow内,但未实现ActionListener。由于Centerwindow是一个内部类,因此您可以访问封闭的Calculator实例并添加它,如果这是您要执行的操作:

button[i].addActionListener(Calculator.this);