Icon标签
package com.deng.lesson04;
import javax.swing.*;
import java.awt.*;
//图标是一个接口需要实现
public class IconDemo extends JFrame implements Icon{
private int width;
private int height;
public IconDemo(){} //无参构造
public IconDemo(int width, int height) throws HeadlessException {
this.width = width;
this.height = height;
}
public void init(){
IconDemo iconDemo = new IconDemo(15, 15); //图标放在标签上,也可以放在按钮上。
JLabel jLabel = new JLabel("我的标签", iconDemo, SwingConstants.CENTER);
Container container = getContentPane();
container.add(jLabel);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(Color.GREEN);
g.fillRect(x,y,width,height);
}
@Override
public int getIconWidth() {
return this.width;
}
@Override
public int getIconHeight() {
return this.height;
}
public static void main(String[] args) {
new IconDemo().init();
}
}
ImageIcon标签
package com.deng.lesson04;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
JLabel jLabel = new JLabel("24号科比");
//获取图片位置
URL url = ImageIconDemo.class.getResource("tx.jpg");
//获取当前这个类下面同级名为“tx.jpg”的资源 返回的url是一个具体的地址
ImageIcon imageIcon = new ImageIcon(url);
jLabel.setIcon(imageIcon);
jLabel.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(jLabel);
setVisible(true);
setBounds(100,100,200,200);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}