使用HTML调整JLabel ImageIcon的大小 [英] Resizing JLabel ImageIcon with HTML

查看:96
本文介绍了使用HTML调整JLabel ImageIcon的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我浏览了


So I looked through this thread and saw the suggestion of using HTML for resizing.

I've been going through the Oracle website but it only provided example for text customization in JLabels using HTML. Can I get an example of a JLabel with HTML parameters?

解决方案

This basically requires you to have a URL reference to the image in question. This is quite easy to achieve if the image is an embedded resource (as demonstrated below), but you should be able to generate a URL from file using File#getURI#toURL

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.net.URL;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class HTMLLabel {

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

    public HTMLLabel() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                URL url = getClass().getResource("/Chicken.png");
                System.out.println(url);

                JLabel perLabel = new JLabel("<html><img width=125 height=125 src=" + url + "></html>");
                JLabel orgLabel = new JLabel("<html><img src=" + url + "></html>");

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());

                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;

                frame.add(orgLabel, gbc);
                frame.add(perLabel, gbc);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

It should be noted that scaling is pretty redumentry. I would, personally, avoid it and simple devise some kind of ImagePane that had better scaling capabilities, for example

这篇关于使用HTML调整JLabel ImageIcon的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆