Java6学习笔记24——利用Swing创建带有RadioButton的菜单

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

public class MenuRadiobox extends JFrame implements ActionListener {
private JRadioButtonMenuItem upMenuItem;//RadioButton的菜单项
private JRadioButtonMenuItem downMenuItem;
private JRadioButtonMenuItem leftMenuItem;
private JRadioButtonMenuItem rightMenuItem;
public static void main(String arg[]) {
MenuRadiobox ms = new MenuRadiobox();
}
public MenuRadiobox() {
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 chooseMenu = new JMenu("Choose");
fileMenu.getPopupMenu().setLightWeightPopupEnabled(false);
menuBar.add(chooseMenu);

ButtonGroup bg = new ButtonGroup();//设置单选组

upMenuItem = new JRadioButtonMenuItem("Up");
upMenuItem.addActionListener(this);
chooseMenu.add(upMenuItem);
bg.add(upMenuItem);

downMenuItem = new JRadioButtonMenuItem("Down");
downMenuItem.addActionListener(this);
chooseMenu.add(downMenuItem);
bg.add(downMenuItem);

leftMenuItem = new JRadioButtonMenuItem("Left");
leftMenuItem.addActionListener(this);
chooseMenu.add(leftMenuItem);
bg.add(leftMenuItem);

rightMenuItem = new JRadioButtonMenuItem("Right");
rightMenuItem.addActionListener(this);
chooseMenu.add(rightMenuItem);
bg.add(rightMenuItem);

return(menuBar);
}
public void actionPerformed(ActionEvent e) {
String selection = e.getActionCommand();
if(selection.equals("Exit")) {
System.exit(0);
} else if(selection.equals("Up")) {
System.out.println("The choice is Up.");
} else if(selection.equals("Down")) {
System.out.println("The choice is Down.");
} else if(selection.equals("Left")) {
System.out.println("The choice is Left.");
} else if(selection.equals("Right")) {
System.out.println("The choice is Right.");
}
}
}

你可能感兴趣的:(swing,UP)