I have a static JPopupMenu
which I create and assign keybindings to using:
JMenuItem mItem = new MenuItem( "name" );
mItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_W, ActionEvent.CTRL_MASK ) );
This JPopupMenu
is added to a JTable
by doing the following:
JTable table = new JTable();
table.add( popupMenu );
I also add a MouseListener
to the JTable
as well to trigger the popup menu:
table.addMouseListener( mListener );
I override mouseReleased( MouseEvent me )
to add the action for displaying the popup menu in the following way:
private void checkPopupTrigger( MouseEvent me )
{
if ( me.isPopupTrigger() )
{
JTable source = (JTable)me.getSource();
int row = source.rowAtPoint( me.getPoint() );
int column = source.columnAtPoint( me.getPoint() );
if (! source.isRowSelected(row))
source.changeSelection(row, column, false, false);
popupMenu.show( me.getComponent(), me.getX(), me.getY() );
}
}
The problem I have is that upon first load the shortcut will work fine, it will work without the JPopupMenu open & therefore no need to right click and display the menu if you already know the shortcut you want to press. If I right click and the popup menu gets displayed the shotcut will no longer work once the popupmenu isn't visible.
If I inspect my JTable
instance ( in Eclipse IDE ) it actually appears that the JPopupMenu
component gets removed from the table after the following line is called :
popupMenu.show( me.getComponent(), me.getX(), me.getY() );
Is there a reason for this behaviour? I can't seem to find out what's going on after various different approaches. I have also tried using:
table.setComponentPopupMenu(myPopupMenu);
But by doing the above, although the menu will display the shortcuts never work unless the popupmenu is visible.
I am running on Windows 8 if that might be of any relevance to the key bindings getting assigned.
Any help is greatly appreciated, I did have this working using a separate KeyListener
on the JTable
as well as the JPopupMenu
, but that meant assigning all the shortcuts twice, once on the popup and again for the separate KeyListener
. After getting it to work with just the JPopupMenu
I now hope to be able to find out why the shortcuts only work before ( and during ) the menu being displayed. Even if I don't click on an item in the popup menu the shortcuts will not work after the menu has become hidden.
Thank you.