-
Need JMenu help
Hi, I wonder if anyone can help me with my error?
here is my code:
Code:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class menuTutorial extends JFrame {
JMenuBar menuBar = new JMenuBar();
public menuTutorial() {
setLayout(new FlowLayout());
JMenu file = new JMenu("File");
menuBar.add(file);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenuItem undo = new JMenuItem("Undo");
undo.add(undo);
event e = new event();
exit.addActionListener(e);
}
public class event implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main (String args[]) {
menuTutorial gui = new menuTutorial();
gui.setJMenuBar(menuBar);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(400,400);
gui.setVisible(true);
}
}
this bit gives me an error: gui.setJMenuBar(menuBar);
it says: non-static variable menuBar cannot be referenced from a static context.
-
The menuBar variable is an instance variable and if you desire to access it in a static method, it must be associated with a menuTutorial object. But easier still is to just add the menuBar to the JFrame (the menuTutorial object or this) in the class's constructor:
Code:
public menuTutorial() {
setLayout(new FlowLayout());
JMenu file = new JMenu("File");
menuBar.add(file);
JMenuItem exit = new JMenuItem("Exit");
file.add(exit);
JMenu edit = new JMenu("Edit");
menuBar.add(edit);
JMenuItem undo = new JMenuItem("Undo");
undo.add(undo);
event e = new event();
exit.addActionListener(e);
setJMenuBar(menuBar);
}
This way you don't need to access it from the main method.
-
-