Reputation: 11
I am a new, terribly green user of Swing. I managed to create a table class using examples from java.sun tutorials, and I managed to load data dynamically into it. I want to be able to react to a click on a row by displaying a dialog box. How do I add the event Handler that will identify the selected row number?
The main function code:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
createAndShowGUI();
//...
}
}
}
}
and
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Data Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up data of the content pane.
TableClass mainTable = new TableClass(fh.getColNames(), fh.getTableContent());
mainTable.setOpaque(true);
frame.setContentPane(mainTable);
//Display the window.
frame.pack();
frame.setVisible(true);
}
Thank you
Upvotes: 1
Views: 1560
Reputation: 253
A couple of points.
The answer from Bozhidar Batsov is correct. However, you may not necessarily have a reference to the table (if for example your mouse listener is in another class or something). Point is, the table can be found from the MouseEvent's getSource() method. You can safely cast it to a JTable.
Also, table.getSelectedRow() may return a -1 if no row has actually been selected on the table yet. That would happen if the user, for example, clicks in the "whitespace" of the table (the area outside of the grid, but still in the text area). Just be sure to test for a -1 in your code.
Upvotes: 1
Reputation: 56595
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1) {
int selectedRowIndex = table.getSelectedRow();
//show your dialog with the selected row's contents
}
}
});
Upvotes: 5