Creating an auto-complete JComboBox

Main.java:

import javax.swing.plaf.basic.*;
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);
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT));
 
      String[] elements = new String[] { "arthur", "brian", "chet", "danny", "dave",  
                                         "don", "edmond", "eddy", "glen", "gregory", "john",
                                         "ken", "malcolm", "pete", "stephanie", "yvonne" };
 
      JComboBox comboBox = new AutoCompleteComboBox(elements);
      getContentPane().add(comboBox);
   }
      
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}
 
class AutoCompleteComboBox extends JComboBox
{
   public int caretPos=0;
   public JTextField inputField=null;
 
   public AutoCompleteComboBox(final Object elements[]) {
      super(elements);
      setEditor(new BasicComboBoxEditor());
      setEditable(true);
   }
 
   public void setSelectedIndex(int index) {
      super.setSelectedIndex(index);
 
      inputField.setText(getItemAt(index).toString());
      inputField.setSelectionEnd(caretPos + tf.getText().length());
      inputField.moveCaretPosition(caretPos);
   }
 
   public void setEditor(ComboBoxEditor editor) {
      super.setEditor(editor);
      if (editor.getEditorComponent() instanceof JTextField) {
         inputField = (JTextField) editor.getEditorComponent();
 
         inputField.addKeyListener(new KeyAdapter() {
            public void keyReleased( KeyEvent ev ) {
               char key=ev.getKeyChar();
               if (! (Character.isLetterOrDigit(key) || Character.isSpaceChar(key) )) return;
 
               caretPos=inputField.getCaretPosition();
               String text="";
               try {
                  text=inputField.getText(0, caretPos);
               }
               catch (javax.swing.text.BadLocationException e) {
                  e.printStackTrace();
               }
 
               for (int i=0; i<getItemCount(); i++) {
                  String element = (String) getItemAt(i);
                  if (element.startsWith(text)) {
                     setSelectedIndex(i);
                     return;
                  }
               }
            }
         });
      }
   }
}

Have a JDialog always-on-top

+Please bear in mind that this freeware solution is licensed under the
+GNU General Public License. You must read, accept and enact *all*
+terms of this license in order to use it free of charge.

An excellent class has been written by Mitch Goldstein (Author of HARDCORE JFC) that uses JNI to perform this Windows-specific task.

You can download it here: WInterface.zip

Adding a JPanel with a null layout to a JScrollPane

Make sure you set the preferredSize of the JPanel. Invoke the method setViewportView on JScrollPane.

Main.java:

import java.awt.event.*;
import javax.swing.border.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame 
{
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      JPanel panel = createContactPanel();
 
      JScrollPane sp = new JScrollPane();
      sp.setViewportView(panel);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(sp, BorderLayout.CENTER); 
   }
 
   public JPanel createContactPanel() {
      JLabel titleLbl      = new JLabel("Title");
      JLabel firstNameLbl  = new JLabel("First name");
      JLabel lastNameLbl   = new JLabel("Last name");
      JLabel addressLbl    = new JLabel("Address");
      JLabel cityLbl       = new JLabel("City");
      JLabel zipLbl        = new JLabel("Postal code");
      JLabel countryLbl    = new JLabel("Country");
      JLabel phoneLbl      = new JLabel("Phone number");
      JLabel faxLbl        = new JLabel("Fax number");
      JLabel emailLbl      = new JLabel("E-mail");
      JLabel birthdayLbl   = new JLabel("Birthdate");
      JLabel pickchoiceLbl = new JLabel("Pick a choice");
      JLabel creditCardTypeLbl     = new JLabel("Credit card type");
      JLabel creditCardNumberLbl   = new JLabel("Credit card number");
      JLabel expirationLbl         = new JLabel("Expiration date");
 
      JComboBox titleCombo = new JComboBox(
             new String[] { "-", "Mr", "Mrs", "Miss" });
      JTextField firstNameTf    = new JTextField();
      JTextField lastNameTf     = new JTextField();
      JTextField address1Tf     = new JTextField();
      JTextField address2Tf     = new JTextField();
      JTextField cityTf         = new JTextField();
      JTextField zipTf          = new JTextField();
      JTextField countryTf      = new JTextField();
      JTextField phoneTf        = new JTextField();
      JTextField faxTf          = new JTextField();
      JTextField emailTf        = new JTextField();
      JComboBox bd1Combo = new JComboBox();
      for (int i=1; i<=12; i++) bd1Combo.addItem(""+i);
      JComboBox bd2Combo = new JComboBox();
      for (int i=1; i<=31; i++) bd2Combo.addItem(""+i);
      JComboBox bd3Combo = new JComboBox();
      for (int i=1900; i<2000; i++) bd3Combo.addItem(""+i);
      JComboBox referCombo = new JComboBox();
      referCombo.addItem("Friend");
      referCombo.addItem("Search engine");
      referCombo.addItem("Print Media");
      referCombo.addItem("Banner Add");
      referCombo.addItem("Other");
      JComboBox creditCardTypeCombo = new JComboBox();
      creditCardTypeCombo.addItem("VISA");
      creditCardTypeCombo.addItem("MasterCard");
      creditCardTypeCombo.addItem("American Express");
      JTextField creditCardNumberTf = new JTextField();
      JComboBox expiration1Combo = new JComboBox();
      for (int i=1; i<=12; i++) expiration1Combo.addItem(""+i);
      JComboBox expiration2Combo = new JComboBox();
      for (int i=1; i<=31; i++) expiration2Combo.addItem(""+i);
      JComboBox expiration3Combo = new JComboBox();
      for (int i=1900; i<=2000; i++) expiration3Combo.addItem(""+i);
 
      JPanel panelGeneral = new JPanel();
      panelGeneral.setLayout(null);
      panelGeneral.add(titleLbl);
      panelGeneral.setBorder(new TitledBorder("General Information"));
      titleLbl.setBounds(20, 20, 150, 20);
      panelGeneral.add(firstNameLbl);
      firstNameLbl.setBounds(20, 50, 150, 20);
      panelGeneral.add(lastNameLbl);
      lastNameLbl.setBounds(20, 80, 150, 20);
      panelGeneral.add(addressLbl);
      addressLbl.setBounds(20, 110, 150, 20);
      panelGeneral.add(cityLbl);
      cityLbl.setBounds(20, 170, 150, 20);
      panelGeneral.add(zipLbl);
      zipLbl.setBounds(20, 200, 150, 20);
      panelGeneral.add(countryLbl);
      countryLbl.setBounds(20, 230, 150, 20);
      panelGeneral.add(phoneLbl);
      phoneLbl.setBounds(20, 260, 150, 20);
      panelGeneral.add(faxLbl);
      faxLbl.setBounds(20, 290, 150, 20);
      panelGeneral.add(emailLbl);
      emailLbl.setBounds(20, 320, 150, 20);
      panelGeneral.add(birthdayLbl);
      birthdayLbl.setBounds(20, 350, 150, 20); 
      panelGeneral.add(titleCombo);
      titleCombo.setBounds(150, 20, 60, 20);
      panelGeneral.add(firstNameTf);
      firstNameTf.setBounds(150, 50, 200, 20);
      panelGeneral.add(lastNameTf);
      lastNameTf.setBounds(150, 80, 200, 20);
      panelGeneral.add(address1Tf);
      address1Tf.setBounds(150, 110, 200, 20);  
      panelGeneral.add(address2Tf);
      address2Tf.setBounds(150, 140, 200, 20);  
      panelGeneral.add(cityTf);
      cityTf.setBounds(150, 170, 200, 20);
      panelGeneral.add(zipTf);
      zipTf.setBounds(150, 200, 200, 20);
      panelGeneral.add(countryTf);
      countryTf.setBounds(150, 230, 200, 20);
      panelGeneral.add(phoneTf);
      phoneTf.setBounds(150, 260, 200, 20);
      panelGeneral.add(faxTf);
      faxTf.setBounds(150, 290, 200, 20);
      panelGeneral.add(emailTf);
      emailTf.setBounds(150, 320, 200, 20);
      panelGeneral.add(bd1Combo);
      bd1Combo.setBounds(150, 350, 60, 20);
      panelGeneral.add(bd2Combo);
      bd2Combo.setBounds(220, 350, 60, 20);
      panelGeneral.add(bd3Combo);
      bd3Combo.setBounds(290, 350, 60, 20);
 
      JPanel panelReferral = new JPanel();
      panelReferral.setLayout(null);
      panelReferral.setBorder(new TitledBorder("Where did you hear about us?"));
      panelReferral.add(pickchoiceLbl);
      pickchoiceLbl.setBounds(20, 20, 150, 20);
      panelReferral.add(referCombo);
      referCombo.setBounds(150, 20, 100, 20);
 
      JPanel panelCreditCard = new JPanel();
      panelCreditCard.setLayout(null);
      panelCreditCard.setBorder(new TitledBorder("Payment method"));
      panelCreditCard.add(creditCardTypeLbl);
      creditCardTypeLbl.setBounds(20, 20, 150, 20);
      panelCreditCard.add(creditCardNumberLbl);
      creditCardNumberLbl.setBounds(20, 50, 150, 20);
      panelCreditCard.add(expirationLbl);
      expirationLbl.setBounds(20, 80, 150, 20);
 
      panelCreditCard.add(creditCardTypeCombo);
      creditCardTypeCombo.setBounds(150, 20, 100, 20);
      panelCreditCard.add(creditCardNumberTf);
      creditCardNumberTf.setBounds(150, 50, 150, 20);
      panelCreditCard.add(expiration2Combo);
      expiration2Combo.setBounds(220, 80, 60, 20);
      panelCreditCard.add(expiration3Combo);
      expiration3Combo.setBounds(290, 80, 60, 20);
 
      JPanel panel = new JPanel();
      panel.setLayout(null);
      panel.add(panelGeneral);
      panelGeneral.setBounds(10, 20, 370, 400);
      panel.add(panelReferral);
      panelReferral.setBounds(10, 430, 370, 50);
      panel.add(panelCreditCard);
      panelCreditCard.setBounds(10, 490, 370, 120);
      
      panel.setPreferredSize(new Dimension(380, 620)); 
 
      return panel;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Creating a nested JTabbedPane

The following example nests JTabbedPanes recursively until 10 levels deep:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.beans.*;
 
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
      JTabbedPane tabbedPane = new JTabbedPane();
 
      getContentPane().add(BorderLayout.CENTER, tabbedPane);
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      setTitle("JTabbedPane Nested Demonstration");
      setSize(new Dimension(400, 400));
 
      createTab(tabbedPane, 0);
   }
 
   protected void createTab(JTabbedPane jtp, int ct) {
      if (ct > 10) return;
      JTabbedPane tp = new JTabbedPane();
      tp.setTabPlacement(getNextOrientation(jtp.getTabPlacement()));
      jtp.addTab("TabLevel #" + ct, tp);
      createTab(tp, ct+1);
   }
 
   private int getNextOrientation(int tabPlacement) {
      if (tabPlacement == JTabbedPane.TOP) return JTabbedPane.RIGHT;
      if (tabPlacement == JTabbedPane.RIGHT) return JTabbedPane.BOTTOM;
      if (tabPlacement == JTabbedPane.BOTTOM) return JTabbedPane.LEFT;
      else return JTabbedPane.TOP;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.show();
   }
}

Adding a radiobutton to a JToolBar

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   public Main()
   {
      JToolBar toolBar = new JToolBar();
 
      JRadioButton gifButton = new JRadioButton("GIF", false);
      JRadioButton jpgButton = new JRadioButton("JPG", false);
      JRadioButton tiffButton = new JRadioButton("TIFF", false);
 
      ButtonGroup group = new ButtonGroup();
      group.add(gifButton);
      group.add(jpgButton);
      group.add(tiffButton);
 
      toolBar.add(gifButton);
      toolBar.add(jpgButton);
      toolBar.add(tiffButton);
 
      getContentPane().setLayout(new BorderLayout());
      getContentPane().add(BorderLayout.NORTH, toolBar);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
      
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(300, 300);
      main.setVisible(true);
   }
}

Changing the color of the title bar and border of a JInternalFrame

This worked for me, using the Windows Look and Feel.

To change the colors of the title bar, modify some properties:

   InternalFrame.activeTitleBackground
   InternalFrame.activeTitleForeground
   InternalFrame.inactiveTitleBackground
   InternalFrame.inactiveTitleForeground

To change the border, you can call setBorder on a JInternalFrame.

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;
  
   public Main() {
      modifyColors();
      desktop = new JDesktopPane(); 
      setContentPane(desktop);
      setJMenuBar(createMenuBar());
      createInternalFrame(); 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   }
 
   protected void modifyColors() {
      try {
         String name = UIManager.getSystemLookAndFeelClassName();
         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
         UIManager.put("InternalFrame.activeTitleBackground", Color.red);
         UIManager.put("InternalFrame.activeTitleForeground", Color.blue);
         UIManager.put("InternalFrame.inactiveTitleBackground", Color.black);
         UIManager.put("InternalFrame.inactiveTitleForeground", Color.yellow);
      }
      catch(Exception e) { 
         e.printStackTrace();
      }
   }
 
   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);
 
      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); 
 
      frame.setBorder(BorderFactory.createLineBorder(Color.black));
 frame.updateUI();
      desktop.add(frame);
      frame.setSize(200, 200);
      frame.setLocation(30*nframes, 30*nframes);
      try {
         frame.setSelected(true);
      } catch (java.beans.PropertyVetoException e) {}
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(500, 300);
      main.setVisible(true);
   }
}

Specifying a JButton’s icon height and width

Main.java:

import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
 
public class Main {
 
   public static ImageIcon zoom(ImageIcon imI, double width, double height) {
      Image source = imI.getImage();
 
      BufferedImage dest = new BufferedImage(
            (int) (imI.getIconWidth() * width),
            (int) (imI.getIconHeight() * height),
            BufferedImage.TYPE_INT_RGB);
 
      AffineTransform ta = new AffineTransform();
 
      ta.scale(width, height);
 
      Graphics2D g2d = dest.createGraphics();
      g2d.drawImage(source, ta, null);
      g2d.dispose();
 
      return new ImageIcon(dest);
   }
 
   public static void main(String args[]) {
      JFrame f = new JFrame();
      JButton b = new JButton("test", new ImageIcon("button1.jpg"));
      b.setIcon(Main.zoom((ImageIcon) b.getIcon(), 0.5, 0.8));
      f.getContentPane().add(b);
      f.setSize(150, 150);
      f.setVisible(true);
   }
}

Showing a different tooltip for every item in a JComboBox

Modify the behavior of the ListRenderer such that it includes the currently selected JComboBox item in determining the tooltip text. Here’s an example:

import javax.swing.plaf.basic.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
    
public class Main extends JFrame
{ 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
      
      final JComboBox combobox = new JComboBox(new String[] { "Item 1", "Item 2", "Item 3" });
 
      getContentPane().add(combobox);
 
      combobox.setRenderer(new BasicComboBoxRenderer() {
         public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { 
            if (isSelected) { 
               setBackground(list.getSelectionBackground()); 
               setForeground(list.getSelectionForeground()); 
               if (index > -1) {
                  list.setToolTipText("Tooltip #" + new Integer(index).toString()); 
               }
            }
            else { 
               setBackground(list.getBackground()); 
               setForeground(list.getForeground()); 
            } 
            setFont(list.getFont()); 
            setText((value == null) ? "" : value.toString()); 
 
            return this; 
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}

Creating a JTextField as an element of JList

This example uses an EditableJList, a custom JList that only allows an EditableJList.EditableListModel as model. Our EditableListModel can only contain JTextComponents (JTextField, JTextArea, …) items.
The behavior is such that when double-clicking on the JList, the selected item is detected using the method locationToIndex and a border is added to it. The border will be removed when the textfield looses focus. To ensure that the JList element is being updated while editing the textfield, every DocumentEvent is captured and fireContentsChanged is called.
Main.java:

import javax.swing.event.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new BorderLayout());
 
      EditableJList.EditableListModel listModel = new EditableJList.EditableListModel();
 
      // populate listmodel
      Random r = new Random();
      for (int i=0; i&lt;50; i++) {
         String item = &quot;list item # &quot; + (Math.abs(r.nextInt()) % 100);
         JTextField tc = new JTextField(item);
//         JTextArea tc = new JTextArea(item);
//         JEditorPane tc = new JEditorPane(&quot;text/html&quot;, &quot;&lt;h3&gt;&quot; + item + &quot;&lt;/h3&gt;&quot;);
         listModel.addElement(tc);
      }
 
      EditableJList list = new EditableJList(listModel); 
      getContentPane().add(BorderLayout.CENTER, new JScrollPane(list));    
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class EditableJList extends JList {
   public EditableJList(EditableListModel listModel) {
      setModel(listModel);
      addMouseListener();
 
      // set our custom cell renderer
      setCellRenderer(new TextComponentCellRenderer()); 
   }
 
   private void addMouseListener() {  
      MouseListener mouseListener = new MouseAdapter() {
         public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
               EditableListModel listModel = (EditableListModel) getModel();
 
               // determine the clicked item
               int index = locationToIndex(e.getPoint());
               Object value = listModel.getElementAt(index);
               final JTextComponent tc = (JTextComponent) value;
 
               // set the appropriate border for editing 
               String classname = tc.getClass().getName().toString();
               classname = classname.substring(classname.lastIndexOf(&quot;.&quot;));
               tc.setBorder(UIManager.getBorder(classname + &quot;border&quot;));
 
               // make this border appear in the JList
               listModel.updateItem(index);
 
               tc.addFocusListener(new FocusListener() {
                  public void focusGained(FocusEvent fe) {
                     // no selection color desired when editing a JTextComponent
                     clearSelection();
                  }
 
                  public void focusLost(FocusEvent fe) {
                     // remove the border again when stopped editing
                     tc.setBorder(null);
                  }
               });
 
               // request the focus on this component to be able to edit it
               tc.requestFocus();
 
               // listen to all key events on the JTextComponent and update the 
               // JList item every time.  Without this, you won't see the changes.           
               tc.getDocument().addDocumentListener(new UpdateListDocumentListener(listModel, index));
            }
         }
      };
 
      addMouseListener(mouseListener);
   }
 
   // DocumentListener that takes care of updating a JList item
   // when editing it.  Calls updateItem on our custom EditableListModel
   private class UpdateListDocumentListener implements DocumentListener {
      private EditableListModel elm;
      private int index;
 
      public UpdateListDocumentListener(EditableListModel elm, int index) {
         this.elm = elm;
         this.index = index;
      }
 
      public void insertUpdate(DocumentEvent e) {
         elm.updateItem(index);
      }
 
      public void removeUpdate(DocumentEvent e) {
         elm.updateItem(index);
      }
 
      public void changedUpdate(DocumentEvent e) {
         elm.updateItem(index);
      }
   }
 
   private class TextComponentCellRenderer implements ListCellRenderer {
      public Component getListCellRendererComponent(
         JList list,
         Object value,            // value to display
         int index,               // cell index
         boolean isSelected,      // is the cell selected
         boolean cellHasFocus)    // the list and the cell have the focus
      {
         JTextComponent tc = (JTextComponent) value;
         if (isSelected) {
            tc.setBackground(list.getSelectionBackground());
            tc.setForeground(list.getSelectionForeground());
         }
         else {
            tc.setBackground(list.getBackground());
            tc.setForeground(list.getForeground());
         }
 
         tc.setEnabled(list.isEnabled());
         tc.setFont(list.getFont());
         tc.setBorder(null);
 
         return (Component) value;
      }
   }
 
   public static class EditableListModel extends DefaultListModel {
      public void updateItem(int index) {
         fireContentsChanged(this, index, index);
      }

      public void addElement(JTextComponent tc) {
         super.addElement(tc);
      }
   }
}

Disable the keyboard accellerator that has been assigned to a JMenuItem

Set the accelerator to null. This example assigns accelerators to the JMenuItems ‘male’ and ‘female’. Press CTRL-M and CTRL-F to invoke them. After 5 selections, the accelerators will be disabled.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   JMenuItem menuItem1;
   JMenuItem menuItem2;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Sex");
      menuItem1 = new JMenuItem("male");
      menuItem2 = new JMenuItem("female");
 
      // add the MenuItems to the Menu 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuItem1.setAccelerator(KeyStroke.getKeyStroke('M', Event.CTRL_MASK));
      menuItem2.setAccelerator(KeyStroke.getKeyStroke('F', Event.CTRL_MASK));
 
      // listen for events on these MenuItems
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
 
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   private int count = 0;
   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand());
 
      count++;
      if (count == 5) {
         System.out.println("now disabling accelerators");
 
         menuItem1.setAccelerator(null);
         menuItem2.setAccelerator(null);
      }
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}