Issue
I'm using netbeans and i'm having trouble when deleting a row in a jTable. I want to delete a data using a textfield and a button. I've tried something like this but doesn't work:
private void btnDelActionPerformed(java.awt.event.ActionEvent evt) {
String text2 = (String)jTextField2.getText();
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
if (!text2.equals(model)){
do {
String [] row = {text2};
while(!text2.equals(model));
model.removeRow(WIDTH);
}
}
I also tried to make it like this one, but still doesn't work:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String text = (String)jTextField1.getText();
DefaultTableModel model = (DefaultTableModel)jTable2.getModel();
for (int i = 0; i < model.getRowCount(); i++)
{
for(int j = 0; j < model.getColumnCount(); j++) {
model.setValueAt(text, i, j);
}
}
Any ideas? Please make it easy for me to understand. I'm really a beginner on java and I don't know if I'm using the right code.
Solution
Say you have this data
First Name Last Name
Lebron James
Michael Jordan
Kobe Bryant
What you want to do is loop through the model and depending on which column you want to check against, that will be the column
you pass to getValueAt(row, column)
. So you could do something like this
private void jButton1ActionPerformed(ActionEvent evt) {
String name = jTextField1.getText();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
for (int i = 0; i < model.getRowCount(); i++) {
if (((String)model.getValueAt(i, 0)).equals(name)) {
model.removeRow(i);
break;
}
}
}
I use 0
for the getValueAt()
, checking for the First Name
column. If a name equals, the row is deleted.
If I type in Lebron
, the row of Lebron James
will be deleted.
Answered By - Paul Samsotha