简体   繁体   English

尝试将Jpanel引用添加到ActionListener的类,但引用始终为null

[英]trying to add Jpanel reference to an ActionListener's class but the reference is always null

I'm trying to add a JPanel to a class which is implemented the actionListener just like following : 我试图将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);
    }


}

but after running the program and clicking the buttons I'll get null reference out of mControl. 但是在运行程序并单击按钮后,我将从mControl中获取空引用。

what should I do? 我该怎么办?

regards 问候

control = mControl;

is wrong in your ActionListener constructor. 在您的ActionListener构造函数中是错误的。 You wanted: 你自找的:

mControl = control;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM