Icon标签
public class IcnoDemo extends JFrame implements Icon {
private int height;
private int width;
public IcnoDemo(){}
public IcnoDemo(int height,int width){
this.height = height;
this.width = width;
}
public void init(){
IcnoDemo icnoDemo = new IcnoDemo(15,15);
//图标放在标签也可以放在按钮上
JLabel label = new JLabel("icon", icnoDemo, SwingConstants.CENTER);
Container contentPane = getContentPane();
contentPane.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new IcnoDemo().init();
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.fillOval(x,y,width,height);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
}
不懂在那里调用的paintIcon(),想不明白,看Icon的类也没看懂
ImageIcon标签
public class ImageIconDemo extends JFrame {
public static void main(String[] args) {
new ImageIconDemo();
}
public ImageIconDemo(){
JLabel label = new JLabel("hanbin");
URL url = ImageIconDemo.class.getResource("1.jpg");
ImageIcon imageIcon = new ImageIcon(url);//命名不要冲突了
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
先写标签,然后获得照片的url 然后将url放在ImageIcon对象,将imageIcon挂在label上,然后创建容器,将label放在容器上,最后设置可见,设置窗口监听关闭。