This is a quick post to show how developer can intercept Right mouse click in JTable. Name of our JTable object is "jTable". We need to add MouseListener and catch "MousePressed" events. As the code shows correct mouse button is determined using "SwingUtilities" class, quite easy job. Tricky part is finding Row number and Column number and displaying Pop-up window at correct position.
Enjoy!
Enjoy!
jTable.addMouseListener( new MouseAdapter()
{
public void mousePressed( MouseEvent event )
{
if ( SwingUtilities.isLeftMouseButton( event ) ) {
// Do something
} else if ( SwingUtilities.isRightMouseButton( event ) ) {
Point p = event.getPoint();
// Get row and column index that contains our coordinate
int rowIndex = jTable.rowAtPoint( p );
int colIndex = jTable.columnAtPoint( p );
// Get ListSelectionModel of the JTable
ListSelectionModel model = jTable.getSelectionModel();
// Set how many rows are selected using "rowIndex".
// If beginning and end selection indexes are equal then
// only one row is selected.
model.setSelectionInterval( rowIndex, rowIndex );
}
// Show popup
if (event.isPopupTrigger() && event.getComponent() instanceof JTable ) {
JPopupMenu popup = createMyPopUp();
popup.show(event.getComponent(), event.getX(), event.getY());
}
}
});
Comments