The examples in this article share with you the specific code for implementing menu functions in the java graphical user interface for your reference. The specific content is as follows
Topic: Write a graphical user interface to implement the functions of menus. There are 3 first-level menu items: File, Edit and Help. Among the File menu items, there are 3 secondary menu items: New, Open, and Save. Among the Edit menu items, there are 3 secondary menu items: Copy, Cut, and Paste. In the Help menu item, there is a secondary menu item About. For each secondary menu item, it does not have to really implement its functionality. Just demonstrate that it can respond to a mouse click event, such as a pop-up dialog box or a sentence printed.
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class MenuDemo extends JFrame implements ActionListener{ public static void main(String[] args){ MenuDemo demo = new MenuDemo(); demo.go(); } public void go(){ this.setTitle("Graphic User Interface"); this.setBounds(600, 150, 500, 150); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); //Create menu JMenuBar jmb = new JMenuBar(); //Create position, it will be automatically placed at the top of this.setJMenuBar(jmb); //Add menu JMenu menu1 = new JMenu("File"); JMenu menu2 = new JMenu("Edit"); JMenu menu3 = new JMenu("Help"); JMenuItem item1 = new JMenuItem("New"); JMenuItem item2 = new JMenuItem("Open"); JMenuItem item3 = new JMenuItem("Save"); JMenuItem item4 = new JMenuItem("Copy"); JMenuItem item5 = new JMenuItem("Cut"); JMenuItem item6 = new JMenuItem("Paste"); JMenuItem item7 = new JMenuItem("About"); //Add menu items to menu1.add(item1); menu1.add(item2); menu1.add(item3); menu2.add(item4); menu2.add(item5); menu2.add(item6); menu3.add(item7); //Add the menu to the menu bar jmb.add(menu1); jmb.add(menu2); jmb.add(menu3); item1.addActionListener(this); item2.addActionListener(this); item3.addActionListener(this); item4.addActionListener(this); item5.addActionListener(this); item5.addActionListener(this); item6.addActionListener(this); item7.addActionListener(this); } public void actionPerformed(ActionEvent e){ String str = e.getActionCommand(); if("New".equals(str)) { System.out.println("New is being clicked"); } else if("Open is being clicked"); } else if("Save".equals(str)) { System.out.println("Save is being clicked"); } else if("Copy".equals(str)){ System.out.println("Copy is being clicked"); } else if("Cut".equals(str)){ System.out.println("Cut is being clicked"); } else if("Paste".equals(str)){ System.out.println("Paste is being clicked"); } else{ System.out.println("About is being clicked"); } } } }Running effect:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.