11 菜单栏 & 工具栏

菜单栏

代码:

class MyFrame extends JFrame{
	
	public MyFrame(String title) {
		super(title);
		
		JPanel root = new JPanel();
		this.setContentPane(root);
		
		//添加菜单
		JMenuBar menuBar = new JMenuBar();
		this.setJMenuBar(menuBar);
		
		//菜单文件
		JMenu fileMenu = new JMenu("文件");
		menuBar.add(fileMenu);
		JMenuItem fileOpenCmd = new JMenuItem("打开");
		JMenuItem fileSaveCmd = new JMenuItem("保存");
		JMenuItem fileSaveAsCmd = new JMenuItem("另存为");
		fileMenu.add(fileOpenCmd);
		fileMenu.add(fileSaveCmd);
		fileMenu.add(fileSaveAsCmd);
		
		JMenuItem fileExitCmd = new JMenuItem("退出");
		fileMenu.addSeparator();
		fileMenu.add(fileExitCmd);
		
		//帮助菜单
		JMenu helpMenu = new JMenu("帮助");
		menuBar.add(helpMenu);
		JMenuItem helpAbout = new JMenuItem("关于");
		JMenuItem helpManual = new JMenuItem("打开帮助");
		helpMenu.add(helpAbout);
		helpMenu.add(helpManual);
		
		fileExitCmd.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				System.exit(0);
			}
			
		});
	}
}

显示:
在这里插入图片描述

总结就是,菜单栏里面放菜单,菜单里面放菜单项

工具栏

JToolBar:工具栏

JButton:工具按钮

setIcon()  图标
setActionCommand()  命令
setToolTipText()  提示摁字
addActionListener()  事件处理

代码:

public class Demo {
	public static void main(String[] args) {
		MyFrame frame = new MyFrame("Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(500, 500);
		frame.setLocation(500, 500);
		frame.setVisible(true);
	}
}

class MyFrame extends JFrame{
	
	public MyFrame(String title) {
		super(title);
		
		JPanel root = new JPanel();
		root.setLayout(new BorderLayout());
		this.setContentPane(root);
		root.setLayout(new BorderLayout());
		
		//创建工具栏
		JToolBar toolBar = new JToolBar();
		toolBar.setFloatable(false);
		root.add(toolBar, BorderLayout.NORTH);
		
		//向工具栏上添加按钮
		toolBar.add(toolButton("./src/icons/denglong.png", "fileOpen", "打开"));
		toolBar.add(toolButton("./src/icons/lipao.png", "fileSave", "保存"));
		toolBar.add(toolButton("./src/icons/tongqian.png", "fileSaveAs", "另存为"));
		toolBar.addSeparator();
		toolBar.add(toolButton("./src/icons/yuanbao.png", "fileHelp", "帮助"));
	}
	
	protected JButton toolButton(String imageName, String action, String toolTipText) {
		JButton button = new JButton();
		button.setIcon(new ImageIcon(imageName));
		button.setToolTipText(toolTipText);
		button.setFocusPainted(false);
		button.setActionCommand(action);
		button.addActionListener(new MyActionListener());
		return button;
	}
	
	private class MyActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			System.out.println(e.getActionCommand());
		}
		
	}
}

显示:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值