Demonstrating JDesktopPane. - Java Swing

Java examples for Swing:JDesktopPane

Description

Demonstrating JDesktopPane.

Demo Code

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.security.SecureRandom;

import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;

class DesktopFrame extends JFrame {
  final JDesktopPane theDesktop;

  public DesktopFrame() {
    JMenuBar bar = new JMenuBar();
    JMenu addMenu = new JMenu("Add");
    JMenuItem newFrame = new JMenuItem("Internal Frame");

    addMenu.add(newFrame);/* w  w w.j  a  va 2 s . c  o  m*/
    bar.add(addMenu);
    setJMenuBar(bar);

    theDesktop = new JDesktopPane();
    add(theDesktop);

    newFrame.addActionListener(e -> {
      JInternalFrame frame = new JInternalFrame("Internal Frame", true, true,
          true, true);

      MyJPanel panel = new MyJPanel();
      frame.add(panel, BorderLayout.CENTER);
      frame.pack();

      theDesktop.add(frame);
      frame.setVisible(true);
    });
  }
}

class MyJPanel extends JPanel {
  private static final SecureRandom generator = new SecureRandom();
  private final ImageIcon picture; // image to be displayed
  private static final String[] images = { "a.png", "b.png", "c.png", "d.png",
      "e.png" };

  // load image
  public MyJPanel() {
    int randomNumber = generator.nextInt(images.length);
    picture = new ImageIcon(images[randomNumber]); // set icon
  }

  // display imageIcon on panel
  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    picture.paintIcon(this, g, 0, 0); // display icon
  }

  // return image dimensions
  public Dimension getPreferredSize() {
    return new Dimension(picture.getIconWidth(), picture.getIconHeight());
  }
}

public class Main {
  public static void main(String[] args) {
    DesktopFrame desktopFrame = new DesktopFrame();
    desktopFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    desktopFrame.setSize(600, 480);
    desktopFrame.setVisible(true);
  }
}

Related Tutorials