Java jtable popup menu example

Here's an example of how to add a popup menu to a JTable in Java:

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class TablePopupMenuExample extends JFrame {

    public TablePopupMenuExample() {
        super("Table Popup Menu Example");

        // Create the table
        Object[][] data = {
                {"John Doe", "25", "Male"},
                {"Jane Smith", "30", "Female"},
                {"Bob Johnson", "40", "Male"}
        };
        String[] columnNames = {"Name", "Age", "Gender"};
        JTable table = new JTable(data, columnNames);

        // Create the popup menu
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem deleteItem = new JMenuItem("Delete");
        deleteItem.addActionListener(e -> {
            int selectedRow = table.getSelectedRow();
            if (selectedRow != -1) {
                ((javax.swing.table.DefaultTableModel) table.getModel()).removeRow(selectedRow);
            }
        });
        popupMenu.add(deleteItem);

        // Add the popup menu listener to the table
        table.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                showPopupMenu(e);
            }

            public void mouseReleased(MouseEvent e) {
                showPopupMenu(e);
            }

            private void showPopupMenu(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    popupMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });

        // Add the table to a scroll pane
        JScrollPane scrollPane = new JScrollPane(table);
        JPanel panel = new JPanel();
        panel.add(scrollPane);
        add(panel);

        // Set the size, location and visibility of the frame
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new TablePopupMenuExample();
    }
}
Source‮‬:www.theitroad.com

In this example, we create a JTable and add it to a JScrollPane and JPanel. We then create a JPopupMenu with a single JMenuItem that removes the selected row from the table when clicked.

We add a MouseListener to the table that shows the popup menu when the right mouse button is pressed or released using the isPopupTrigger() method. The show() method of the JPopupMenu is used to display the popup menu at the current mouse location.

When you run this example and right-click on a row in the JTable, a popup menu will appear with a "Delete" option. Clicking on this option will remove the selected row from the JTable.