showImage.java
import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.io.*; import javax.imageio.*; import javax.swing.*; public class showImage extends JFrame { BufferedImage img; public showImage(BufferedImage img, String title) { this.img = img; setup(title); } public showImage(String filename) { readImage(filename); setup(filename); } private void setup(String title) { setTitle(title); //setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); add(new ImagePanel()); pack(); setLocationRelativeTo(null); setVisible(true); } public void readImage(String filename) { try { img = ImageIO.read(new File(filename)); } catch (IOException e) { //System.out.println(e); // e.getMessage()); System.out.println(filename + " not found"); System.exit(-1); } } public void writeImage(String filename) { writeImage(filename,"jpg"); } public void writeImage(String filename, String format) { File file = new File(filename + "." + format); try { ImageIO.write(img, format, file); } catch (IOException e) { System.out.println("image write failed"); System.out.println(e); System.exit(-1); } } public Dimension getPreferredSize() { if (img == null) { return new Dimension(100,100); } else { return new Dimension(img.getWidth(null), img.getHeight(null)); } } class ImagePanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(img, 0, 0, null); } } public static void main(String[] args) { showImage f1 = new showImage("owl.jpg"); f1.setLocation(100,100); f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); showImage f2 = new showImage("bld.jpg"); int w = f1.getWidth(); f2.setLocation(150+w,100); showImage f3 = new showImage("duke_skateboard.jpg"); int h = f1.getHeight(); f3.setLocation(100,150+h); } }
Maintained by John Loomis, updated Thu Oct 10 11:09:37 2013