Java Swing(六):使用图标

将图片用于控件

import java.net.URL;
代码示例:


//1.创建一个Box作为顶层容器
Box root = Box.createHorizontalBox();
this.setContentPane(root);
//2.在当前src文件夹中创建一个包images,将图片放入其中
//3.使用URL获取图片的存放位置
URL url = getClass().getResource("/images/tmp01.jpg");
//4.创建ImageIconIcon 
icon = new ImageIcon(url);
//5.给控件设置图标JLabel 
iconLabel = new JLabel();
iconLabel.setIcon(icon);
//6.添加控件
root.add(iconLabel);

这里的图片称为资源文件。
一个下载图标的网站:www.iconfont.cn
以JButton为例将上述代码封装到一个函数中:


public JButton createButton(String path){        
	URL url = getClass().getResource(path);        
	Icon icon = new ImageIcon(url);        
	JButton button = new JButton();        
	button.setIcon(icon);        
	//其他设置        
	button.setContentAreaFilled(false);        
	button.setFocusPainted(false);
	return button;    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值