我想保存在文本字段中写入的所有内容,并删除程序在单击搜索按钮后找到的行。为什么它不起作用?这是我的两个按钮:
private class dDelete implements ActionListener {
public void actionPerformed (ActionEvent e) {
HM.remove((String)result.getText());
}
}
private class sSave implements ActionListener {
public void actionPerformed (ActionEvent e) {
Set <String> ISet = HM.keySet();
Iterator itr = ISet.iterator();
String tuple = "";
java.io.File iwrite = new java.io.File("c:\\temp\\savetest.txt");
if (iwrite.exists()){
System.out.println("The file exists");
System.exit(0);
}
java.io.PrintWriter output = null;
try {
output = new java.io.PrintWriter(iwrite);
} catch(Exception ex) {
ex.printStackTrace();
}
while (itr.hasNext()) {
String Keys = (String)itr.next();
String val = HM.get(Keys);
tuple = Keys + " " + val;
output.print(tuple);
}
}
}
最佳答案
您应该关闭输出编写器 output.close()
这可能就是原因。
您没有显示要添加到集合 HM 中的内容,因此很难判断删除是否有效。检查 HM.remove 调用的返回值,您将看到它是否成功,否则您使用了错误的键(添加和删除时不使用相同/相等的键)。
除此之外,当您需要键和值时(HM.entrySet()
),我建议您迭代entrySet。
还要根据 Java 命名约定重命名您的类和变量(类以大写字母开头,实例变量不应以大写字母开头等)。欲了解更多信息。请参阅Java naming conventions .
关于java - 保存和删除按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10405325/