I am trying to get a JPopUpMenu show when a user right clicks on my JTable. In my class which extends JTable, I call the following code:
addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
rowClicked = rowAtPoint(e.getPoint());
colClicked = columnAtPoint(e.getPoint());
if (e.isPopupTrigger())
{
popUpMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mouseClicked(MouseEvent e)
{
rowClicked = rowAtPoint(e.getPoint());
colClicked = columnAtPoint(e.getPoint());
if(e.isPopupTrigger())
{
popUpMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
Whenever I right click on the track pad, with a mouse, or using ctrl + right click, if(e.isPopupTrigger())
never evaluates to true and the menu is never shown. I have break points in there to verify.
I have done some research online, and it seems like this solution should work. Since right clicks are platform dependent, using isPopupTrigger() should be the way to go.
Is there something special that is going on since I am on a mac?
This simple example works for me, perhaps it will help you locate your issue. I'm on a Mac, using Java 7.
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
String columnNames[] = { "Column 1", "Column 2", "Column 3" };
String dataValues[][] = { { "12", "234", "67" }, { "-123", "43", "853" }, { "93", "89.2", "109" }, { "279", "9033", "3092" } };
JTable table = new JTable(dataValues, columnNames);
panel.add(table);
final JPopupMenu menu = new JPopupMenu();
JMenuItem item = new JMenuItem("item");
menu.add(item);
table.setComponentPopupMenu(menu);
table.addMouseListener(new MouseAdapter()
{
@Override
public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
{
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
@Override
public void mouseClicked(MouseEvent e)
{
if (e.isPopupTrigger())
{
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
});
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With