Issue
So I am creating a program that will search through the first column of a jtable and find if the value is there then if it is there, it will output in the jTextFields below. I got them right but I don't know how to check if the entered data on the search textfield does not exist on the jtable. I want to output a joptionpane if the data does not exist on that column of jtable.
This is my code.
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String value = jTextField1.getText();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
for (int r = 0; r <= jTable1.getRowCount() - 1; r++){
if (value.equals(jTable1.getValueAt(r, 0))) {
jTable1.setRowSelectionInterval(r, r);
}
}
String ID = model.getValueAt(jTable1.getSelectedRow(), 0).toString();
String Name = model.getValueAt(jTable1.getSelectedRow(), 1).toString();
jTextField2.setText(ID);
jTextField3.setText(Name);
}
Solution
Well...since your search criteria appears to be based from the ID, if ID equals nothing then inform User that nothing was found.
String value = jTextField1.getText(); // Search Criteria.
if (value.isEmpty()) {
return; // Search criteria is empty. Get outta here.
}
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
String id = ""
String name = ""
int r;
for (r = 0; r < model.getRowCount(); r++){
// Does the current column cell match the search criteria?
if (value.equals(model.getValueAt(r, 0))) {
// Yes it does...
id = model.getValueAt(r, 0).toString(); // Fill id variable
name = model.getValueAt(r, 1).toString(); // Fill name variable
jTable1.setRowSelectionInterval(r, r); // Select JTable Row
break; // Break out of loop. Don't need it anymore.
}
}
// Search Item Not Found.
if (id.equals("") {
JOptionPane.showMessageDialog(this, "Search Criteria (" + value +
") Could No Be Found!",
"Item Not Found", JOptionPane.WARNING_MESSAGE);
return; // Get out of method.
}
// Search Item Was Found, Fill JTextFields...
jTextField2.setText(id);
jTextField3.setText(name);
And...I'm sure you already know about Java naming conventions. :)
Answered By - DevilsHnd
Answer Checked By - Pedro (JavaFixing Volunteer)