Java6学习笔记25——利用Swing创建带有分隔栏的菜单

import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MenuSeparator extends JFrame implements ActionListener {
public static void main(String arg[]) {
MenuSeparator ms = new MenuSeparator();
}
public MenuSeparator() {
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 typeMenu = new JMenu("Type");
fileMenu.getPopupMenu().setLightWeightPopupEnabled(false);
menuBar.add(typeMenu);

JMenuItem largeMenuItem = new JMenuItem("Large");
typeMenu.add(largeMenuItem);

JMenuItem smallMenuItem = new JMenuItem("Small");
typeMenu.add(smallMenuItem);

typeMenu.add(new JSeparator());//添加分隔栏

JMenuItem blueMenuItem = new JMenuItem("Blue");
typeMenu.add(blueMenuItem);

JMenuItem redMenuItem = new JMenuItem("Red");
typeMenu.add(redMenuItem);

return(menuBar);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
}
}
}

你可能感兴趣的:(swing)