Adding an ActionListener
Hello.
I am having some problems implementing ActionListeners into my code. I am using the following:
JRadioButton carn =new JRadioButton ("Carnivore");
carn.setSelected (true);
carn.addActionListener (this);
This generates the following error when I try to compile:
"A "this" expression may only be used in the body of an instance method, constructor (after the explicit constructor invocation, if any), initializer block, or in the initializer expression of an instance variable."
My entire code is below:
import javax.swing.*;
import java.awt.*;
publicclass Main
{
publicstaticvoid main (String[] args)
{
JFrame frame =new JFrame ("Create a Creature");
JPanel mid =new JPanel ();
mid.setLayout (new BorderLayout ());
JPanel stanceP =new JPanel ();
stanceP.setLayout (new BorderLayout ());
JPanel ecoP =new JPanel ();
ecoP.setLayout (new BorderLayout ());
JPanel colourP =new JPanel ();
colourP.setLayout (new BorderLayout ());
JPanel main =new JPanel ();
main.setLayout (new FlowLayout ());
JPanel diet =new JPanel ();
diet.setLayout (new BorderLayout ());
JLabel dietL =new JLabel ("Diet:");
diet.add (dietL, BorderLayout.NORTH);
JRadioButton carn =new JRadioButton ("Carnivore");
carn.setSelected (true);
carn.addActionListener (this);
diet.add (carn, BorderLayout.CENTER);
JRadioButton herb =new JRadioButton ("Herbivore");
// herb.addActionListener (this);
diet.add (herb, BorderLayout.SOUTH);
main.add (diet, BorderLayout.WEST);
ButtonGroup dietGroup =new ButtonGroup ();
dietGroup.add (carn);
dietGroup.add (herb);
ImageIcon icon =new ImageIcon ("creatures/gif/qblueha.gif");
JLabel pic =new JLabel (icon);
mid.add (pic, BorderLayout.CENTER);
main.add (mid, BorderLayout.CENTER);
JLabel stanceL =new JLabel ("Stance:");
JLabel ecoL =new JLabel ("Ecosystem:");
JLabel colourL =new JLabel ("Colour:");
String stanceS[] ={"Omnipedal","Bipedal","Tripedal","Quadrapedal"};
JComboBox stance =new JComboBox (stanceS);
stanceP.add (stanceL, BorderLayout.NORTH);
stanceP.add (stance, BorderLayout.CENTER);
main.add (stanceP);
String ecoS[] ={"Tropical","Arctic","Boreal"};
JComboBox eco =new JComboBox (ecoS);
ecoP.add (ecoL, BorderLayout.NORTH);
ecoP.add (eco, BorderLayout.CENTER);
main.add (ecoP);
String colourS[] ={"Red","Blue","Green","Black"};
JComboBox colour =new JComboBox (colourS);
colourP.add (colourL, BorderLayout.NORTH);
colourP.add (colour, BorderLayout.CENTER);
main.add (colourP);
frame.getContentPane ().add (main);
frame.setSize (300, 200);
frame.setVisible (true);
}
}
I release that I do not have an ActionListener method, nor do I use the "implement ActionListener" on my method, but implementing neither of these things solves this problem.
Thanks for your time,
Drew

