Results 1 to 4 of 4
Thread: Need JMenu help
- 05-16-2010, 03:45 AM #1
Member
- Join Date
- May 2010
- Posts
- 23
- Rep Power
- 0
Need JMenu help
Hi, I wonder if anyone can help me with my error?
here is my code:
this bit gives me an error: gui.setJMenuBar(menuBar);Java 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); } }
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:
This way you don't need to access it from the main method.Java 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); }
- 05-16-2010, 04:58 AM #3
Member
- Join Date
- May 2010
- Posts
- 23
- Rep Power
- 0
Thanks a bunch :)
-
Similar Threads
-
JMenu help
By Kyle227 in forum New To JavaReplies: 3Last Post: 05-02-2010, 12:36 AM -
unwanted bug. JMenu
By ocean in forum New To JavaReplies: 7Last Post: 11-20-2009, 09:29 PM -
JMenu with Tabs using swing
By phil128 in forum AWT / SwingReplies: 1Last Post: 03-03-2009, 03:29 PM -
JMenu to JPopupMenu
By carderne in forum New To JavaReplies: 0Last Post: 02-28-2009, 06:07 PM -
JMenu and JRadioButtonMenuItem
By doron70 in forum AWT / SwingReplies: 3Last Post: 07-18-2007, 06:13 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks