使用HTML调整JLabel ImageIcon的大小

时间:2013-08-21 07:22:07

标签: java html swing jlabel imageicon

所以我浏览了this thread并看到了使用HTML进行大小调整的建议。

我一直在浏览Oracle网站,但它只提供了使用HTML在JLabels中进行文本自定义的示例。我可以获得带有HTML参数的JLabel的示例吗?

1 个答案:

答案 0 :(得分:4)

这基本上要求您对相关图片进行URL引用。如果图像是嵌入式资源(如下所示),这很容易实现,但您应该能够使用URL

从文件生成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);
            }
        });
    }

}

应该注意的是,缩放是相当减少的。我个人会避免它并简单地设计一些具有更好扩展能力的ImagePanefor example