Dispatch new Event

Hi everyone.

I'm building an application that has a JTable inside a JScrollPane. Usually when you click the table with the left mouse button it selects the row (in my case). I also have a popup menu that shows up when the right button of the mouse is clicked. Well, this popup menu has to retrieve information from the selected row. The problem is that the row isn't selected. This is my problem: i the row to be selected when i click the right mouse button.

This is the code I'm using:

jTable1.addMouseListener(new java.awt.event.MouseAdapter(){// Setting up the listener

publicvoid mouseClicked(java.awt.event.MouseEvent evt){

jTable1MouseClicked(evt);

}

});

....

privatevoid jTable1MouseClicked(java.awt.event.MouseEvent evt){

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

jTable1.dispatchEvent(new MouseEvent(jTable1,

evt.getID(),

evt.getWhen(),

MouseEvent.BUTTON1_MASK,

evt.getPoint().x,

evt.getPoint().y,

evt.getClickCount(),

evt.isPopupTrigger(),

MouseEvent.BUTTON1));

}

}

As you can see I'm trying to "emulate" a click of the left mouse button and just let the table handle it. But it isn't happening.

Every suggestion will be welcomed.

Thank you.

JCruz

[1797 byte] By [JCruza] at [2007-10-3 10:31:56]
# 1
How about you just save the last selected row and when you have a right click you know the last row that was selected?
zadoka at 2007-7-15 5:54:50 > top of Java-index,Security,Event Handling...
# 2

I hadn't think about that but that's not exactly what i want to do. Let me see if i can explain it: for instance, if you click one of your desktop icons it will show a popup menu with several things and, at the same time, select that shortcut.

That's what I want to achieve: when I click the right button mouse in my table I want the row selected and the popup displayed.

Thank you

JCruza at 2007-7-15 5:54:50 > top of Java-index,Security,Event Handling...
# 3

Rather than dispatching a left click event, you can pull the coordinates of the MouseEvent via getPoint(), then do a lookup on the appropriate row/column using the JTable rowAtPoint and columnAtPoint methods. Then call the JTable changeSelection method to set the selected row to wherever you right clicked:

private void jTable1MouseClicked(java.awt.event.MouseEvent evt){

/*

Code

*/

int row = jTable1.rowAtPoint(evt.getPoint());

int col = jTable1.columnAtPoint(evt.getPoint());

jTable1.changeSelection(row, col, false, false);//See JTable javadoc for what the false, false means

/*

Code

*/

}

MatthewJMurraya at 2007-7-15 5:54:50 > top of Java-index,Security,Event Handling...
# 4
Thank you guys for all your help and suggestions, especially to Matthew:it worked perfectly.
JCruza at 2007-7-15 5:54:50 > top of Java-index,Security,Event Handling...