栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Icon,Imagelcon(图标)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Icon,Imagelcon(图标)

1.文字图标

package com.jia.lesson;

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

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 void init() {
        IconDemo iconDemo = new IconDemo(15,15);
        //图标放在标签,也可以放在按钮上
        JLabel label = new JLabel("icontest", iconDemo, SwingConstants.CENTER);
        Container container =this.getContentPane();
        container.add(label);

        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;
    }

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

2.图片图标

注意问题:

图片添加后显示空指针,此时重启idea就好了

package com.jia.lesson;

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

public class ImageIconDemo extends Jframe{


    //构造器
    public ImageIconDemo() {
        //获取图片的地址,图片和代码在同级目录
        JLabel label = new JLabel("ImageIcon");
        URL url=ImageIconDemo.class.getResource("dsBuffer.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);
    }

    //主程序
    public static void main(String[] args) {
        new ImageIconDemo();
    }

}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/292809.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号