Java: Loading images in JFrame - Reusable ImageFrame

Sometimes we need to show multiple images in separate window by using single line statement :
new ImageFrame(inImg, "Input Image ");// inImg is reference to Image object
The code below can be used to load images in JFrame as a separate window.
It also checks for null and displays message "Invalid or No Image".

The Full Working Source Code :


Testing : 
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 Class : 
//shows image in separate instance of JFrame - 
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

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);
        }
    }
}


No comments :

Post a Comment

Your Comment and Question will help to make this blog better...