我正在尝试将JPanel添加到实现actionListener的类中,如下所示:

JPanel jp2 = new JPanel();

        RangBazi red = new actionListenerClass (Color.RED, jp2);
        RangBazi green = new actionListenerClass (Color.GREEN, jp2);
        RangBazi blue = new actionListenerClass (Color.BLUE, jp2);

        JButton bred = new JButton("red");
        JButton bgreen = new JButton("green");
        JButton bblue = new JButton("blue");

        bred.addActionListener(red);
        bgreen.addActionListener(green);
        bblue.addActionListener(blue);
        jp2.add(bred);
        jp2.add(bgreen);
        jp2.add(bblue);

        this.add(jp2 , BorderLayout.NORTH);
//------------------------actionListenerClass.java
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class actionListenerClass implements ActionListener
{
    private Color mClr;
    private JComponent mControl;

    public actionListenerClass(Color clr , JComponent control )
    {
        mClr = clr;
        control = mControl;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        mControl.setBackground(mClr);
    }


}


但是在运行程序并单击按钮后,我将从mControl中获取空引用。

我该怎么办?

问候

最佳答案

control = mControl;


在您的ActionListener构造函数中是错误的。你自找的:

mControl = control;

07-24 15:48