效果图:
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();
}
});
}
}