Java Swing 图形用户界面——菜单条、菜单与菜单项

时间:2023-01-26 18:51:00

带菜单项的窗口:
Java Swing 图形用户界面——菜单条、菜单与菜单项


具体使用方法见代码及注释:
Test_Menu.java


public class Test_Menu {
public static void main(String args[]) {
Menu menu = new Menu("菜单");
menu.setBounds(10, 10, 300, 200);
}
}

Menu.java

import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public class Menu extends JFrame{
JMenuBar menubar; //菜单条
JMenu menuFile; //菜单
JMenuItem itemOpen, itemSave; //菜单项

public Menu() {}
public Menu(String string) {
init(string);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}

void init(String s) {
setTitle(s);
menubar = new JMenuBar();
menuFile = new JMenu("文件(F)");
menuFile.setMnemonic('F'); //设置菜单的键盘操作方式是Alt + F键
itemOpen = new JMenuItem("打开(O)");
itemSave = new JMenuItem("保存(S)");

//设置菜单项的键盘操作方式是Ctrl+O和Ctrl+S键
KeyStroke Ctrl_cutKey =
KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK);
itemOpen.setAccelerator(Ctrl_cutKey);
Ctrl_cutKey =
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK);
itemSave.setAccelerator(Ctrl_cutKey);

menuFile.add(itemOpen);
//menuFile.addSeparator();
menuFile.add(itemSave);
menubar.add(menuFile); //将菜单添加到菜单条上
setJMenuBar(menubar);
}
}