我有一个带有编辑按钮的 jtable,当我选择一行并单击编辑按钮和编辑字段,然后单击保存按钮时,该行不会更新,我必须刷新我的表才能更改该行!
我的代码:
if (e.getSource() == editButton) {
selectedRow = uTable.getSelectedRow();
if (selectedRow >= 0) {
editUser(selectedRow);
} else {
JOptionPane.showMessageDialog(null, "Select a row");
}
}
public void editUser(int row) {
UserInformation userInf = userModel.getSelectedMember(row);
NewUserFrame_Edit edit = new NewUserFrame_Edit(userInf, row);
}
...
我的 NewUserFrame_Edit 类:
public class NewUserFrame_Edit extends javax.swing.JFrame {
private AllUser userModel;
private int selectedrow;
private String gender;
public NewUserFrame_Edit(AllUser userModel,UserInformation userinf, int row) {
...
this.userModel = userModel;
jTextField1.setText(userinf.getFname().toString().trim());
jTextField2.setText(userinf.getLname().toString().trim());
if (userinf.getGender().equals("Male")) {
jRadioButton1.setSelected(true);
} else {
jRadioButton2.setSelected(true);
}
jTextField3.setText(userinf.getDate());
selectedrow = row;
setVisible(true);
}
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {
userinf = new UserInformation();
userinf.setFname(jTextField1.getText());
userinf.setLname(jTextField2.getText());
userinf.setGender(gender);
userinf.setDate(jTextField3.getText());
userModel.setValueAt(userinf.getFname() , selectedrow, 1);
userModel.setValueAt(userinf.getLname() , selectedrow, 2);
userModel.setValueAt(userinf.getGender(), selectedrow , 3);
userModel.setValueAt(userinf.getDate() , selectedrow, 4);
userModel.updateFile(userModel.Udata);
NewUserFrame_Edit.this.dispose();
}
...
}
我的模型类的 setValueAt() 和 updateFile() 方法:
public class AllUser extends AbstractTableModel {
...
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
UserInformation userInfo = Udata.get(rowIndex);
switch (columnIndex) {
case 0:
userInfo.setID((String) value);
break;
case 1:
userInfo.setFname((String) value);
break;
case 2:
userInfo.setLname((String) value);
break;
case 3:
userInfo.setGender((String) value);
break;
case 4:
userInfo.setDate((String) value);
break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
public void updateFile(ArrayList<UserInformation> data) {
PrintWriter pw;
try {
pw = new PrintWriter(new FileWriter("AllUserRecords.txt"));
for (UserInformation userinf : data) {
String line = userinf.getID()
+ " " + userinf.getFname()
+ " " + userinf.getLname()
+ " " + userinf.getGender()
+ " " + userinf.getDate();
pw.println(line);
}
pw.close();
} catch (IOException ioe) {
}
}
...
}
当我选择一行并单击以编辑按钮时,将打开一个新的 jframe,其文本字段填充有旧数据,我更新数据并单击以保存按钮。因此,我的专栏并不确定。我选择了一整行,而不是一个单元格!
谢谢。