Resizing JLabel ImageIcon with HTML

十年热恋 提交于 2019-12-13 18:40:27

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/18351186/resizing-jlabel-imageicon-with-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!