пытается добавить ссылку Jpanel в класс ActionListener, но ссылка всегда нулевая - PullRequest
0 голосов
/ 11 декабря 2011

Я пытаюсь добавить 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.

что мне делать?

привет

1 Ответ

4 голосов
/ 11 декабря 2011
control = mControl;

неправильно в вашем конструкторе ActionListener.Вы хотели:

mControl = control;
...