2011-12-11 24 views
0

我想一個JPanel添加到其實施的ActionListener就像下面的類:努力的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的空引用。

我該怎麼辦?

問候

回答

4
control = mControl; 

是錯在你的ActionListener構造。你想要:

mControl = control; 
+0

哦,我的上帝,我的愚蠢的錯誤..... –

相關問題