菜单条JMenuBar
菜单JMenu
菜单项JMenuItem
menuFruit.addSeparator(); //在菜单添加分隔线
public class Example9_2 {public static void main(String args[]) {WindowMenu win=new WindowMenu("带菜单的窗口",20,30,600,290);}
}
C:/Users/86156/OneDrive/图片/水果照片java中用到/banana.jpg
路径的书写
C:\Users\86156\OneDrive\图片\水果照片java中用到\banana.jpg
这俩都可以
import javax.swing.*;
public class WindowMenu extends JFrame {JMenuBar menubar;//菜单条JMenu menuFruit;JMenuItem bananaItem,pearItem;JMenu appleMenu;JMenuItem redAppleItem,yellowAppleItem;public WindowMenu(){} public WindowMenu(String s,int x,int y,int w,int h) {init(s);setLocation(x,y);setSize(w,h);setVisible(true);setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); }void init(String s){setTitle(s); //设置窗口的标题 menubar=new JMenuBar(); menuFruit=new JMenu("水果菜单"); //menuFruit做根菜单 bananaItem=new JMenuItem("香蕉"); bananaItem.setIcon(new ImageIcon("C:/Users/86156/OneDrive/图片/水果照片java中用到/banana.jpg"));pearItem=new JMenuItem("甜梨");pearItem.setIcon(new ImageIcon("C:/Users/86156/OneDrive/图片/水果照片java中用到/pear.jpg"));appleMenu=new JMenu("苹果"); redAppleItem = new JMenuItem("红苹果");redAppleItem.setIcon(new ImageIcon("C:/Users/86156/OneDrive/图片/水果照片java中用到/redApple.jpg")); yellowAppleItem = new JMenuItem("黄苹果"); yellowAppleItem.setIcon(new ImageIcon("C:/Users/86156/OneDrive/图片/水果照片java中用到/yellowApple.png"));menuFruit.add(bananaItem); //菜单添加菜单项 menuFruit.add(pearItem); //菜单添加菜单项menuFruit.addSeparator(); //在菜单添加分隔线menuFruit.add(appleMenu); //菜单也可以添加菜单appleMenu.add(redAppleItem); //菜单添加菜单项appleMenu.add(yellowAppleItem); //菜单添加菜单项menubar.add(menuFruit); //菜单条添加menuFruit菜单setJMenuBar(menubar); //窗口放置菜单条}
}