Here is how to set up a double-click event that opens a new form:
1) First set up Mouse Listener on your JTable:
myJTable.addMouseListener(new MouseAdapter() {This will give you the row and column that was double clicked.
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
// do some action
}
}
});
2) You can then use this to get the value of that row's ID and open a new form and populate it with this record's data. Here is how you would open a new form
JFrame newFrame = new JFrame();The below link was useful in working out how to do this and has many other helpful items:
newFrame.setTitle("Detail Screen");
newFrame.setVisible(true);
Detect Double Click

7 comments:
Just a suggestion; you might want to use the ContextMenu / right click instead. The right click is the norm for desktop / fat clients; double click is the norm for web apps.
To do this, your mouseListener should implement both mousePressed and mouseReleased, and then just show a popupMenu. you can add menus, actions etc to your popup menu, and dynamically change text / actions according to the content of the cell etc.
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(table, e.getX(), e.getY());
}
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
popupMenu.show(table, e.getX(), e.getY());
}
}
Thanks for the tip. How do you implement a double or single right-click?
Note that your code will not work if a cell is editable, because the MouseEvent will be catched by CellEditor listener to start editing.
Thanks for the note. I haven't had the use of an editable cell table, but this is good to know for the future.
"The right click is the norm for desktop / fat clients; double click is the norm for web apps."
Strange, I've never heard about that "norm" before. Where did you see that? Double-click on lists have been common practice for years in fat clients. It's present in both Windows and Linux (Gnome, KDE), in many applications of several kinds.
Dude, you saved my day.
Glad I could help Crispin.
Post a Comment