Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将ActionListener作为构造函数参数接收并存储,以便类中的其他方法可以将该ActionListener添加到按钮?_Java - Fatal编程技术网

Java 将ActionListener作为构造函数参数接收并存储,以便类中的其他方法可以将该ActionListener添加到按钮?

Java 将ActionListener作为构造函数参数接收并存储,以便类中的其他方法可以将该ActionListener添加到按钮?,java,Java,所以我有一个NumberPad类,带有一个类构造函数NumberPad(ActionListener)。然后,我需要将侦听器添加到下面NumberPad类中addButton()方法中的按钮。 这就是我的教授要求这样做的具体方式。他甚至说“修改NumberPad类中的构造函数,使其现在被传递一个ActionListenerobject,并存储在名为listener的私有属性中”。但是我不知道如何存储Action Listener对象 import java.awt.event.*; impo

所以我有一个NumberPad类,带有一个类构造函数NumberPad(ActionListener)。然后,我需要将侦听器添加到下面NumberPad类中addButton()方法中的按钮。 这就是我的教授要求这样做的具体方式。他甚至说“修改NumberPad类中的构造函数,使其现在被传递一个ActionListenerobject,并存储在名为listener的私有属性中”。但是我不知道如何存储Action Listener对象



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

;/**
 * A numeric keypad
 */
public class NumberPad extends    JPanel
{
    /**
     * Default Constructor
     */
    public NumberPad(ActionListener listener)
    {
        super();
        setupLayout();
    }

    /**
     * Setup and layout this NumberPad
     */
    private void setupLayout()
    {
        // Setup and layout this NumberPad
        GridLayout pinpad = new GridLayout (4, 3);
        setLayout(pinpad);
        addButton("1");
        addButton("2");
        addButton("3");
        addButton("4");
        addButton("5");
        addButton("6");
        addButton("7");
        addButton("8");
        addButton("9");
        addButton("Del");
        addButton("0");
        addButton("C");
    }
    
    private void addButton(String anyString)
    {
        JButton anyButton = new JButton(anyString);
        add(anyButton);
    }
    
}```
公共类NumberPad扩展了JPanel
{
私人行动听者;
/**
*默认构造函数
*/
public NumberPad(ActionListener侦听器)
{
超级();
//在此处存储为私有属性
this.listener=listener;
setupLayout();
}
/**
*设置和布局此数字广告
*/
专用布局()
{
//设置和布局此数字广告
GridLayout pinpad=新的GridLayout(4,3);
设置布局(pinpad);
添加按钮(“1”);
添加按钮(“2”);
添加按钮(“3”);
添加按钮(“4”);
添加按钮(“5”);
添加按钮(“6”);
添加按钮(“7”);
添加按钮(“8”);
添加按钮(“9”);
添加按钮(“Del”);
添加按钮(“0”);
添加按钮(“C”);
}
私有void addButton(字符串anyString)
{
JButton anyButton=新JButton(anyString);
添加(任意按钮);
//您可以使用'this.listener'访问存储的私有属性
}
}