all, I'm a newbie to Java and I'm working on the Lab 12 on the Java textbook, Starting out with Java (Ed.5).
After written the code for constructor, I have created a method to build a panel and add some radio buttons to it. I have registered these radio buttons to an Action Listener called RadioButtonListener. Then I wrote an inner class for RadioButtonListener.
Here is the problem, as I used the getSource() method to determine which button is clicked, the compiler does not recognize the button I indicated.
Here is my coding:
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);
}
}
}
try to use getActionCommand()
instead of getSource()
as Below :-
if (f.getActionCommand().equals("green"))
{
messageLabel.setForeground(Color.GREEN);
}
or you can use anonymous inner classes as below :-
greenButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e)
{
messageLabel.setForeground(Color.GREEN);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.