有关于图标Icon和ImageIcon的使用

首先是关于Icon的使用,这是给label标签以及button按钮等添加默认图标的做法

public class lesson07 extends JFrame implements Icon {//因为继承了接口,所以要实现父类的所有方法,不然会报错

    private int width, height;
    public lesson07(){}//无参构造
    public lesson07(int width,int height){//有参构造
        this.width=width;
        this.height=height;
    }

    void init(){
        lesson07 icon = new lesson07(15,15);//先初始化一个Icon图标
        JLabel label = new JLabel("Icon",SwingConstants.CENTER);
        label.setIcon(icon);//这行和上一行还能写成一行————>   (JLabel label = new JLabel("Icon",icon,SwingConstants.CENTER);)
        this.setVisible(true);
        this.setBounds(100,100,600,400);
        Container container = this.getContentPane();
        container.add(label);
        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;
    }

    public static void main(String[] args) {
        new lesson07().init();
    }
}

然后是关于ImageIcon的使用,他可以将我们自定义上传的图片作为图标使用,大大增加了我们界面的美观程度

public class ImageIconDemo extends JFrame{
    public ImageIconDemo(){
        this.setVisible(true);
        this.setBounds(50,50,600,400);
        URL url = ImageIconDemo.class.getResource("girl.jpg");//ImageIconDemo是我们的类名,后面加上.class.getResourse("")可以选到该类名下的所有资源,如本
行代码就实现了图片的选取,得到的是图片的地址
        JLabel label = new JLabel("hello");
        ImageIcon imageIcon = new ImageIcon(url);//创建ImageIcon ,并将我们获取到的URL加入进来
        label.setIcon(imageIcon);
        Container container = this.getContentPane();
        container.add(label);
    }

    public static void main(String[] args) {
        new ImageIconDemo();
    }
}
posted on 2022-04-06 16:09  damango  阅读(207)  评论(0编辑  收藏  举报