Examples The following program demonstrates how to create a menu in java. Menus created with two main classes JMenu and JMenuItem.
Here is an example looks:
Berikut ini contoh program lengkapnya:
003 | import java.awt.event.*; |
007 | public class MenuTest extends JFrame { |
009 | private JMenuBar bar; |
011 | private JMenu mnuFile, mnuHelp, submnuNew; |
013 | private JMenuItem itemNew, itemOpen, itemExit, itemAbout, itemHelp, |
015 | subitemFile, subitemProject; |
019 | super ( "Membuat menu" ); |
021 | bar = new JMenuBar(); |
025 | mnuFile = new JMenu ( "File" ); |
027 | mnuFile.setMnemonic( 'F' ); |
029 | mnuHelp = new JMenu ( "Help" ); |
031 | mnuHelp.setMnemonic( 'H' ); |
033 | submnuNew = new JMenu ( "New" ); |
035 | submnuNew.setMnemonic( 'N' ); |
037 | mnuFile.add(submnuNew); |
039 | subitemFile = new JMenuItem ( "File..." ); |
041 | subitemFile.setIcon( new ImageIcon( "images/new.gif" )); |
043 | subitemFile.setAccelerator(KeyStroke.getKeyStroke( |
045 | KeyEvent.VK_N, ActionEvent.CTRL_MASK)); |
047 | subitemFile.addActionListener( |
049 | new ActionListener() { |
051 | public void actionPerformed(ActionEvent e) { |
053 | JOptionPane.showMessageDialog( null , "New File" ); |
061 | submnuNew.add(subitemFile); |
063 | subitemProject = new JMenuItem ( "Project..." ); |
065 | subitemProject.setMnemonic ( 'P' ); |
067 | submnuNew.add(subitemProject); |
069 | itemOpen = new JMenuItem ( "Open" ); |
071 | itemOpen.setMnemonic( 'O' ); |
073 | mnuFile.add(itemOpen); |
075 | mnuFile.addSeparator(); |
077 | itemExit = new JMenuItem ( "Exit" ); |
079 | itemExit.setMnemonic( 'E' ); |
081 | itemExit.addActionListener( |
083 | new ActionListener() { |
085 | public void actionPerformed(ActionEvent e) { |
087 | if (JOptionPane.showConfirmDialog( null , "Apakah Anda yakin akan keluar?" , |
089 | "Konfirmasi" ,JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE) |
091 | == JOptionPane.OK_OPTION) { |
103 | mnuFile.add(itemExit); |
105 | itemHelp = new JMenuItem ( "Help" ); |
107 | itemHelp.setIcon( new ImageIcon( "images/help.gif" )); |
109 | itemHelp.setMnemonic( 'e' ); |
111 | mnuHelp.add(itemHelp); |
113 | itemAbout = new JMenuItem ( "About" ); |
115 | itemAbout.setMnemonic( 'A' ); |
117 | itemAbout.setIcon( new ImageIcon( "images/info.gif" )); |
119 | mnuHelp.add(itemAbout); |
127 | setLocationRelativeTo( null ); |
133 | public static void main (String args[]) { |
135 | JFrame.setDefaultLookAndFeelDecorated( true ); |
137 | MenuTest test = new MenuTest(); |
139 | test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); |
0 komentar: