set Popup Menu for JTable - Java Swing

Java examples for Swing:JTable

Description

set Popup Menu for JTable

Demo Code

/*//from w  w w .  j av  a  2 s .  c  o m
(C) 2007 Stefan Reich (jazz@drjava.de)
This source file is part of Project Prophecy.
For up-to-date information, see http://www.drjava.de/prophecy

This source file is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation, version 2.1.
 */
import javax.swing.*;
import javax.swing.event.AncestorListener;
import javax.swing.event.AncestorEvent;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.*;

public class Main{
    public static void setPopupMenu(final JTable table,
            final PopupMenuFactory factory) {
        table.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                mouseReleased(e);
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = table.rowAtPoint(e.getPoint());
                    if (!table.isRowSelected(row))
                        table.setRowSelectionInterval(row, row);

                    JPopupMenu popup = factory.createPopupMenu();
                    if (popup != null)
                        popup.show(e.getComponent(), e.getX() + 2, e.getY());
                }
            }
        });
    }
    public static void setPopupMenu(final JList list,
            final PopupMenuFactory factory) {
        list.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                mouseReleased(e);
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    int row = list.locationToIndex(e.getPoint());
                    if (!list.isSelectedIndex(row))
                        list.setSelectedIndex(row);

                    JPopupMenu popup = factory.createPopupMenu();
                    if (popup != null)
                        popup.show(e.getComponent(), e.getX() + 2, e.getY());
                }
            }
        });
    }
    public static void setPopupMenu(final JComponent c,
            final PopupMenuFactory factory) {
        c.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                mouseReleased(e);
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    JPopupMenu popup = factory.createPopupMenu();
                    if (popup != null)
                        popup.show(e.getComponent(), e.getX() + 2, e.getY());
                }
            }
        });
    }
}

Related Tutorials