import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Example1 extends JFrame implements ActionListener { private JTable table; private JButton button; public Example1() { String[] columnNames = {"Name", "Age", "Gender"}; Object[][] data = { {"Alice", 20, "F"}, {"Bob", 23, "M"}, {"Charlie", 25, "M"} }; table = new JTable(data, columnNames); button = new JButton("Get Selected Rows Count"); button.addActionListener(this); add(table, BorderLayout.CENTER); add(button, BorderLayout.SOUTH); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e) { int count = table.getSelectedRowCount(); JOptionPane.showMessageDialog(this, "Selected Rows Count: " + count); } public static void main(String[] args) { new Example1(); } }
import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.*; public class Example2 extends JFrame implements ListSelectionListener { private JTable table; public Example2() { String[] columnNames = {"Name", "Age", "Gender"}; Object[][] data = { {"Alice", 20, "F"}, {"Bob", 23, "M"}, {"Charlie", 25, "M"} }; table = new JTable(data, columnNames); table.getSelectionModel().addListSelectionListener(this); add(new JScrollPane(table), BorderLayout.CENTER); pack(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void valueChanged(ListSelectionEvent e) { int count = table.getSelectedRowCount(); System.out.println("Selected Rows Count: " + count); } public static void main(String[] args) { new Example2(); } }In this example, a JTable is created with the same data as in Example 1. However, instead of a button, a ListSelectionListener is added to the JTable to receive events when cells are selected. The valueChanged() method is called whenever a cell is selected, and it prints the number of selected rows to the console using the getSelectedRowCount() method.