GUI编程核心技术Swing——lable标签

GUI编程核心技术Swing——lable标签

图标标签

package com.wei.lesson09;

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

//Icon 图标是一个接口,要一个实现类
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);//返回一个图标iconDemo
        //图标放在标签上                    标签名字   标签要加的图标    让图标位于标签的中间
        JLabel label = new JLabel("这是一个标签", iconDemo, SwingConstants.CENTER);
        Container container = getContentPane();
        container.add(label);
        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setBounds(100,100,500,500);
        }
    public static void main(String[] args) {
    
    
        new IconDemo().init();
    }
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
    
    
        g.fillRect(x,y,width,height);
    }
    @Override
    public int getIconWidth() {
    
    
        return this. width;
    }
    @Override
    public int getIconHeight() {
    
    
        return this.height;
    }
}

在这里插入图片描述

图片标签

package com.wei.lesson09;

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

 class ImageIconDemo extends JFrame {
    
    
    public ImageIconDemo(){
    
    
        setBounds(100,100,800,800);
        JLabel label = new JLabel("万茜");
        //获取图片的地址  url具体的地址
        URL url = ImageIconDemo.class.getResource("头像.jpg");//通过这个类获得类目录下的资源
        //ImageIcon是Icon的一个实现类
        ImageIcon imageIcon = new ImageIcon(url);//新建一个图片标签,里面有图片的地址,然后在返回一个imageIcon用于存放照片
        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();

    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wpc2018/article/details/108169095