I have written a program, which displays a table inside of a JScrollPane. The reason for this is that, if the table gets to long the user should be able to use the scrollbar. Further I want the user to be able to open a popup menu on right click to edit or delete data. At first I thought my implementation works as shown in this image:
Later I realized that if I use the scollbar something gets wrong with the mouseposition and the popup is at the wrong location as shown here:
The mouse is located at the highlighted entry.
Here is my code for this:
table.addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()){
rightClickPopUpOnTable(tablePanel.getComponentAt(e.getX(), e.getY()), e.getX(), e.getY());
//rightClickPopUpOnTable(tablePanel.getComponentAt(e.getXOnScreen(), e.getYOnScreen()), e.getXOnScreen(), e.getYOnScreen());
}
}
@Override
public void mouseReleased(MouseEvent e) {
int r = table.rowAtPoint(e.getPoint());
if (r >= 0 && r < table.getRowCount()) {
table.setRowSelectionInterval(r, r);
} else {
table.clearSelection();
}
if (e.isPopupTrigger()){
rightClickPopUpOnTable(tablePanel.getComponentAt(e.getX(), e.getY()), e.getX(), e.getY());
//rightClickPopUpOnTable(tablePanel.getComponentAt(e.getXOnScreen(), e.getYOnScreen()), e.getXOnScreen(), e.getYOnScreen());
}
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
public void rightClickPopUpOnTable(Component component, int x, int y){
JPopupMenu pop = new JPopupMenu();
pop.setVisible(true);
pop.setFocusable(false);
JMenuItem item = new JMenuItem("Edit");
item.addActionListener(new ActionListener() {
@java.lang.Override
public void actionPerformed(ActionEvent e) {
handler.getData().showData(table.getValueAt(table.getSelectedRow(),0).toString());
}
});
JMenuItem item2 = new JMenuItem("Delete");
item2.addActionListener(new ActionListener() {
@java.lang.Override
public void actionPerformed(ActionEvent e) {
int dialogResult = JOptionPane.showConfirmDialog (null, "Are you sure you want to delete "+table.getValueAt(table.getSelectedRow(), 0).toString()+"?","Delete Confirmation",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
//DO STUFF
}
}
});
pop.add(item);
pop.add(item2);
pop.show(component, x, y);
}
I found a way to "fix" the problem partially by using e.getXOnScreen() as you can see in the code . Now the popup is displayed at the right location, but it won't highlight the items anymore AND it wont close as shown here:
I would be nice if someone knowns a solution for this.