import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TableExample extends JFrame implements MouseListener { private JTable table; public TableExample() { setTitle("JTable Example"); setDefaultCloseOperation(EXIT_ON_CLOSE); String[] columnNames = {"Name", "Age", "Gender"}; Object[][] data = { {"John", 25, "Male"}, {"Mary", 30, "Female"}, {"Tom", 40, "Male"}, {"Linda", 20, "Female"}, {"Mike", 35, "Male"} }; table = new JTable(data, columnNames); table.addMouseListener(this); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane); pack(); setVisible(true); } public void mouseClicked(MouseEvent e) { int[] selectedRows = table.getSelectedRows(); System.out.println("Selected Rows: "); for (int i = 0; i < selectedRows.length; i++) { System.out.println(selectedRows[i]); } } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public static void main(String[] args) { new TableExample(); } }
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TableExample2 extends JFrame implements ActionListener { private JTable table; private JButton button; public TableExample2() { setTitle("JTable Example"); setDefaultCloseOperation(EXIT_ON_CLOSE); String[] columnNames = {"Name", "Age", "Gender"}; Object[][] data = { {"John", 25, "Male"}, {"Mary", 30, "Female"}, {"Tom", 40, "Male"}, {"Linda", 20, "Female"}, {"Mike", 35, "Male"}, {"Lisa", 28, "Female"}, {"Bob", 45, "Male"}, {"Susan", 22, "Female"}, {"Bill", 32, "Male"}, {"Jane", 27, "Female"} }; table = new JTable(data, columnNames); button = new JButton("Get Selected Rows"); button.addActionListener(this); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); pack(); setVisible(true); } public void actionPerformed(ActionEvent e) { int[] selectedRows = table.getSelectedRows(); JOptionPane.showMessageDialog(this, "Number of Selected Rows: " + selectedRows.length); } public static void main(String[] args) { new TableExample2(); } }The javax.swing package library is used in both examples.