Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we detect the double click events of a JTable row in Java?
A JTable is a subclass of JComponent for displaying complex data structures. A JTable can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. We can detect the double click events of a JTable by using a MouseAdapter class or MouseListener interface. We can set the getClickCount() value to '2' of a MouseEvent class for detecting the double click events of a JTable.
Example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public final class DoublClickJTableRowTest extends JFrame {
private JTable table;
private JScrollPane scrollPane;
public DoublClickJTableRowTest() {
setTitle("DoublClickJTableRow Test");
String[] columnNames = {"First Name", "Last Name"};
Object[][] data = {{"Raja", "Ramesh"}, {"Adithya", "Sai"}, {"Vineet", "Kumar"}, {"Krishna", "Kasyap"}};
table = new JTable(data, columnNames) {
public boolean editCellAt(int row, int column, java.util.EventObject e) {
return false;
}
};
table.setFocusable(false);
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if (me.getClickCount() == 2) { // to detect doble click events
JTable target = (JTable)me.getSource();
int row = target.getSelectedRow(); // select a row
int column = target.getSelectedColumn(); // select a column
JOptionPane.showMessageDialog(null, table.getValueAt(row, column)); // get the value of a row and column.
}
}
});
scrollPane= new JScrollPane(table);
add(scrollPane);
setSize(375, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new DoublClickJTableRowTest();
}
}
Output
Advertisements