Java Swing How to - Display image with JInternalFrame








Question

We would like to know how to display image with JInternalFrame.

Answer

import java.awt.BorderLayout;
import java.awt.Image;
import java.io.IOException;
import java.net.URL;
/*w w  w.j av  a 2 s.  c  o m*/
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(final String[] args) throws IOException {
    final URL url1 = new URL("http://www.java2s.com/style/download.png");
    final URL url2 = new URL("http://www.java2s.com/style/download.png");
    final URL url3 = new URL("http://www.java2s.com/style/download.png");

    final PictureDesktop desktop = new PictureDesktop();
    desktop.addPicture(ImageIO.read(url1));
    desktop.addPicture(ImageIO.read(url2));
    desktop.addPicture(ImageIO.read(url3));

    final JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(BorderLayout.CENTER, desktop);
    frame.setSize(720, 480);
    frame.setVisible(true);
  }

}

class PictureDesktop extends JDesktopPane {
  public void addPicture(final Image image) {
    add(createFrame(image));
  }
  private static int frames;
  private JInternalFrame createFrame(final Image image) {
    frames++;
    final JInternalFrame frame = new JInternalFrame("Picture " + frames);
    frame.add(BorderLayout.CENTER, new JLabel(new ImageIcon(image)));
    frame.pack();
    frame.setVisible(true);
    frame.setLocation(40 * frames, 40 * frames);
    return frame;
  }
}