[ Java jtable allow row selection ]
I am trying to make a jtable which displays a list of users. The table should allow users to select an entire row but not allow editing of the cells.
So far i have this, it stops them from editing cells but how to i allow them to select the rows instead of cells?
DefaultTableModel userTableModel = new DefaultTableModel(new Object[]{"Customer ID", "First Name", "Last Name"}, 0) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
And this i show i am populating the table:
public void refreshCustomersList() throws SQLException, ClassNotFoundException {
UserBeanList userList = dbConnector.getUserData();
for (int i = 0; i < userList.size(); i++) {
UserBean userBean = userList.getUserBeanAt(i);
String[] data = new String[3];
data[0] = userBean.getCustomerID();
data[1] = userBean.getFirstName();
data[2] = userBean.getLastName();
userTableModel.addRow(data);
}
tableCustomers.setModel(userTableModel);
}
As i said i have disabled cell editing but how do i only allow row selection.
I have seen posts from other people saying i should put this but i not sure were to put it.
selectionTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Any help would be great.
Answer 1
Have you tried setRowSelectionAllowed(true)
on your JTable instance?
I would suggest trying to look at the javadocs http://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html#setRowSelectionAllowed(boolean)
and read the tutorial linked from the javadocs: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
They are pretty thorough :)
Answer 2
private void jTable1MousePressed(java.awt.event.MouseEvent evt) {
int selectedRow;
ListSelectionModel rowSM = jTable1.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener()
{
@Override
public void valueChanged(ListSelectionEvent e)
{
ListSelectionModel lsm = (ListSelectionModel) e.getSource();
selectedRow = lsm.getMinSelectionIndex();
int numCols = jTable1.getColumnCount();
model = (DefaultTableModel) jTable1.getModel();
System.out.print(" \n row " + selectedRow + ":");
for (int j = 0; j < numCols; j++)
{
System.out.print(" " + model.getValueAt(selectedRow, j));
}
}
});
}
Using this you can get value of whole row where u click on particular row.