import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MenuSubMenu extends JFrame implements ActionListener {
public static void main(String arg[]) {
MenuSubMenu ms = new MenuSubMenu();
}
public MenuSubMenu() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = buildMenuBar();
setJMenuBar(menuBar);
setLocation(250,150);
setSize(300,200);
setVisible(true);
}
JMenuBar buildMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.getPopupMenu().setLightWeightPopupEnabled(false);
menuBar.add(fileMenu);
JMenuItem exitMenuItem = new JMenuItem("Exit");
exitMenuItem.addActionListener(this);
fileMenu.add(exitMenuItem);
JMenu decideMenu = new JMenu("Style");
fileMenu.getPopupMenu().setLightWeightPopupEnabled(false);
menuBar.add(decideMenu);
JMenuItem tallMenuItem = new JMenuItem("Tall");
tallMenuItem.addActionListener(this);
decideMenu.add(tallMenuItem);
JMenuItem wideMenuItem = new JMenuItem("Wide");
wideMenuItem.addActionListener(this);
decideMenu.add(wideMenuItem);
JMenu subMenu = new JMenu("Color");
subMenu.getPopupMenu().setLightWeightPopupEnabled(false);
decideMenu.add(subMenu);
JMenuItem blackMenuItem = new JMenuItem("Black");
blackMenuItem.addActionListener(this);
subMenu.add(blackMenuItem);
JMenuItem whiteMenuItem = new JMenuItem("White");
whiteMenuItem.addActionListener(this);
subMenu.add(whiteMenuItem);
JMenuItem puceMenuItem = new JMenuItem("Puce");
puceMenuItem.addActionListener(this);
subMenu.add(puceMenuItem);
return(menuBar);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
} else if(selection.equals("Black")) {
System.out.println("The color is Black");
} else if(selection.equals("White")) {
System.out.println("The color is White");
} else if(selection.equals("Puce")) {
System.out.println("The color is Puce");
}
}
}
Java6学习笔记26——利用Swing创建子菜单
最新推荐文章于 2023-07-17 08:50:44 发布