簡體   English   中英

在小程序中繪制緩沖的圖像

[英]Draw a buffered image in an applet

我正在嘗試做的是將已經緩沖的圖像繪制到JFrame。

JFrame p1=new JFrame();
p1.getContentPane();
p1.setSize(new Dimension(h,w));
p1.setVisible(true);
p1.update(bufferedImage.getGraphics());

到目前為止,這是代碼。 bufferedImage是一個緩沖的圖像,但是此代碼僅打開JFrame而不繪制圖像。 我以前從未使用過圖形。 謝謝

1)將BufferedImage作為圖標添加JLabel

2)不要直接畫到JFrame放在JComponent / JPanel上

看到這個工作代碼:

public static void main(String[] args) throws Exception {
    BufferedImage buf=null;
    try {
        buf = ImageIO.read(new File("estbest.jpg"));
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    new ImageFrame(buf, "Input Image ");
}

ImageFrame類別:

public class ImageFrame extends JFrame {
    BufferedImage image;

    public ImageFrame(final BufferedImage image) {
        this(image, "No Title");
    }

    public ImageFrame(final BufferedImage image, final String title) {
        this.image = image;
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                if (image != null) {
                    setSize(image.getWidth(null), image.getHeight(null));
                } else {
                    setSize(250, 90);
                }
                setTitle(title);
                setVisible(true);
                repaint();
            }
        });
    }

    public void paint(Graphics g) {
        if (image == null) {
            g.setColor(Color.BLACK);
            g.fillRect(0, 0, 250, 90);
            System.out.println("image null");
            g.setFont(new Font("Arial", Font.BOLD, 24));
            g.setColor(Color.RED);
            g.drawString("Invalid or No Image", 10, 50);
        } else {
            g.drawImage(image, 0, 0, null);
        }
    }
}

來源: Java:在JFrame中加載圖像-可重用ImageFrame

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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