I have the following sample Java Swing JTable app:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class JTableListSelectionListener
{
public static void main(String[] a)
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTable table;
String[] columnTitles={"A","B","C","D"};
Object[][] rowData={{"11","12","13","14"},{"21","22","23","24"},{"31","32","33","34"},{"41","42","43","44"}};
table=new JTable(rowData,columnTitles);
table.setCellSelectionEnabled(true);
ListSelectionModel cellSelectionModel=table.getSelectionModel();
cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cellSelectionModel.addListSelectionListener(new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
String selectedData=null;
int[] selectedRow=table.getSelectedRows();
int[] selectedColumns=table.getSelectedColumns();
for (int i=0;i<selectedRow.length;i++)
for (int j=0;j<selectedColumns.length;j++)
selectedData=(String)table.getValueAt(selectedRow[i],selectedColumns[j]);
System.out.println("Selected: "+selectedData);
}
});
frame.add(new JScrollPane(table));
frame.setLocationRelativeTo(null);
frame.setSize(300,200);
frame.setVisible(true);
}
}
It won't respond if I click on the same row:
If I click on "12" then on "13" or first click on "21" then click on "23", why?
How to fix it so no matter where I click in whichever order, it will always output the value in that cell?
How to be able to tell if I have clicked with the left mouse button or the right mouse button?
The problem is, the
ListSelectionModelfor theJTablemanagers the row selection only, from the JavaDocsThis means that of the row selection doesn't change, you won't get a notification.
Instead, you probably want to use the
ListSelectionModelused by theTableColumnModel, for example...