本文介绍了如何添加侦听多个按钮的动作侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚我对动作听众的错误。我正在关注多个教程,但是当我尝试使用动作监听器时,netbeans和eclipse会给我错误。

I'm trying to figure out what i am doing wrong with action listeners. I'm following multiple tutorials and yet netbeans and eclipse are giving me errors when im trying to use an action listener.

下面是一个简单的程序,我试图让按钮工作。

Below is a simple program that im trying to get a button working in.

我做错了什么?

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


public class calc extends JFrame implements ActionListener {



    public static void main(String[] args) {

        JFrame calcFrame = new JFrame();

        calcFrame.setSize(100, 100);
        calcFrame.setVisible(true);

        JButton button1 = new JButton("1");
        button1.addActionListener(this);

        calcFrame.add(button1);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button1)
    }

}

动作监听器从未注册,因为 if(e.getSource( )== button1)它看不到 button1 ,错误说无法找到符号。

the action listener is never registered because with the if(e.getSource() == button1) it cant see button1, errors saying cannot find symbol.

推荐答案

静态方法中没有这个指针。 (我不相信这段代码甚至会编译。)

There is no this pointer in a static method. (I don't believe this code will even compile.)

您不应该在静态方法中执行这些操作,例如 main() ;在构造函数中设置。我没有编译或运行它来查看它是否真的有用,但试一试。

You shouldn't be doing these things in a static method like main(); set things up in a constructor. I didn't compile or run this to see if it actually works, but give it a try.

public class Calc extends JFrame implements ActionListener {

    private Button button1;

    public Calc()
    {
        super();
        this.setSize(100, 100);
        this.setVisible(true);

        this.button1 = new JButton("1");
        this.button1.addActionListener(this);
        this.add(button1);
    }


    public static void main(String[] args) {

        Calc calc = new Calc();
        calc.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == button1)
    }

}

这篇关于如何添加侦听多个按钮的动作侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-06 07:28