non-static variable, addActionListener()
Hi all ive been having a bita trouble adding an action listener to one of my menu items, the compiler gives me the following error . .
non-static variable this cannot be referenced from a static context
exitItem.addActionListener(this);
1 error
heres a snippet of my code that should give some detail to the program . .
Code java:
public class Project implements GLEventListener, ActionListener {
static JMenuItem exitItem;
static private Animator animator;
public static void main(String[] args) {
JFrame frame = new JFrame("Learn TCP/ IP");
GLCanvas canvas = new GLCanvas();
canvas.addGLEventListener(new Project());
frame.add(canvas);
frame.setSize(640, 480);
animator = new Animator(canvas);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
// Run this on another thread than the AWT event queue to
// make sure the call to Animator.stop() completes before
// exiting
new Thread(new Runnable() {
public void run() {
animator.stop();
System.exit(0);
}
}).start();
}
});
JMenuBar titleMenu = new JMenuBar();
JMenu fileMenu = new JMenu("File");
exitItem = new JMenuItem("Exit");
exitItem.addActionListener(this); // ERROR ON THIS LINE
fileMenu.add(exitItem);
titleMenu.add(fileMenu);
frame.setJMenuBar(titleMenu);
// Center frame
frame.setLocationRelativeTo(null);
frame.setVisible(true);
animator.start();
}
Anyone got any ideas?? thanks in advance :)
Re: non-static variable, addActionListener()
'this' doesn't refer to anything in that context. You must create an instance of your class
Code java:
exitItem.addActionListener(new Project());
See Common Java Mistakes, a few posts down.