java给标签添加图标,Java / JavaFX:为JavaFX标签设置Swing图标

I'm trying to read a thumbnail (icon; 32x32px) from a file (.ico/.exe) and set it to a JavaFX label.

My first try:

public Icon getLargeIcon(String exeFile) {

if (exeFile != null) {

File file = new File(exeFile);

try {

ShellFolder sf = ShellFolder.getShellFolder(file);

return new ImageIcon(sf.getIcon(true), sf.getFolderType());

} catch (FileNotFoundException e) {

e.printStackTrace();

}

}

return null;

}

After that I'm doing this:

Icon largeIcon = getLargeIcon(file.getAbsolutePath());

ImageIcon swingImageIcon = (ImageIcon) largeIcon;

java.awt.Image awtImage = swingImageIcon.getImage();

Image fxImage = javafx.scene.image.Image.impl_fromPlatformImage(awtImage);

lblAppIconValue.setGraphic(new ImageView(fxImage));

I've searched trough several sites and found this, but it gives me an exception:

java.lang.UnsupportedOperationException: unsupported class for loadPlatformImage

My second try:

URL url = file.toURI().toURL();

Image image = new Image(url.toString());

lblAppIconValue.setGraphic(new ImageView(image));

Also not working ...

My question: How can I set a javax.swing.Icon to a JavaFX label? Is it possible? If it's not possible, how can I read a thumbnail from a file and set it as an icon/graphic for a JavaFX label?

Thanks!

解决方案

Never use impl_ methods: these are not part of the public API.

To convert an awt Image to an FX Image, the SwingFXUtils class in javafx.embed.swing has a toFXImage(...) method that converts a BufferedImage to a JavaFX Image. It's not clear whether the image you have from the icon is a BufferedImage, so you'll need a couple of steps to make that work:

BufferedImage bImg ;

if (awtImage instanceof BufferedImage) {

bImg = (BufferedImage) awtImage ;

} else {

bImg = new BufferedImage(awtImage.getWidth(null), awtImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);

Graphics2D graphics = bImg.createGraphics();

graphics.drawImage(awtImage, 0, 0, null);

graphics.dispose();

}

Image fxImage = SwingFXUtils.toFXImage(bImg, null);

This is a fairly inefficient approach, as you are first creating an awt image from your file, then converting it to an FX image, possibly via an intermediate buffered image. If you have access to the source code for the ShellFolder class, you might see how that implements the getIcon() method and follow the same process. At some point, it must get an InputStream with the image data; once you have that you can pass it to the javafx.scene.image.Image constructor.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值