Controlling transparancy when two Swing shapes overlap

Use the class AlphaComposite as shown in following example.

Main.java:

import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.text.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      g2d.setColor(Color.blue);
      g2d.fill(new Ellipse2D.Float(50, 30, 80, 50));
      g2d.setColor(Color.red);
      g2d.fill(new Ellipse2D.Float(100, 30, 80, 50));
 
      g2d.setColor(Color.black);
      g2d.drawLine(0, 90, 250, 90);
      
      DecimalFormat decimalFormat = (DecimalFormat)NumberFormat.getInstance();
      decimalFormat.applyPattern("0.0");
 
      int yd = 80;
      for (float f = 1f; f>=0f; f-=.2f) {
         g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
         g2d.setColor(Color.black);
         g2d.drawString("AlphaComposite = " + decimalFormat.format(f), 50, 50 + yd - 10);
         g2d.setColor(Color.blue);
         g2d.fill(new Ellipse2D.Float(50, 50 + yd, 80, 50));
 
         AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, f);
         g2d.setComposite(ac);
 
         g2d.setColor(Color.red);
         g2d.fill(new Ellipse2D.Float(100, 50 + yd, 80, 50));
 
         yd += 80;
      }
   }
  
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(250, 600);
      main.setVisible(true);
   }
}

Drawing a gradient-filled shape in Swing

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
   }
 
   public void paint(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      GradientPaint gp = new GradientPaint(20, 50, Color.red, 100, 130, Color.blue, true);
      g2d.setPaint(gp);
      g2d.fillRect(20, 50, 80, 80);
      g2d.setColor(Color.black);
      g2d.drawLine(20, 50, 100, 130);
 
      gp = new GradientPaint(140, 50, Color.red, 220, 130, Color.blue, false);
      g2d.setPaint(gp);
      g2d.fillRect(140, 50, 80, 80);       
      g2d.setColor(Color.black);
      g2d.drawLine(140, 50, 220, 130);
 
      gp = new GradientPaint(260, 60, Color.red, 270, 60, Color.blue, true);
      g2d.setPaint(gp);
      g2d.fillRect(260, 50, 80, 80);
      g2d.setColor(Color.black);
      g2d.drawLine(260, 60, 270, 60);
 
      gp = new GradientPaint(380, 60, Color.red, 390, 60, Color.blue, false);
      g2d.setPaint(gp);
      g2d.fillRect(380, 50, 80, 80);
      g2d.setColor(Color.black);
      g2d.drawLine(380, 60, 390, 60);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(480, 160);
      main.setVisible(true);
   }
}

Drawing text on top of a BufferedImage

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   BufferedImage image;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      createImage();
   }
 
   public void createImage() {
      Image backImage = new javax.swing.ImageIcon("mong.jpg").getImage(); 
      int width = backImage.getWidth(this); 
      int height = backImage.getHeight(this); 
      image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
      Graphics2D g2d = image.createGraphics(); 
      g2d.drawImage(backImage, 0, 0, this); 

      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                           RenderingHints.VALUE_ANTIALIAS_ON);
      Font f = new Font("Mistral", Font.BOLD, 56);
      g2d.setFont(f);
      String text = "Philip Elliott";
      FontMetrics fm = getFontMetrics(f);       
      int swidth = fm.stringWidth(text);
      int sheight = fm.getAscent();
 
      GradientPaint gp = new GradientPaint(20, 50, Color.red, 
                                           100, 130, Color.yellow, true); 
      g2d.setPaint(gp);
      g2d.drawString(text, width/2 - swidth/2, height/2 + sheight/2);   
 
      setSize(width, height);
   }
  
   public void paint(Graphics g) { 
      Graphics2D g2d = (Graphics2D) g; 
 
      g2d.drawImage(image, null, 0, 0); 
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}

Image used:

Use double-buffering for animation in Swing

Look at the performance between these two examples. The first one (Main1.java) will directly write to the graphics context and results in lots of flickering. The second one (Main2.java) uses instead to an intermediate buffer.

Main1.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main1 extends JFrame implements Runnable {
   int pos = 0;
   int WIDTH = 300;
   int HEIGHT = 150;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      setSize(WIDTH, HEIGHT);
   } 
 
   public void update(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      g.setColor(Color.white);
      g.fillRect(0, 0, WIDTH, HEIGHT);
 
      g.setColor(Color.black);
      g.fillRect(10 + pos, 50, 50, 50);
   }
 
   public void run() {
      setResizable(false); 
 
      while (true) {
         pos++;
         if (pos > 220) pos = 0;
         repaint();
 
         try {
            Thread.sleep(10);
         }
         catch(InterruptedException e) {
         }
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
 
      Thread t = new Thread(main);
      t.start();
   }
}

Main2.java:

import java.awt.image.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.*;
 
public class Main2 extends JFrame implements Runnable {
   BufferedImage buffer;
   Graphics bufferGraphics;
   int pos = 0;
   int WIDTH = 300;
   int HEIGHT = 150;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      setSize(WIDTH, HEIGHT);
   } 
 
   public void update(Graphics g) {
      Graphics2D g2d = (Graphics2D) g;
 
      bufferGraphics.setColor(Color.white);
      bufferGraphics.fillRect(0, 0, WIDTH, HEIGHT);
 
      bufferGraphics.setColor(Color.black);
      bufferGraphics.fillRect(10 + pos, 50, 50, 50);
 
      g2d.drawImage(buffer, 0, 0, this);
   }
 
   public void run() {
      buffer = (BufferedImage) createImage(WIDTH, HEIGHT);
      bufferGraphics = buffer.createGraphics();
      setResizable(false); 
 
      while (true) {
         pos++;
         if (pos > 220) pos = 0;
         repaint();
 
         try {
            Thread.sleep(10);
         }
         catch(InterruptedException e) {
         }
      }
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
 
      Thread t = new Thread(main);
      t.start();
   }
}

Catching events while an image is being written out using ImageIO

Register an IIOWriteProgressListener with your ImageWriter.

   IIOWriteProgressListener listener = new MyWriteProgressListener();
   writer.addIIOWriteProgressListener(listener);

This example reads a JPG and creates a new one, vertically subsampled.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 1 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg");
         System.exit(1);
      }
 
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      BufferedImage bi = reader.read(0);
 
      IIOWriteProgressListener listener = new MyWriteProgressListener();
      writer.addIIOWriteProgressListener(listener);
 
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      ImageWriteParam param = writer.getDefaultWriteParam();
 
      IIOImage iioImage = new IIOImage(bi, null, null);
      param.setSourceSubsampling(1, 4, 0, 0);
      writer.setOutput(ios);
      writer.write(null, iioImage, param);
   }
 
   static class MyWriteProgressListener implements IIOWriteProgressListener {
        float last = 0;
 
	public MyWriteProgressListener() {}

        public void imageStarted(ImageWriter dest, int imageIndex)  { 
           System.out.println("0% -----------------------------------> 100%n");
        }
 
        public void imageProgress(ImageWriter dest, final float percentageDone) {
           int n = (int) (percentageDone-last);
           for (int i=0; i<n/2; i++) {
              System.out.print("*");
           }
           last = percentageDone;
        }
 
        public void imageComplete(ImageWriter dest) { 
           System.out.println();
        }
 
        public void writeAborted(ImageWriter dest)                  { }
        public void sequenceComplete(ImageWriter dest)              { }
        public void sequenceStarted(ImageWriter dest, int minIndex) { }
        public void thumbnailComplete(ImageWriter dest)             { }
        public void thumbnailProgress(ImageWriter dest, float percentageDone) { }
        public void thumbnailStarted(ImageWriter dest, int imageIndex, int thumbnailIndex) { }
   }
}

Examples of JOptionPane?

   JOptionPane.showMessageDialog(frame, "File successfully imported!");

   JOptionPane.showMessageDialog(frame, "Deprecated version", "Warning", 
                                 JOptionPane.WARNING_MESSAGE);

   JOptionPane.showMessageDialog(frame, "Error importing file!", "Error", 
                                 JOptionPane.ERROR_MESSAGE);

   JOptionPane.showMessageDialog(frame, "File successfully imported!", "Message", 
                                 JOptionPane.PLAIN_MESSAGE);

   JOptionPane.showMessageDialog(frame, "File successfully imported?", "Question",
                                 JOptionPane.QUESTION_MESSAGE);

   ImageIcon icon = new ImageIcon("thumbsup.gif");
   JOptionPane.showMessageDialog(frame, "File successfully imported!", "Hey", 
                                 JOptionPane.INFORMATION_MESSAGE, icon);

   int status = JOptionPane.showOptionDialog(frame, "Are you sure you want to import this file?", 
                                             "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                             JOptionPane.QUESTION_MESSAGE, null, null, null);
   System.out.println("Option " + status + " selected!");

   Object[] options = { "Ja", "Nee", "Annuleren", "Test" };
   status = JOptionPane.showOptionDialog(frame, "Ben je zeker dat je dit bestand wilt importeren?",
                                         "vraag", -1, JOptionPane.QUESTION_MESSAGE, null,
                                         options, options[2]);
   System.out.println("Option " + status + " selected!");

   options = new Object[] { "Yes, please", "No, thanks" };
   status = JOptionPane.showOptionDialog(frame, "Error importing, try again?", "Question",
                                         -1, JOptionPane.ERROR_MESSAGE, null,
                                         options, options[0]);
   System.out.println("Option " + status + " selected!");

   String value = JOptionPane.showInputDialog("Please enter your name"); 
   System.out.println("You entered: " + value);

   options = new Object[] { "male", "female" };
   value = (String) JOptionPane.showInputDialog(frame, "Select your sex", "Input", 
                                                JOptionPane.QUESTION_MESSAGE, icon, options, 
                                                options[1]); 
   System.out.println("You entered: " + value);

   JDesktopPane desktop = new JDesktopPane(); 
   frame.setContentPane(desktop);
   frame.setSize(new Dimension(400, 200));
   frame.setLocation(100, 100);
   frame.setVisible(true);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
   status = JOptionPane.showInternalOptionDialog(desktop, "Are you sure you want to import this file?", 
                                                 "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                 JOptionPane.QUESTION_MESSAGE, null, null, null);
   System.out.println("Option " + status + " selected!");

The complete working example: Main.java:

import javax.swing.*;
import java.awt.*;
 
public class Main
{
   public static void main(String []args) {
      JFrame frame = new JFrame();
 
      // #1 
      JOptionPane.showMessageDialog(frame, "File successfully imported!");
 
      // #2
      JOptionPane.showMessageDialog(frame, "Deprecated version", "Warning", 
                                    JOptionPane.WARNING_MESSAGE);
 
      // #3
      JOptionPane.showMessageDialog(frame, "Error importing file!", "Error", 
                                    JOptionPane.ERROR_MESSAGE);
      
      // #4
      JOptionPane.showMessageDialog(frame, "File successfully imported!", "Message", 
                                    JOptionPane.PLAIN_MESSAGE);
 
      // #5
      JOptionPane.showMessageDialog(frame, "File successfully imported?", "Question",
                                    JOptionPane.QUESTION_MESSAGE);
 
      // #6
      ImageIcon icon = new ImageIcon("thumbsup.gif");
      JOptionPane.showMessageDialog(frame, "File successfully imported!", "Hey", 
                                    JOptionPane.INFORMATION_MESSAGE, icon);
 
      // #7
      int status = JOptionPane.showOptionDialog(frame, "Are you sure you want to import this file?", 
                                                "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                JOptionPane.QUESTION_MESSAGE, null, null, null);
      System.out.println("Option " + status + " selected!");
 
      // #8
      Object[] options = { "Ja", "Nee", "Annuleren", "Test" };
      status = JOptionPane.showOptionDialog(frame, "Ben je zeker dat je dit bestand wilt importeren?",
                                            "vraag", -1, JOptionPane.QUESTION_MESSAGE, null,
                                            options, options[2]);
      System.out.println("Option " + status + " selected!");
 
      // #9
      options = new Object[] { "Yes, please", "No, thanks" };
      status = JOptionPane.showOptionDialog(frame, "Error importing, try again?", "Question",
                                            -1, JOptionPane.ERROR_MESSAGE, null,
                                            options, options[0]);
      System.out.println("Option " + status + " selected!");
 
      // #10
      String value = JOptionPane.showInputDialog("Please enter your name"); 
      System.out.println("You entered: " + value);
      
      // #11
      options = new Object[] { "male", "female" };
      value = (String) JOptionPane.showInputDialog(frame, "Select your sex", "Input", 
                                                   JOptionPane.QUESTION_MESSAGE, icon, options, 
                                                   options[1]); 
      System.out.println("You entered: " + value);
 
      // #12
      JDesktopPane desktop = new JDesktopPane(); 
      frame.setContentPane(desktop);
      frame.setSize(new Dimension(400, 200));
      frame.setLocation(100, 100);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
      status = JOptionPane.showInternalOptionDialog(desktop, "Are you sure you want to import this file?", 
                                                    "Question", JOptionPane.YES_NO_CANCEL_OPTION, 
                                                    JOptionPane.QUESTION_MESSAGE, null, null, null);
      System.out.println("Option " + status + " selected!");
 
      System.exit(1);
   }
}

Creating a scrollable JPanel

Create a JScrollPane and pass your panel to its constructor. Then add the scrollpane to the container. Make sure your panel has a size in case you use the null layout manager (with setSize and setPreferredSize). Here’s an example that uses a BorderLayout.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      JPanel panel = createPanel();
 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(panel));
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   public static JPanel createPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new GridLayout(20, 4, 10, 10));
 
      for (int i=0; i<20; i++) {
         for (int j=0; j<4; j++) {
            JLabel label = new JLabel("label " + i + ", " + j);
            label.setFont(new Font("Helvetica", Font.PLAIN, 30));
            panel.add(label);            
         }
      }
 
      return panel;
   }
 
   public static void main(String [] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   } 
} 

Find out what JTabbedPane tab is selected

Note:
1.Each Tab in a Tabbed Pane is a JPanel i.e it has a name
2.The first Tab index is ’0′, 2′nd tab ’1′ and so on.
3.’StateChanged’ event is fired on selection of a tab.

....
....
....
tabbedPane.addChangeListener(changeListener)
....
....
public void stateChanged(changeEvent)
{
   if(e.getSource() == tabbedPane)
   {
      int i = tabbedPane.getSelectedIndex();
      Component c = tabbedPane.getSelectedComponent();
   }
}
....
....

Adding a vertical line separator to a JToolBar

The method addSeparator in the JToolBar class only adds blank space. You could add JSeparator components to your JToolBar with add but then you run into trouble when changing the orientation. In the following example, this has been solved by listening to propertyChangeEvents and changing the JSeparator orientation so that they are opposite to the JToolBar’s orientation.

Main.java:

import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
import java.awt.*;
  
public class Main extends JFrame {
   public Main() {
      super("JToolBar example");
 
      final JTextArea textArea = new JTextArea(5, 30);
      MyJToolBar toolBar = new MyJToolBar();
 
      JButton gifButton = new JButton(new ImageIcon("gifIcon.gif"));
      JButton jpgButton = new JButton(new ImageIcon("jpgIcon.gif"));
      JButton tiffButton = new JButton(new ImageIcon("tiffIcon.gif"));
 
      gifButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("gifButton clicked!n");
         }
      });
  
      jpgButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("jpgButton clicked!n");
         }
      });
        
      tiffButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            textArea.append("tiffButton clicked!n");
         }
      });
 
      toolBar.add(gifButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(new JSeparator(JSeparator.VERTICAL));
      toolBar.add(new JToolBar.Separator());
      toolBar.add(jpgButton);
      toolBar.add(new JToolBar.Separator());
      toolBar.add(new JSeparator(JSeparator.VERTICAL));
      toolBar.add(new JToolBar.Separator());
      toolBar.add(tiffButton);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(textArea));
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class MyJToolBar extends JToolBar
{
   public MyJToolBar() {
      super();
      listenForOrientationChange();
   }
 
   public MyJToolBar(int orientation) {
      super(orientation);
      listenForOrientationChange();
   }
 
   public MyJToolBar(String name) {
      super(name);
      listenForOrientationChange();
   }
 
   public MyJToolBar(String name, int orientation) {
      super(name, orientation);
      listenForOrientationChange();
   }
 
   protected void listenForOrientationChange() {
      addPropertyChangeListener(new PropertyChangeListener() {
         public void propertyChange(PropertyChangeEvent evt) {
            MyJToolBar toolBar = MyJToolBar.this;
            Component[] components = toolBar.getComponents();
            for (int i=0; i<components.length; i++) {
               if (components[i] instanceof javax.swing.JSeparator) {
                  JSeparator separator = (JSeparator) components[i];
                  if (toolBar.getOrientation() == SwingConstants.HORIZONTAL) {
                     separator.setOrientation(JSeparator.VERTICAL);      
                     separator.setMaximumSize(new Dimension(2,
                                              toolBar.getPreferredSize().width));
                  }
                  else {
                     separator.setOrientation(JSeparator.HORIZONTAL);
                     separator.setMaximumSize(new Dimension(
                                              toolBar.getPreferredSize().height, 2));
                  }
               }
            }
         }
      });
   }
}

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);
      }
   }
}