查看API 可通过 JLabel构造函数,也可使用setIcon(Icon icon) 函数,下面给出一个列子!
看楼主提问,主要想知道路径怎么得来!
可使用
this.getClass().getResource("/")获取的是class文件编译后放置的绝对路径。
this.getClass().getResource("/images/a.png");编译地址/images/a.png (详见代码20-21)
这里图片是放到src -- images -- a.png
有问题再追问,good luck!
import java.awt.BorderLayout;import java.awt.Container;import javax.swing.Icon;import javax.swing.ImageIcon;import javax.swing.JFrame;import javax.swing.JLabel;public class MyImages extends JFrame { /** * @Fields serialVersionUID : Description */ private static final long serialVersionUID = 1060195358054863848L; /** * 创建一个新的实例 MyImages. */ public MyImages() { // TODO Auto-generated constructor stub Container c = this.getContentPane(); c.setLayout(new BorderLayout()); Icon icon = new ImageIcon(this.getClass().getResource("/images/a.png")); JLabel label = new JLabel("aaa", icon, JLabel.LEFT); c.add(label, BorderLayout.CENTER); this.setSize(500, 500); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { new MyImages(); }}
取消
评论