Adds the supplied popupMenu to the JTable as a right click menu. - Java Swing

Java examples for Swing:JTable

Description

Adds the supplied popupMenu to the JTable as a right click menu.

Demo Code


//package com.java2s;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPopupMenu;
import javax.swing.JTable;

public class Main {
    /**/*w w w .  ja  v  a 2s. c  om*/
     * Adds the supplied popupMenu to the table as a right click menu. Also 
     * ensures that when right clicking the table, the correct table row is
     * highlighted and selected. If the user right clicks into an empty area of
     * the table, then no popup-menu is shown. 
     * 
     * The code has been inspired from:
     * http://stackoverflow.com/questions/3558293/java-swing-jtable-right-click-menu-how-do-i-get-it-to-select-aka-highlight-t
     * 
     * @param table What table to attach the popup menu to.
     * @param popupMenu What popup menu to attach to the table.
     */
    public static void setupPopupMenu(final JTable table,
            final JPopupMenu popupMenu) {
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseReleased(MouseEvent e) {
                if (e.getButton() == MouseEvent.BUTTON3) {
                    int r = table.rowAtPoint(e.getPoint());
                    if (r >= 0 && r < table.getRowCount()) {
                        table.setRowSelectionInterval(r, r);
                        popupMenu.show(table, e.getX(), e.getY());
                    } else {
                        table.clearSelection();
                    }
                }
            }
        });
    }
}

Related Tutorials