本人初学习Javaswing没多久,刚开始找不到怎么把图片放在按钮上,上网查找资料都是涵盖了在项目中的,自己摸索后才知道原来没有那么难。下面是我写的例子:
package com.iconButtonDemo;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
/**
* 自定义图片按钮
* @author lenovo
*
*/
public class IconOnButton {
//声明窗体
private JFrame frame = null;
//获取按钮方法
public void getButtonss(){
//创建窗体并设置标题
frame = new JFrame("图片在按钮上");
//创建图片容器并赋予图片路径
ImageIcon icon = new ImageIcon("C:/Users/lenovo/Desktop/pt/stop.jpg");
//创建按钮
JButton button = new JButton(icon);
//设置图片大小
button.setSize(37,36);
//使窗体居中
frame.setLocationRelativeTo(null);
//窗体大小自定义
frame.setSize(100,100);
//点击窗体关闭时同时关闭后台服务
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//使窗体可视化
frame.setVisible(true);
//把按钮放进窗体中
frame.add(button);
}
public static void main(String[] args){
IconOnButton iob = new IconOnButton();
iob.getButtonss();
}
}