I have a JTable in a GUI and I want to return a number based on the value of the cell that a user clicks on. This is the code:
ListSelectionModel newmodel = mytable.getSelectionModel();
newmodel.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
int row = mytable.getSelectedRow();
int column = mytable.getSelectedColumn();
int cell = getNewNum();
datefield.setText(String.valueOf(cell));
}
});
I have a couple of problems with this. Firstly this method makes my table editable. Before I used this method I couldn’t edit the table but now I can delete entries. I looked in the API but I don’t know why this is. Secondly, if I click on a cell in row 3, say, and then I click on another row in cell 3, no event is registered. How can I make an event from clicking in a cell on the currently selected row?
A common method is to get the point where the user clicked through the event:
Here is a second option using selection mode:
If you go:
Then your JTable will not be editable.
Finally in order to get the value you want, you just need to call the
getValueAt(row,col)of your JTable Model, or get the contents like this: