2014-02-26 30 views
0

all,我是Java的新手,我正在开发Java教科书的Lab 12,从Java开始( Ed.5)。动作侦听器中的getSource()方法无法识别我所指的按钮

在为构造函数编写代码之后,我创建了一个方法来构建一个面板并向它添加一些单选按钮。我已经将这些单选按钮注册到名为RadioButtonListener的Action Listener。然后我为RadioButtonListener写了一个内部类。

这是问题所在,因为我使用getSource()方法确定单击哪个按钮,编译器无法识别我指示的按钮。

这里是我的编码:

private void buildBottomPanel() 
{ 
    bottomPanel = new JPanel(); 

    JRadioButton greenButton = new JRadioButton("Green"); 

    JRadioButton blueButton = new JRadioButton("Blue"); 

    JRadioButton cyanButton = new JRadioButton("Cyan"); 

    ButtonGroup bottomButtonGroup = new ButtonGroup(); 
    bottomButtonGroup.add(greenButton); 
    bottomButtonGroup.add(blueButton); 
    bottomButtonGroup.add(cyanButton); 

    greenButton.addActionListener(new RadioButtonListener()); 
    blueButton.addActionListener(new RadioButtonListener()); 
    cyanButton.addActionListener(new RadioButtonListener()); 

    bottomPanel.add(greenButton); 
    bottomPanel.add(blueButton); 
    bottomPanel.add(cyanButton); 
} 

private class RadioButtonListener implements ActionListener 
{ 
    public void actionPerformed(ActionEvent f) 
    { 
     if (f.getSource() == greenButton) 
     { 
      messageLabel.setForeground(Color.GREEN); 
     } 
     else if (f.getSource() == blueButton) 
     { 
      messageLabel.setForeground(Color.BLUE); 
     } 
     else if (f.getSource() == cyanButton) 
     { 
      messageLabel.setForeground(Color.CYAN); 
     } 
    } 
} 
+1

因为您正试图访问本地变量'JRadioButton greenButton' – vels4j

+0

看起来buildBottomPanel()初始化方法局部变量,而侦听器将动作源与对象字段进行比较。你应该检查你的实际代码,如果它看起来完全像这个例子,你应该改变buildBottomPanel()方法来初始化对象字段(通过从greenButton,blueButton和cyanButton变量中删除JRadioButton类型声明)。 –

+0

你说得对。我在buildBottomPanel()方法中初始化了按钮变量。你的意思是我应该在buildBottomPanel()方法之外声明按钮变量吗?当我在自己的计算机上时,我会尝试在外部类中声明该变量。非常感谢! – Daguva

回答

-2

尝试使用getActionCommand()代替getSource()如下: -

if (f.getActionCommand().equals("green")) 
     { 
      messageLabel.setForeground(Color.GREEN); 
     } 

,或者你可以按照以下使用匿名内部类: -

greenButton.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) 
      { 

       messageLabel.setForeground(Color.GREEN); 

      } 
     }); 
+0

非常感谢您的建议。我将getActionCommand()用于另一个动作侦听器内部类,它工作正常。然而,对于这个内部类,实验室指令要求我使用getSource()方法,并在类似于教科书中的示例中输入编码。我现在想知道内部类中的getSource()方法是否无法跟踪内部类之外的方法的局部变量。 – Daguva

+0

如果局部变量被声明为final,那么只有你可以在内部类中使用该变量。 –

相关问题