簡體   English   中英

如何將 javax.swing.ImageIcon 繪制到 JavaFX.fxml 呈現的用戶界面中?

[英]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.GraphicsImageIcon繪制到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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM