ActionListener实现

时间:2016-04-15 09:21:00

标签: java swing netbeans interface

Netbeans将ActionListener视为用户定义的界面,并显示错误

  

方法不会覆盖或实现超类型方法

还有一个奇怪的事情,如果我删除了行import java.awt.event.*没有任何意义,它不会出错

package mycalculator;

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

public class MyCalculator extends JFrame implements ActionListener {
    private JButton Cbtn;
    private JButton eqbtn;
    private JButton opbtn[] = new JButton[4];
    private JButton digbtn[] = new JButton[10];
    private JLabel disp;

    public MyCalculator() {
        Container c = this.getContentPane();
        c.setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(212,290);
        this.setResizable(false);

        disp = new JLabel("0");

        disp.setBounds(5,10,190,30);
        c.add(disp);

        Cbtn =  new JButton("C");
        Cbtn.setBounds(105, 200,45,45);
        c.add(Cbtn);

        eqbtn = new JButton("=");
        eqbtn.setBounds(5,200,45,45);
        c.add(eqbtn);

        for (int i = 0; i < digbtn.length; i++) {
            digbtn[i] = new JButton(i+"");
            if (i == 0) {
                digbtn[i].setBounds(55,200,45,45);   
            } else {
                digbtn[i].setBounds(5+((i-1)%3)*50,50+((i-1)/3)*50,45,45);
            }
            c.add(digbtn[i]);
            //digbtn[i].addActionListener(this);
        }

        String str [] = {"+", "-", "*", "/"};

        for (int i = 0; i < opbtn.length; i++) {
            opbtn[i] = new JButton(str[i]);
            opbtn[i].setBounds(155,50+50*i, 45,45);

            c.add(opbtn[i]);
            //opbtn[i].addActionListener(this);
        }

         disp.setBorder(BorderFactory.createLineBorder(Color.black));
         disp.setHorizontalAlignment(SwingConstants.RIGHT);

    }

   //here  
   @Override
   public void actionPerformed(ActionEvent e) {
        JButton pressed = (JButton)e.getSource();

        if (disp.getText().equals("0")) {
            disp.setText(pressed.getText());
        } else {
            disp.setText(disp.getText().concat(pressed.getText()));
        }
    }   

    public static void main(String[] args) {
         MyCalculator frmCalc1 = new MyCalculator();
         frmCalc1.setVisible(true);
    }
}

0 个答案:

没有答案