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; }