C/C++教程

Icon、ImageIcon标签

本文主要是介绍Icon、ImageIcon标签,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

标签

label

new JLabel("xxx");
package com.wang.gui.lesson04;

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

//图标,需要实现类,Frame继承
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 = getContentPane();
        container.add(label);

        this.setVisible(true);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

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

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

图形ICON

package com.wang.gui.lesson04;

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("tx.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);
        setBounds(100, 100, 100, 100);
    }

    public static void main(String[] args) {
        new ImageIconDemo();
    }
}
这篇关于Icon、ImageIcon标签的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!