package editor.gui.generic;

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

import javax.swing.JPopupMenu;
import javax.swing.JTable;

/**
 * This class represents a listener for mouse events on a table and opens up
 * a pop-up menu when the appropriate button is clicked.
 * <p>
 * TODO: Try to make right clicking have all the features of left clicking.
 * Currently you can select single rows (or add the single row to the selection by
 * holding ctrl) with the right button, but you can't extend a selection (with shift)
 * or drag it using the right mouse button
 * TODO: This does weird things with DnD
 *
 * @author Alec Roelke
 */
public class TableMouseAdapter extends MouseAdapter
{
    /**
     * The menu that will open on right-click.
     */
    private JPopupMenu menu;
    /**
     * The JTable this TableMouseAdapter operates on.
     */
    private JTable table;

    /**
     * Create a new TableMouseAdapter.
     *
     * @param t table to operate on
     * @param m menu to open
     */
    public TableMouseAdapter(JTable t, JPopupMenu m)
    {
        super();

        table = t;
        menu = m;
    }

    @Override
    public void mousePressed(MouseEvent e)
    {
        popupClick(e);
    }

    /**
     * {@inheritDoc}
     * In addition to the pop-up menu, clear the table if the mouse button is released off of it.
     */
    @Override
    public void mouseReleased(MouseEvent e)
    {
        popupClick(e);
        if (table.rowAtPoint(e.getPoint()) < 0)
            table.clearSelection();
    }

    /**
     * If the event that generated the click was a pop-up event (usually
     * right-click), open the menu.  If the mouse is over an empty row,
     * then select that row first.  If the ctrl key is not held down,
     * deselect all other rows.
     *
     * @param e #MouseEvent corresponding to the click
     */
    public void popupClick(MouseEvent e)
    {
        if (e.isPopupTrigger())
        {
            int r = table.rowAtPoint(e.getPoint());
            if (r >= 0 && !table.isRowSelected(r))
            {
                if ((e.getModifiersEx()&InputEvent.CTRL_DOWN_MASK) == 0)
                    table.setRowSelectionInterval(r, r);
                else
                    table.addRowSelectionInterval(r, r);
            }
            menu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
}

@@ -328,344 +328,8 @@
 ed.%0A
- * %3Cp%3E%0A * TODO: Try to make right clicking have all the features of left clicking.%0A * Currently you can select single rows (or add the single row to the selection by%0A * holding ctrl) with the right button, but you can't extend a selection (with shift)%0A * or drag it using the right mouse button%0A * TODO: This does weird things with DnD%0A
  *%0A 

Move bug to GitHub issue