Java - Convert Image to Icon/ImageIcon?

六月ゝ 毕业季﹏ 提交于 2019-11-30 14:42:00

问题


I have an Image object that I would like to convert to an Icon or ImageIcon to add to a JTextPane. How would I go about doing this? (this is in JAVA)

clarification: my "Image" is an instance of the Image Object, not a File.


回答1:


What's wrong with new ImageIcon(Image)?

Image img = ...
ImageIcon icon = new ImageIcon(img);



回答2:


Add the image to your JTextPane document:

Image image = ImageIO.read(new File("myImage.jpg"));

StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);

Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

Icon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
StyleConstants.setComponent(labelStyle, label);

document.insertString(document.getLength(), "Ignored", labelStyle);

JTextPane textPane = new JTextPane(document);



回答3:


Try this...

Toolkit t = Toolkit.getDefaultToolkit();

Image i = t.getImage("icon.gif");

setIconImage(i);



回答4:


ImageIcon icon=null; 

ImageIcon imageicon = new ImageIcon("C:\\Winter.jpg");

if (imageicon != null) {

    if (imageicon.getIconWidth() > 60) {
        System.out.println(jLabel1.getWidth());
        icon = new ImageIcon(imageicon.getImage().getScaledInstance(26, -1, Image.SCALE_DEFAULT));
    } else {
        icon = imageicon;
}

jLabel1.setIcon((Icon) icon);


来源:https://stackoverflow.com/questions/12020597/java-convert-image-to-icon-imageicon

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