How to add a JPopupMenu to a JTable

Here's an example of how to add a JPopupMenu to a JTable. The purpose of the popup menu is to let the user right-click on contents in the table and work directly with those contents.

In the code below I've taken a real class and trimmed it down considerably for these demo purposes. I hope the code remaining is useful enough to help you implement your own JPopupMenu on a JTable, or perhaps in other components as well.

package com.devdaily.mywidget.view;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class MyWidgetTablePanel extends JPanel {
  BorderLayout borderLayout1 = new BorderLayout();
  JScrollPane MyWidgetTableScrollPane = new JScrollPane();
  MyWidgetController controller;
  MyWidgetTableModel MyWidgetTableModel;
  JPopupMenu popupMenu = new JPopupMenu();

  private static String INSERT_CMD = "Insert Rows";
  private static String DELETE_CMD = "Delete Rows";

  JTable MyWidgetTable = new JTable();

  public MyWidgetTablePanel(MyWidgetController controller, 
                            MyWidgetTableModel MyWidgetTableModel) {
    this.controller = controller;
    this.MyWidgetTableModel = MyWidgetTableModel;
    MyWidgetTable.setModel(MyWidgetTableModel);

    this.setLayout(borderLayout1);
    this.add(MyWidgetTableScrollPane, BorderLayout.CENTER);
    MyWidgetTableScrollPane.getViewport().add(MyWidgetTable, null);

    JMenuItem menuItem = new JMenuItem(INSERT_CMD);
    menuItem.addActionListener(new InsertRowsActionAdapter(this));
    popupMenu.add(menuItem);

    MouseListener popupListener = new PopupListener();
    MyWidgetTable.addMouseListener(popupListener);
  }

  class PopupListener extends MouseAdapter {
    public void mousePressed(MouseEvent e) {
      showPopup(e);
    }
    public void mouseReleased(MouseEvent e) {
      showPopup(e);
    }
    private void showPopup(MouseEvent e) {
      if (e.isPopupTrigger()) {
        popupMenu.show(e.getComponent(), e.getX(), e.getY());
      }
    }
  }

  void insertRowsctionPerformed(ActionEvent e) {
    int row = MyWidgetTable.getSelectedRow();
    controller.doInsertPagesAction(row);
  }
  
} // end of class


class InsertRowsActionAdapter implements ActionListener {
  MyWidgetTablePanel adaptee;

  InsertRowsActionAdapter(MyWidgetTablePanel adaptee) {
    this.adaptee = adaptee;
  }
  public void actionPerformed(ActionEvent e) {
    adaptee.insertRowsActionPerformed(e);
  }
}