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);
}
}
}
因为您正试图访问本地变量'JRadioButton greenButton' – vels4j
看起来buildBottomPanel()初始化方法局部变量,而侦听器将动作源与对象字段进行比较。你应该检查你的实际代码,如果它看起来完全像这个例子,你应该改变buildBottomPanel()方法来初始化对象字段(通过从greenButton,blueButton和cyanButton变量中删除JRadioButton类型声明)。 –
你说得对。我在buildBottomPanel()方法中初始化了按钮变量。你的意思是我应该在buildBottomPanel()方法之外声明按钮变量吗?当我在自己的计算机上时,我会尝试在外部类中声明该变量。非常感谢! – Daguva