![](/img/trans.png)
[英]Using javax.swing.ImageIcon to display a jpg i saved in the directory
[英]How do I paint a javax.swing.ImageIcon into a JavaFX .fxml rendered User Interface?
我正在开发一个使用旧资源提供程序的JavaFX富客户端。 其中一个提供的资源是javax.swing.ImageIcon
。 我必须在从 JavaFX.fxml 文件呈现的详细信息对话框中绘制该图标。
我发现的工作方式是使用ImageIcon.paintIcon()
方法和来自BufferedImage.createGraphics()
的java.awt.Graphics
将ImageIcon
绘制到java.awt.image.BufferedImage
中。 From that BufferedImage
, javafx.embed.swing.SwingFXUtils.toFXImage()
gives a javafx.scene.image.WritableImage
that can be placed in the ImageView
of the.fxml.
这是转换方法的代码,基于 StackOverflow 中查看的其他一些解决方案:
private javafx.scene.image.Image atonIcon2ImageConverter(ImageIcon icon) {
BufferedImage bi = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = bi.createGraphics();
// paint the Icon to the BufferedImage.
icon.paintIcon(null, g, 0, 0);
g.dispose();
return SwingFXUtils.toFXImage(bi.getSubimage(0, 1, bi.getWidth(), bi.getHeight()-1), null);
}
虽然这个解决方案有效,但在我看来它相当复杂,我想就如何使它更简单一些专家意见。 With JavaFX being the successor of Swing, I see quite possible that there is a simpler way to place a Swing ImageIcon
inside a JavaFX.fxml file (the ImageIcon
is given, but the ImageView
can be challenged).
在玩弄并混合了不同的评论和解决方案之后,这是我为我的真实系统实现得出的结论。 这绝对是一个非常特殊的环境( ImageIcon
内部有一个 Swing ToolkitImage
),因此它可能不适用于许多环境:
private javafx.scene.image.Image atonIcon2ImageConverter(ImageIcon icon) {
BufferedImage bi = ((sun.awt.image.ToolkitImage)imageIcon.getImage()).getBufferedImage();
return SwingFXUtils.toFXImage(bi, null);
}
你有没有尝试过:
ImageIcon imageIcon;
Image image = imageIcon.getImage();
BufferedImage bufferedImage = (BufferedImage) image;
或结合
BufferedImage bufferedImage = (BufferedImage) imageIcon.getImage();
这是否有效取决于在您的旧代码中如何构建 ImageIcons。 这是一个工作示例。 它还包含注释掉的不起作用的变体。
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class ImageIconTest {
public static void main(String[] args) throws IOException {
ImageIcon imageIcon = createImageIcon("/DukeCheers.png", "DukeCheers");
BufferedImage bufferedImage = (BufferedImage)imageIcon.getImage();
System.out.println("done");
}
private static ImageIcon createImageIcon(String path, String description) throws IOException {
java.net.URL imgURL = ImageIconTest.class.getResource(path);
if (imgURL != null) {
// This does not work.
// return new ImageIcon(imgURL, description);
// This works.
return new ImageIcon(ImageIO.read(imgURL), description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.