我有一个名为 A 的类和一个名为 T 的类。当 A 单击按钮时,我希望它更新 T 的内容。我在执行此操作时遇到问题...任何建议,谢谢。
A类:
FileWriter fstream = new FileWriter("open.txt", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("\n" +number1);
jLabel1.setText(number1);
out.close();
T t = new T();
t.refresh();
refresh是我想要调用来更新类T的函数
T:
public void refresh() {
File file = new File("open.txt");
try {
Scanner sc = new Scanner(file);
if (sc.hasNext()) {
jTextField2.setText(sc.next());
} else {
jTextField2.setText("Nothing to see here");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
这就是我希望它调用的函数。它只是不更新文本。我认为这与我如何使用文本文件有关。任何想法谢谢。
最佳答案
您正在附加到您的文件:
FileWriter fstream = new FileWriter("open.txt", true);
但读取第一个值:
Scanner sc = new Scanner(file);
if (sc.hasNext()) {
jTextField2.setText(sc.next());
永远不会改变。我怀疑这就是您没有看到变化的原因。
您需要写入该文件吗?难道您不能使用刚刚写入文件的数据调用 refresh()
方法(或重载变体)吗?
关于java - 尝试将一个类中的信息刷新到java中的另一个类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13175656/