Swing组件中,在标签Label上插图标及图片Icon

1、图标

import java.awt.*;
import javax.swing.*;

//图标,需要实现类,JFrame继承
public class IconDemo extends JFrame implements Icon{
	
	private int width;
	private int height;
	
	public IconDemo() {} //无参构造
	
	public IconDemo(int width, int height) {
		this.width = width;
		this.height = height;
	}

	public static void main(String[] args) {
		new IconDemo().Init();
	}
	
	public void Init() {
		IconDemo iconDemo = new IconDemo(15,15);
		//图标 放在标签,也可以放在按钮上! 
		JLabel label = new JLabel("icontest",iconDemo,SwingConstants.CENTER);
		Container container = getContentPane();
		container.add(label);
		
		this.setVisible(true);
		this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		this.setBounds(100,100,200,200);
	}
	
	@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;
	}

}

效果:
Swing组件中,在标签Label上插图标及图片Icon

2、图片

import java.awt.*;
import java.net.URL;
import javax.swing.*;

public class ImageIconDemo extends JFrame{
	
	public ImageIconDemo() {
		//获取图片地址(将图片复制到与class文件同一文件夹下)
		JLabel lable = new JLabel("ImageIcon");
		URL ur1 = ImageIconDemo.class.getResource("tx.png");
		
		ImageIcon imageIcon = new ImageIcon(ur1);
		lable.setIcon(imageIcon);
		lable.setHorizontalAlignment(SwingConstants.CENTER);
		
		Container container = getContentPane();
		container.add(lable);
		
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setBounds(100,100,200,200);
	}
	
	public static void main(String[] args) {
		new ImageIconDemo();
	}
}

效果:
Swing组件中,在标签Label上插图标及图片Icon

Swing组件中,在标签Label上插图标及图片Icon

上一篇:C# 生成一天内不重复的int 值


下一篇:Swing组件基础-----按钮(图片、单选、复选)