因此,我正在创建一个程序,该程序将搜索jtable的第一列,并找到该值是否存在,然后将其输出到下面的jTextFields中。我说对了,但是我不知道如何检查在jtable上不存在在搜索文本字段上输入的数据。如果要在jtable的该列上不存在数据,我想输出一个joptionpane。
这是我的代码。
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);
}
答案 0 :(得分:0)
好吧...由于您的搜索条件似乎是基于ID的,因此如果ID等于零,则通知用户未找到任何内容。
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);
而且...我确定您已经了解Java命名约定。 :)