Java改变图标大小

代码不是很完美,但能运行得起来。直接上代码!

import java.awt.Container;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class ResizeIcon extends JFrame{
    public ResizeIcon() {
    	URL url=MyImageIcon.class.getResource("9.png"); //获取图片的相对路径(需将图片放置与本类同文件夹中)
		Icon icon=new ImageIcon(url);
		Image img = ((ImageIcon)icon).getImage(); // 构造Image对象
		int wideth = img.getWidth(null); // 获取源图宽
		int height = img.getHeight(null); // 获取源图长
		
		//通过改变下面两句中的数字“1”可以改变图片的比例。(注意:宽与宽的数字要一致,高的也一样)
		BufferedImage tag = new BufferedImage((int)(1 * wideth), (int)(1 * height),BufferedImage.TYPE_INT_RGB);
		tag.getGraphics().drawImage(img, 0, 0, (int)(1 * wideth), (int)(1 * height), null); 
		Icon newIcon = new ImageIcon(tag);
		
		//下面是窗体与标签的设置
		Container container=getContentPane();
		JLabel jl=new JLabel("这是一个JFrame窗体",JLabel.CENTER);
		jl.setIcon(newIcon);
		jl.setHorizontalAlignment(SwingConstants.CENTER);		
		jl.setOpaque(true);
		container.add(jl);
		setSize(500,300);
		setVisible(true);
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
    public static void main(String[] args) {
    	new ResizeIcon();
	}
}

猜你喜欢

转载自blog.csdn.net/XiaoLanZi7k7k/article/details/114131713