Swing : Menu

JMenu is the standard menu that may have various JMenuItems. JMunu are placed into JMenuBar. and JMenuBar is added to the JFrame using setMenuBar method. you can add ActionListener to JMenuItem to deal with events. 

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

class MenuDemo
{
    public static void main(String ar[])
    {
        JFrame frame=new JFrame("Menus");
        
        JMenu file=new JMenu("File");
        file.setMnemonic(KeyEvent.VK_F);
        
        
        JMenu edit=new JMenu("Edit");
        JMenu view=new JMenu("View");
        JMenu help=new JMenu("Help");
        
        file.add(new JMenuItem("Open"));
        file.add(new JMenuItem("New"));
        file.addSeparator(  );
        //add separator
        file.add(new JMenuItem("Save"));
        file.add(new JMenuItem("Save As"));
        JMenuItem exit=new JMenuItem("Exit");
        exit.addActionListener(new ActionListener(  ) {
       public void actionPerformed(ActionEvent e) { System.exit(0); }
        });
        
        file.add(exit);
        
        edit.add(new JMenuItem("Copy"));
        edit.add(new JMenuItem("Peste"));
        edit.add(new JMenuItem("Cut"));
        edit.add(new JMenuItem("Find"));
        edit.add(new JMenuItem("Replace"));
        
        view.add(new JMenuItem("wer"));
        view.add(new JMenuItem("sgfsd"));
        view.add(new JMenuItem("sdfgds"));
        
        JMenuBar menubar=new JMenuBar();
        menubar.add(file);
        menubar.add(edit);
        menubar.add(view);
        menubar.add(help);
        
        frame.setJMenuBar(menubar);
        
        frame.setBounds(200,100,400,300);
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        frame.setVisible(true);

    }
}

No comments:

Popular Posts