使用鼠标右键单击打开弹出菜单.
老方法是使用鼠标侦听器来显示弹出窗口.
较新的方法是使用setComponentPopup(...)
方法:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class TableRightClick extends JPanel implements ActionListener
{
JPopupMenu popup;
public TableRightClick()
{
popup = new JPopupMenu();
JMenuItem menuItem = new JMenuItem("Click Me");
menuItem.addActionListener( this );
popup.add( menuItem );
JTable table = new JTable(10, 5);
table.setComponentPopupMenu( popup );
popup.addPopupMenuListener(new PopupMenuListener()
{
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
SwingUtilities.invokeLater(() ->
{
Point point = SwingUtilities.convertPoint(popup, new Point(0, 0), table);
int currentRow = table.rowAtPoint(point);
int currentColumn = table.columnAtPoint(point);
table.changeSelection(currentRow, currentColumn, false, false);
});
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
@Override
public void popupMenuCanceled(PopupMenuEvent e) {}
});
/*
// When using a MouseListener to show popup menu
table.addMouseListener( new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
{
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint( e.getPoint() );
int column = source.columnAtPoint( e.getPoint() );
source.changeSelection(row, column, false, false);
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
});
*/
table.setPreferredScrollableViewportSize(table.getPreferredSize());
add( new JScrollPane(table) );
}
public void actionPerformed(ActionEvent e)
{
Component c = (Component)e.getSource();
JPopupMenu popup = (JPopupMenu)c.getParent();
JTable table = (JTable)popup.getInvoker();
System.out.println(table.getSelectedRow() + " : " + table.getSelectedColumn());
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Table Right Click");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TableRightClick());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}