Search code examples
javahtmlswingjlabelimageicon

Resizing JLabel ImageIcon with HTML


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?


Solution

  • 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

    enter image description here

    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