label
new JLabel("xxx");
图标 icon
package com.sean.icon;
import javax.swing.*;
import java.awt.*;
/**
* 图标,需要实现类,Frame继承
* @create 2021-03-03 10:51
*/
public class Demo extends JFrame implements Icon {
private int width;
private int height;
public Demo(){}//无参构造
public Demo(int width, int height) {
this.width = width;
this.height = height;
}
public void init(){
Demo demo = new Demo(15,15);
//图标放在标签,也可以放在按钮上!
JLabel label = new JLabel("icontest", demo, SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Demo().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;
}
}
图片icon
package com.sean.icon;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
/**
*
* @create 2021-03-03 13:16
*/
public class ImageIconDemo extends JFrame {
public ImageIconDemo(){
//获取图片的地址
JLabel label = new JLabel("imageicon");
URL url = ImageIconDemo.class.getResource("tx.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);
setBounds(100,100,200,200);
}
public static void main(String[] args) {
new ImageIconDemo();
}
}