checking if a cell in JTable is selected
Code:
public void valueChanged(ListSelectionEvent e) {
barcodeTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 1).toString());
nameTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 2).toString());
costTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 3).toString());
searchResults.clearSelection();
}
i have this bit of code here that obviously takes some values from a JTable and puts them into some text fields then clears the selection of
the JTable. the only problem with this is when i do a new search it runs this code because it takes the new search as a valuechange so i
either need a way to stop the searches from being a valuechange or a way to detect if a cell is selected so the code only runs when one is because at the moment i it works but i get a null pointer exception which is completely right cos it still runs when nothing is selected. any help would be appricated.
thank you
Re: checking if a cell in JTable is selected
I managed to get it sorted if anyone got same problem i used
Code:
try {
int rowcheck = searchResults.getSelectedRow();
if (rowcheck > -1) {
idTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 0).toString());
barcodeTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 1).toString());
nameTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 2).toString());
costTF.setText(searchResults.getValueAt(searchResults.getSelectedRow(), 3).toString());
searchResults.clearSelection();
}
} catch (NullPointerException ex) {
}
Re: checking if a cell in JTable is selected
Quote:
Originally Posted by
Dcalladi
I managed to get it sorted if anyone got same problem i used
Code:
try {
//....
}
} catch (NullPointerException ex) {
}
Just. Don't. Do. This. Ever.
Re: checking if a cell in JTable is selected
but it works and its the only way i could get it to work
Re: checking if a cell in JTable is selected
Quote:
Originally Posted by
Dcalladi
but it works and its the only way i could get it to work
You're essentially ignoring a fatal bug in your code and that is just such bad practice, that it will bite you in the tail eventually, and soon. Better to check if a variable is null before you try to use it. First figure out which variable is null -- possibly searchResults, but you'll want to test for this in your code. If so, figure out why and then what you want to do if it is null.