以图片做图标的方法
package Swing;
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageIconDemo extends JFrame{
public static void main(String[] args) {
new ImageIconDemo();
}
public ImageIconDemo() {
JLabel label = new JLabel("ImageIcon");
URL url = ImageIconDemo.class.getResource("fj.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container=getContentPane();
container.add(label);
setVisible(true);
setBounds(100,100,200,200);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
以画笔绘制的图形做图标
package Swing;
import javax.swing.*;
import java.awt.*;
public class IconDemo extends JFrame implements Icon {
private int width;
private int height;
public static void main(String[] args) {
new IconDemo().init();
}
public IconDemo() throws HeadlessException {}
public IconDemo(int width, int height) {
this.width = width;
this.height = height;
}
public void init(){
IconDemo iconDemo = new IconDemo(15, 15);
JLabel label = new JLabel("iconTest", iconDemo, SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setBounds(100,200,500,500);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
@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;
}
}