Programmatically closing a JInternalFrame

Use this:

   frame.getDesktopPane().getDesktopManager().closeFrame(frame);

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
 
public class Main extends JFrame {
   JDesktopPane desktop;
   int nframes = 0;
 
   JMenu internalFrameMenu;
   Action closeAction = new CloseAction();
 
   public Main() {
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected JMenuBar createMenuBar() {
      JMenuBar menuBar = new JMenuBar();
 
      JMenu createMenu = new JMenu("Create");
      createMenu.setMnemonic(KeyEvent.VK_C);
      JMenuItem newMenuItem = new JMenuItem("New");
      newMenuItem.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            createInternalFrame();
         }
      }); 
      newMenuItem.setMnemonic(KeyEvent.VK_N);
      createMenu.add(newMenuItem);
      menuBar.add(createMenu);
 
      internalFrameMenu = new JMenu("Close");
      internalFrameMenu.setMnemonic(KeyEvent.VK_C);
  
      menuBar.add(internalFrameMenu);     
 
      return menuBar;
   }
 
   protected void createInternalFrame() {
      nframes++;
      String title = "JInternalFrame #" + nframes;
      JInternalFrame frame = new JInternalFrame(title,
         true,    // resizable
         true,    // closable
         true,    // maximizable
         true);   // iconifiable
      frame.setVisible(true); 
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
 
      JMenuItem menuItem = new JMenuItem(title);
      internalFrameMenu.add(menuItem);
      menuItem.addActionListener(closeAction);
      frames.put(title, frame);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
 
   public class CloseAction extends AbstractAction
   {
      public CloseAction() {
         super("Close Action");
      }
 
      public void actionPerformed(ActionEvent ae) {
         JMenuItem menuItem = ((JMenuItem) ae.getSource());
         JInternalFrame frame = (JInternalFrame) frames.get(menuItem.getText());
         // close the frame
         frame.getDesktopPane().getDesktopManager().closeFrame(frame);
         // remove JMenuItem from JMenu
         JMenu parent = (JMenu) ((JPopupMenu) menuItem.getParent()).getInvoker();
         parent.remove(menuItem);
      }
   }
}