Hi all,
I have a question I'd like to ask regarding JFrames and JMenuBars. My question is I have a main JFrame window which extends JFrame, and in this JFrame I have created a JMenuBar. I have created other JFrames which open up after JButtons have been clicked on and found that in each JFrame file, in order to show the same JMenuBar that is in the first JFrame window, I have to create the same methods that I created in the first JFrame in order to display the JMenuBar. To me this feels like unnecessary coding of the same thing when I could just have one that is common to all my JFrames but how do i do this?
I have tried several things in order to save myself having to code the same methods in each JFrame, but have not come up with a successful solution, I can create the JMenuBar in the first JFrame, but it will not show in the next JFrame.
public class FirstWindow extends JFrame implements ActionListener { protected JMenuBar myMenuBar = new JMenuBar(); protected JMenu myMenuFile = new JMenu("File"); protected JMenuItem myMenuItemExit = new JMenuItem("Exit"); private JButton btn; protected JPanel pnl; public FirstWindow() { setTitle("First Window"); setSize(700, 430); setJMenuBar(myMenuBar); this.getContentPane().setBackground( Color.yellow); createMenu(); setVisible(true); setResizable(false); pnl = new JPanel(); btn = new JButton("Switch to Next Window"); btn.addActionListener(this); pnl.add(btn, BorderLayout.CENTER); add( pnl, BorderLayout.CENTER ); } protected void buildMenu() { myMenuFile.add(myMenuItemExit); myMenuItemExit.addActionListener( this ); myMenuBar.add(myMenuFile); } public void actionPerformed( ActionEvent e ) { if ( e.getSource() == btn ) { string msg = "Add An exit here"; JOptionPane.showMessageDialog( this, msg, "Exit Message", JOptionPane.OK_OPTION ); }
public class TestExtend extends JFrame { public TestExtend() { setTitle("Test Frame 1"); setSize(700, 430); } public TestExtend(Mgw w) { w.buildMenu(); } }
public class MainP { public static void main(String[] args) { FirstWindow firstwin = new FirstWindow(); firstwin.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } }
From my code above, the new window will show, but without the JMenuBar which I created in the first one.
Just to clarify, I would like to know if there is a way to save myself coding the same JMenuBar in each frame I create by sharing the one from the first frame?
Thanks if you can help