Swing-工具栏

效果图:

 

MyFrame:

思路:

1、自定义一个设置按钮的方法,通过传入三个参数:imageName(按钮图标路径), action(按钮行为), toolTip(按钮提示)

然后实现按钮的三个属性,返回定义后的按钮

2、整体布局采用边界borderlayout布局

3、设置内容面板-面板中加入工具栏-工具栏中加入自定义按钮

package swing01;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JToolBar;

public class MyFrame extends JFrame {
	
	public MyFrame(String title)
	{
		super(title);
		
		//内容面板
		JPanel root=new JPanel();
		this.setContentPane(root);
		root.setLayout(new BorderLayout());
		
		//创建工具栏
		JToolBar toolBar=new JToolBar();
		toolBar.setFloatable(false); //让按钮栏固定,不允许浮动
		root.add(toolBar, BorderLayout.PAGE_START);
		
		//向工具栏中添加按钮
		toolBar.add( toolButton("ic_open.png", "fileOpen","打开"));
		toolBar.add( toolButton("ic_save.png", "fileSave","保存"));
		toolBar.add( toolButton("ic_saveas.png","fileSaveAs","另存为"));
		toolBar.addSeparator();
		toolBar.add( toolButton("ic_help.png", "fileHelp","帮助"));
		
	}
	
    //自定义按钮类
	protected JButton toolButton(String imageName,String action,String toolTip)
	{
		//图标
		String imagePath="/images/"+imageName;
		URL imageURL=getClass().getResource(imagePath);
		
		//创建按钮
		JButton button=new JButton();
		button.setActionCommand(action);  //按钮行为
		button.setToolTipText(toolTip);   //按钮提示
		button.setIcon(new ImageIcon(imageURL));  //设置按钮图标
		button.setFocusPainted(false);
		
		button.addActionListener(actionListener);
		return button;
	}
	
	//创建一个监听器
	private ActionListener actionListener=new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) 
		{
			// TODO Auto-generated method stub
			String action =e.getActionCommand();
			System.out.println("执行命令:"+action);
		}
		
	};

}

MyDemo:

package swing01;

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyDemo
{
	private static void createGUI()
	{
		// JFrame指一个窗口,构造方法的参数为窗口标题
		JFrame frame = new MyFrame("Swing Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
				// 设置窗口的其他参数,如窗口大小
		frame.setSize(400, 300);
		
		// 显示窗口
		frame.setVisible(true);
	}
	
	public static void main(String[] args)
	{
	
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run()
			{
				createGUI();
			}
		});

	}
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值