JTable, JPopupMenu and Mouse event

I am trying to add a JPopupMenu to a JTable. When the user right clicks on a row in the table I want the PopupMenu to be visible and at the same time I'd like to capture the row associated with the click. I am using this code to add the popup to the mouseListener:

baseTable.addMouseListener(new java.awt.event.MouseAdapter() {

public void mouseClicked(java.awt.event.MouseEvent e) {

if(e.getButton()==MouseEvent.BUTTON3){

JMenuItem menuItem;

System.out.println(" row " + baseTable.getSelectedRow()+ " was clicked");

JPopupMenu popup = new JPopupMenu();

menuItem = new JMenuItem("Item 1");

//menuItem.addActionListener(this);

popup.add(menuItem);

menuItem = new JMenuItem("Item2");

//menuItem.addActionListener(this);

popup.add(menuItem);

menuItem = new JMenuItem("Item3");

//menuItem.addActionListener(this);

popup.add(menuItem);

int coordx = e.getX();

int coordy = e.getY();

popup.show(baseTable,coordx,coordy);

}

}

});

The problem with this is that the table has to first get focused before the popupmenu is shown and also before the row count is captured.

Any ideas how I can solve this?

Carlos

[1257 byte] By [charlie_42a] at [2007-10-2 10:14:28]
# 1

I use

// Listen to popup events and show the edit menu

// for the selected path

table.addMouseListener(new AbstractPopupMouseAdapter()

{

public void processPopup(MouseEvent mouseEvent)

{

JTable table = (JTable)mouseEvent.getComponent();

int popupRow = table.rowAtPoint(mouseEvent.getPoint());

table.getSelectionModel().setSelectionInterval(popupRow, popupRow);

mediator_.handlePlaylistPopupTrigger(table, popupRow, mouseEvent.getX(), mouseEvent.getY());

}

});

where AbstractPopupMouseAdapter is

import java.awt.event.*;

import javax.swing.*;

abstract public class AbstractPopupMouseAdapter extends MouseAdapter

{

final public void mousePressed(MouseEvent mouseEvent)

{

handleEvent(mouseEvent);

}

final public void mouseReleased(MouseEvent mouseEvent)

{

handleEvent(mouseEvent);

}

final public void mouseClicked(MouseEvent mouseEvent)

{

handleEvent(mouseEvent);

}

private void handleEvent(MouseEvent mouseEvent)

{

if (mouseEvent.isPopupTrigger())

{

processPopup(mouseEvent);

}

}

abstract public void processPopup(MouseEvent mouseEvent);

}

sabre150a at 2007-7-13 1:38:06 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks sabre150. It works fine.carlos
charlie_42a at 2007-7-13 1:38:06 > top of Java-index,Desktop,Core GUI APIs...