Creating a Menu for a JFrame

This example creates a JFrame, and puts a raised menubar on it, and menu items on the menubar. It also applies acclerators and mnemonics to the menu items and assigns listeners.

MyFrame.java:

import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.border.*;
import javax.swing.KeyStroke;
import javax.swing.JOptionPane;
import java.awt.Component;
 
public class MyFrame extends JFrame {
 
   public static void main(String args[]) {
 
      MyFrame main = new MyFrame();
 
      // center frame on screen
      Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
      main.setBounds(d.width/2-100, d.height/2-75, 200, 150);
 
      main.pack();
      main.setSize(200, 150); //set frame size
           
      main.setVisible(true);     
   } 
 
   public MyFrame() {
      super("Menu Example");
 
      this.addWindowListener(new WindowEventHandler()); 
         
      Container container = this.getContentPane();
 
      JMenu filemenu = new JMenu("Document");
      filemenu.setMnemonic(KeyEvent.VK_D);
 
      JMenuBar bar = new JMenuBar();
      bar.setBorder(new BevelBorder(BevelBorder.RAISED));
      container.add(bar);
      setJMenuBar(bar);
 
      JMenuItem connect = new JMenuItem("Open");
      connect.addActionListener(new openListener());
      connect.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, 
                                         Event.CTRL_MASK, false));
      connect.setMnemonic('O');
 
      JMenuItem exit = new JMenuItem("Exit");
      exit.addActionListener(new exitListener());
      exit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, 
                                         Event.CTRL_MASK, false));
      exit.setMnemonic('X');
 
      filemenu.add(connect);
      filemenu.add(exit);
      bar.add(filemenu);
   }
 
   class WindowEventHandler extends WindowAdapter {
      public void windowClosing(WindowEvent evt) {          
         System.exit(0);
      }
   }
 
   class exitListener implements ActionListener {
      public void actionPerformed(ActionEvent l){
         System.exit(0);
      } 
   } 
 
   class openListener implements ActionListener {
      JFrame f = new JFrame();
 
      public void actionPerformed(ActionEvent l){
         JOptionPane.showMessageDialog(f, "OPEN");
      }
   }
}