Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes


Java Programming Code Examples

Java > Swing Code Examples

MenuDemo.java

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
MenuDemo.java // Title : MenuDemo.java - Simple demo of building menus. import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; /// MenuDemo public class MenuDemo { main public static void main(String[] args) { JFrame win = new MenuDemoGUI(); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); win.setVisible(true); } } ///// MenuDemoGUI class MenuDemoGUI extends JFrame { JTextArea m_editArea = new JTextArea(20, 50);; JMenu m_fileMenu = new JMenu("File");// declare and create new menu JMenuItem m_openItem = new JMenuItem("Open"); // create new menu item JMenuItem m_quitItem = new JMenuItem("Quit"); // another menu item JMenu m_editMenu = new JMenu("Edit"); JMenuItem m_copyItem = new JMenuItem("Copy"); JMenuItem m_pasteItem= new JMenuItem("Paste"); constructor public MenuDemoGUI() { //... Add listeners to menu items m_openItem.addActionListener(new OpenAction()); m_quitItem.addActionListener(new QuitAction()); // Copy and Paste don't have listeners yet, so disable them for now. m_copyItem.setEnabled(false); m_pasteItem.setEnabled(false); //... Menubar, menus, menu items. Use indentation to show structure. JMenuBar menubar = new JMenuBar(); // declare and create new menu bar menubar.add(m_fileMenu); // add the menu to the menubar m_fileMenu.add(m_openItem); // add the menu item to the menu m_fileMenu.addSeparator(); // add separator line to menu m_fileMenu.add(m_quitItem); menubar.add(m_editMenu); m_editMenu.add(m_copyItem); m_editMenu.add(m_pasteItem); //... Content pane: create, layout, add components JPanel content = new JPanel(); content.setLayout(new BorderLayout()); content.add(m_editArea, BorderLayout.CENTER); //... Set JFrame's menubar, content pane, and title. this.setContentPane(content); // Set windows content pane.. this.setJMenuBar(menubar); // Set windows menubar. this.pack(); this.setTitle("MenuDemo"); }//endconstructor //// OpenAction class OpenAction implements ActionListener { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Sorry, can't open anything"); } } /// QuitAction class QuitAction implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); // terminate this program } } }