Question

Say I have got a image file, which shows a dog (just for example). During execution, I want to display the image located at "C:\image.png" (again, just saying) to be displayed by using System.out.println or basic GUI by using Swing class. I am curious to know about it, so if it is possible, it'd be so helpful if you could kindly explain. Same for if not possible. Thanks a ton!

EDIT: Is it impossible to include images in System.out.println?

Was it helpful?

Solution

This should work for images of dogs as well as for images of cats.

import java.awt.GridLayout;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;


public class ShowImage
{
    public static void main(String[] args)
    {
        showImage("C:/image.png");
    }

    private static void showImage(final String fileName)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                JFrame f = new JFrame();
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.getContentPane().setLayout(new GridLayout(1,1));
                f.getContentPane().add(new JLabel(new ImageIcon(fileName)));
                f.pack();
                f.setLocationRelativeTo(null);
                f.setVisible(true);
            }
        });
    }
}

For images of horses, slight adjustments might be necessary.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top