我有一个Image对象,我想将其转换为Icon或ImageIcon以添加到JTextPane。我将如何去做呢?(这是在JAVA中)
说明:我的“图像”是图像对象的实例,而不是文件。
new ImageIcon(Image)
将图像添加到您的JTextPane文档:
Image img = ...
ImageIcon icon = new ImageIcon(img);
尝试一下...
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);
Toolkit t = Toolkit.getDefaultToolkit();
Image i = t.getImage("icon.gif");
setIconImage(i);
将图像转换为图标,例如在Netbeans中将Icon设置为jLable,我使用下面的代码将其设为true:
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);