Loading

Membuat Menu di Java

Contoh program berikut ini mendemonstrasikan bagaimana membuat menu di java. Menu dibuat dengan dua class utama yaitu JMenu dan JMenuItem.


Source code :
import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;
 public class MenuTest extends JFrame {
 private JMenuBar bar;
 private JMenu mnuFile, mnuHelp, submnuNew;
 private JMenuItem itemNew, itemOpen, itemExit, itemAbout, itemHelp,
     subitemFile, subitemProject;
 public MenuTest() {
     super ("Membuat menu");
     bar = new JMenuBar();
     setJMenuBar (bar);
     mnuFile = new JMenu ("File");
     mnuFile.setMnemonic('F');
     mnuHelp = new JMenu ("Help");
     mnuHelp.setMnemonic('H');
     submnuNew = new JMenu ("New");
     submnuNew.setMnemonic('N');
     mnuFile.add(submnuNew);
     subitemFile = new JMenuItem ("File...");
     subitemFile.setIcon(new ImageIcon("images/new.gif"));
     subitemFile.setAccelerator(KeyStroke.getKeyStroke(
         KeyEvent.VK_N, ActionEvent.CTRL_MASK));
     subitemFile.addActionListener(
         new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                 JOptionPane.showMessageDialog(null, "New File");
             }
         }
     );

     submnuNew.add(subitemFile);
     subitemProject = new JMenuItem ("Project...");
     subitemProject.setMnemonic ('P');
     submnuNew.add(subitemProject);
     itemOpen = new JMenuItem ("Open");
     itemOpen.setMnemonic('O');
     mnuFile.add(itemOpen);
     mnuFile.addSeparator();
     itemExit = new JMenuItem ("Exit");
     itemExit.setMnemonic('E');
     itemExit.addActionListener(
         new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                 if (JOptionPane.showConfirmDialog(null,"Apakah Anda yakin akan keluar?",
                     "Konfirmasi",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE)
                     == JOptionPane.OK_OPTION) {
                     System.exit(0);
                 }
             }
         }
     );

     mnuFile.add(itemExit);
     itemHelp = new JMenuItem ("Help");
     itemHelp.setIcon(new ImageIcon("images/help.gif"));
     itemHelp.setMnemonic('e');
     mnuHelp.add(itemHelp);
     itemAbout = new JMenuItem ("About");
     itemAbout.setMnemonic('A');
     itemAbout.setIcon(new ImageIcon("images/info.gif"));
     mnuHelp.add(itemAbout);
     bar.add(mnuFile);
     bar.add(mnuHelp);
     setSize (400,200);
     setLocationRelativeTo(null);
     setVisible (true);
 }

 public static void main (String args[]) {
     JFrame.setDefaultLookAndFeelDecorated(true);
     MenuTest test = new MenuTest();
     test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}

Berikut ini contoh tampilannya:



Artikel Terkait:

0 komentar:

Post a Comment

 
Subscribe to Novel I-One

Enter your email address: