Showing a popup-menu when a user right-clicks on an element in a JList

This example creates a JList and shows a popupmenu only when the user clicked on the selected item.
Main.java:

import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
  
public class Main extends JFrame {
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      final DefaultListModel listModel = new DefaultListModel();   
 
      // populate listmodel
      for (int i=0; i<5; i++) {
         listModel.addElement("list item #" + i);
      }
 
      final JList list = new JList(listModel); 
      getContentPane().add(new JScrollPane(list));    
 
      final JPopupMenu popupMenu = new JPopupMenu();
      popupMenu.add(new JMenuItem("PopupItem 1"));
      popupMenu.add(new JMenuItem("PopupItem 2"));
      popupMenu.add(new JPopupMenu.Separator());
      popupMenu.add(new JMenuItem("PopupItem 3"));
 
      list.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isRightMouseButton(me)    // if right mouse button clicked
                  && !list.isSelectionEmpty()            // and list selection is not empty
                  && list.locationToIndex(me.getPoint()) // and clicked point is
                     == list.getSelectedIndex()) {       //   inside selected item bounds
               popupMenu.show(list, me.getX(), me.getY());
            }
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      pack();
   }
   
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Displaying a popup-menu when right-clicking on a JTable header

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
 
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      final JTable table = new JTable(wineModel);
 
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));

      final JPopupMenu popupMenu = new JPopupMenu();
      popupMenu.add(new JMenuItem("PopupItem 1"));
      popupMenu.add(new JMenuItem("PopupItem 2"));
      popupMenu.add(new JPopupMenu.Separator());
      popupMenu.add(new JMenuItem("PopupItem 3"));

      final JTableHeader header = table.getTableHeader();
      header.addMouseListener(new MouseAdapter() {
         public void mouseClicked(MouseEvent me) {
            if (SwingUtilities.isRightMouseButton(me))
               popupMenu.show(header, me.getX(), me.getY());
         }
      });
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
} 

Catching the event when a JMenuItem has been selected

Add an ActionListener object. Here’s an example:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu(&quot;menu&quot;);
      JMenuItem menuItem1 = new JMenuItem(&quot;option 1&quot;);
      JMenuItem menuItem2 = new JMenuItem(&quot;option 2&quot;);
      JMenuItem menuItem3 = new JMenuItem(&quot;option 3&quot;);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
      menuItem3.addActionListener(this);
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(new JSeparator());
      menu.add(menuItem3);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }

   public void actionPerformed(ActionEvent ae) {
      System.out.println(ae.getActionCommand() + &quot; selected!&quot;);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Adding a JMenuBar to the two components of a JSplitPane

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame
{
   JSplitPane splitPane;
  
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
 
      JPanel firstPanel = createPanel();
      JPanel secondPanel = createPanel();
      splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, firstPanel, secondPanel);
 
      createMainMenuBar();
 
      getContentPane().add(splitPane);
      setSize(300, 300);
      setVisible(true);
 
      splitPane.setDividerLocation(0.5); 
   }
 
   public void createMainMenuBar() {
      JMenuBar mainBar = new JMenuBar();
      JMenu menu = new JMenu(&amp;quot;JSplitPane&amp;quot;);
      JMenuItem item1 = new JMenuItem(&amp;quot;HORIZONTAL_SPLIT&amp;quot;);
      JMenuItem item2 = new JMenuItem(&amp;quot;VERTICAL_SPLIT&amp;quot;);
      menu.add(item1);
      menu.add(item2);
      mainBar.add(menu);
      setJMenuBar(mainBar);
 
      item1.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         }
      });
 
      item2.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
         }
      });
   }
 
   public JPanel createPanel() {
      JPanel panel = new JPanel();
      panel.setLayout(new BorderLayout());
      JMenuBar menuBar = new JMenuBar();
      for (int i=0; i&amp;lt;3; i++) {
         JMenu menu = new JMenu(&amp;quot;JMenu &amp;quot; + (i+1));
         for (int j=0; j&amp;lt;3; j++) {
            JMenuItem item = new JMenuItem(&amp;quot;JMenuItem &amp;quot; + (j+1));
            menu.add(item);
         }
         menuBar.add(menu);
      }
      panel.add(BorderLayout.NORTH, menuBar);
 
      return panel;
   }
 
   public static void main(String []args) {
      Main main = new Main();
   }
}

Creating a JMenuItem with an image

Two constructors of JMenuItem take an Icon as parameters. Try the following example with these animated! GIFs:

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("menu");
      JMenuItem menuItem1 = new JMenuItem("male", new ImageIcon("male.gif"));
      JMenuItem menuItem2 = new JMenuItem("female", new ImageIcon("female.gif"));
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Adding a popup listener to a JTable row

Main.java:

import javax.swing.table.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   public Main() {
      super("TableModel Demonstration");
 
      // create our own custom TableModel
      WineTableModel wineModel = new WineTableModel();
      final JTable table = new JTable(wineModel);
 
      // add rows to our TableModel, each row is represented as a Wine object
      wineModel.addWine(new Wine("Chateau Meyney, St. Estephe", "1994", 18.75f, true));
      wineModel.addWine(new Wine("Chateau Montrose, St. Estephe", "1975", 54.25f, true));
      wineModel.addWine(new Wine("Chateau Gloria, St. Julien", "1993", 22.99f, false));
      wineModel.addWine(new Wine("Chateau Beychevelle, St. Julien", "1970", 61.63f, false));
      wineModel.addWine(new Wine("Chateau La Tour de Mons, Margeaux", "1975", 57.03f, true));
      wineModel.addWine(new Wine("Chateau Brane-Cantenac, Margeaux", "1978", 49.92f, false));
 
      // create the scroll pane and add the table to it. 
      JScrollPane scrollPane = new JScrollPane(table);
 
      // add the scroll pane to this window.
      getContentPane().add(scrollPane, BorderLayout.CENTER);
 
      final TablePopup tablePopup = new TablePopup(table);
      table.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent me) {
            int row = table.rowAtPoint(me.getPoint());
            System.out.println("You clicked at row " + row);
            // possibly use row variable here to do something specific with your popup menu
            if (me.isPopupTrigger()) {
               tablePopup.show(me.getComponent(), me.getX(), me.getY());
            }
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.pack();
      main.setVisible(true);
   }
}
 
// a simple object that holds data about a particular wine
class Wine {
   private String  name;
   private String  vintage;
   private float   price;
   private boolean inStock;
 
   public Wine(String name, String vintage, float price, boolean inStock) {
      this.name = name;
      this.vintage = vintage;
      this.price = price;
      this.inStock = inStock;
   }
 
   public String getName()     { return name; }
   public String getVintage()  { return vintage; }
   public float  getPrice()    { return price; } 
   public boolean getInStock() { return inStock; }
 
   public String toString() { 
      return "[" + name + ", " + vintage + ", " + price + ", " + inStock + "]"; }
}
 
class WineTableModel extends AbstractTableModel {
   // holds the strings to be displayed in the column headers of our table
   final String[] columnNames = {"Name", "Vintage", "Price", "In stock?"};
 
   // holds the data types for all our columns
   final Class[] columnClasses = {String.class, String.class, Float.class, Boolean.class};
 
   // holds our data
   final Vector data = new Vector();
  
   // adds a row
   public void addWine(Wine w) {
      data.addElement(w);
      fireTableRowsInserted(data.size()-1, data.size()-1);
   }
 
   public int getColumnCount() {
      return columnNames.length;
   }
         
   public int getRowCount() {
      return data.size();
   }
 
   public String getColumnName(int col) {
      return columnNames[col];
   }
 
   public Class getColumnClass(int c) {
      return columnClasses1;
   }
 
   public Object getValueAt(int row, int col) {
      Wine wine = (Wine) data.elementAt(row);
      if (col == 0)      return wine.getName();
      else if (col == 1) return wine.getVintage();
      else if (col == 2) return new Float(wine.getPrice());
      else if (col == 3) return new Boolean(wine.getInStock());
      else return null;
   }
 
   public boolean isCellEditable(int row, int col) {
      return false;
   }
}
 
class TablePopup extends JPopupMenu {
   public TablePopup(JTable tree) {
      JMenuItem itemEdit = new JMenuItem("Edit");
      JMenuItem itemDelete = new JMenuItem("Delete");
      itemEdit.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Edit child");
         }
      });
      itemDelete.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            System.out.println("Delete selected");
         }
      });
 
      add(itemEdit);
      add(new JSeparator());
      add(itemDelete);
   }
}

Adding a different tooltip for every element in my JMenuItem

Set the tooltip text for every JMenuItem.

Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("menu");
      JMenuItem menuItem1 = new JMenuItem("male");
      JMenuItem menuItem2 = new JMenuItem("female");
      menuItem1.setToolTipText("The weak sex");
      menuItem2.setToolTipText("The strong sex");
      menu.add(menuItem1);
      menu.add(menuItem2);
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Getting the JMenu object from the selected JMenuItem

Get the accessible parent from the accessibleContext.
Main.java:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame implements ActionListener {
   private JMenu menu1;
   private JMenu menu2;
 
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      menu1 = new JMenu("The weak sex");
      JMenuItem menuItem1 = new JMenuItem("male");
      menu2 = new JMenu("The strong sex");
      JMenuItem menuItem2 = new JMenuItem("female");
      menu1.add(menuItem1);
      menu2.add(menuItem2);
      menuBar.add(menu1);
      menuBar.add(menu2);
      menuItem1.addActionListener(this);
      menuItem2.addActionListener(this);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
 
   public void actionPerformed(ActionEvent ae) {
      JMenuItem menuItem = (JMenuItem) ae.getSource();
      JMenu menu = (JMenu) menuItem.getAccessibleContext().getAccessibleParent();
      System.out.println("Selected menu: " + menu.getText());
   }
 
   public static void main(String[] args) {
      (new Main()).show();
   }
}

Adding a general JComponent to a JMenu

Create your own version of the JComponent that you would like to add to your Menu and have it implement the methods of MenuElement. Here’s an example that shows a JMenu with a JTextField and a JSlider as its elements:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame {
   public Main() {
      getContentPane().setLayout(new FlowLayout());
 
      JMenuBar menuBar = new JMenuBar();
      JMenu menu = new JMenu("Menu");
      JMenuItem menuItem1 = new JMenuItem("item 1");
      JMenuItem menuItem2 = new JMenuItem("item 2");
      JMenuItemTextField menuItem3 = new JMenuItemTextField(20);
      JMenuItem menuItem4 = new JMenuItem("item 4");
      JMenuItemSlider menuItem5 = new JMenuItemSlider();
      menuItem5.setMajorTickSpacing(20);
      menuItem5.setMinorTickSpacing(5);
      menuItem5.setPaintTicks(true);
      JMenuItem menuItem6 = new JMenuItem("item 6");
 
      menu.add(menuItem1);
      menu.add(menuItem2);
      menu.add(menuItem3);
      menu.add(menuItem4);
      menu.add(menuItem5);
      menu.add(menuItem6);
 
      menuBar.add(menu);
 
      this.setJMenuBar(menuBar); 
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent event) {
            System.exit(0);   
         }      
      });
 
      setSize(400, 400);
   }
  
   public static void main(String[] args) {
      (new Main()).show();
   }
}
 
class JMenuItemTextField extends JTextField implements MenuElement
{
   public JMenuItemTextField(int length) {
      super(length);
   }
 
   public Component getComponent() {
      return this;
   }
 
   public MenuElement[] getSubElements() {
      return null;
   }
 
   public void menuSelectionChanged(boolean changed) {
   }
 
   public void processKeyEvent(KeyEvent kevt, MenuElement[] me, MenuSelectionManager msm) {
   }
 
   public void processMouseEvent(MouseEvent mevt, MenuElement[] me, MenuSelectionManager msm) {
   }
}
 
class JMenuItemSlider extends JSlider implements MenuElement
{
   public JMenuItemSlider() {
      super();
   }
 
   public Component getComponent() {
      return this;
   }
 
   public MenuElement[] getSubElements() {
      return null;
   }
 
   public void menuSelectionChanged(boolean changed) {
   }
 
   public void processKeyEvent(KeyEvent kevt, MenuElement[] me, MenuSelectionManager msm) {
   }
 
   public void processMouseEvent(MouseEvent mevt, MenuElement[] me, MenuSelectionManager msm) {
   }
}

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