【JAVAGUI】Swing—标签

这篇博客介绍了如何在Java Swing中创建自定义图标和使用图片图标。通过实现Icon接口创建了一个填充椭圆的自定义图标,并将其应用到JLabel上。同时,展示了如何从资源文件加载图片并设置为JLabel的图标。示例代码详细地展示了这两种方法的实现过程。
摘要由CSDN通过智能技术生成

3.3 标签

label

new JLabel("xxx");

图标 ICON

package GUI.Swing;

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

public class IconFemo extends JFrame implements Icon {
    private int width;
    private int height;

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

    public void init(){
        IconFemo iconFemo = new IconFemo(15, 15);
        //图标可以放在标签上,也可以放在按钮上
        JLabel label = new JLabel("icontest", iconFemo, SwingConstants.CENTER);//设置这个标签放在正中间
        Container container = 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) {//放的位置  画笔来画 图标的大小 x,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 IconFemo().init();
    }
}

图片ICON

package GUI.Swing;

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

public class ImageIconDemo extends JFrame {
    public ImageIconDemo(){
        //获取图片的地址
        JLabel label = new JLabel("ImageIcon");
        URL url = ImageIcon.class.getResource("bei.jpg");

        ImageIcon imageIcon = new ImageIcon(url);//命名不要和Image重名
        label.setIcon(imageIcon);
        label.setHorizontalAlignment(SwingConstants.CENTER);

        Container container = getContentPane();
         container.add(label);
         setVisible(true);
         setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
         setBounds(200,200,200,200);
    }

    public static void main(String[] args) {
        new ImageIconDemo();
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值