关闭jframe并在java中重新打开后保存变量 [英] Save variables after closing jframe and re-opening in java

查看:321
本文介绍了关闭jframe并在java中重新打开后保存变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个要求您输入密码的程序,并在稍后添加一个更改密码的选项,但每次关闭它并再次打开时,每次打开时密码都会重置为默认值再一次。我已将默认关闭操作设置为隐藏,但我认为每次再次运行程序时,它都是全新的。另外,我查看了我的任务管理器的后台程序,还有很多Java TM Platform SE Binary。
这是我的核心问题:

I'm making a program that asks you to enter a password, and adds in an option to change the password later, but every time I close it and open it again, the password is reset to the default every time I open it again. I've set the default close operation to hide, but I think every time I run the program again, it's completely new. Also, I look into the background programs of my task manager, and there's a lot of "Java TM Platform SE Binary"s. Here's my core questions:

当我从eclipse运行程序时,它每次都打开一个全新的程序吗?我可以更改吗?

When I run a program from eclipse, does it open a brand new program every time? Can I change this?

如何在程序中的打开/关闭操作中保存变量?

How would I save variables across the open/close actions in my program?

在此先感谢

推荐答案

你没有发布任何代码,所以我假设你有密码变量已定义,您的程序如下所示:

You didn't post any code, so I'm going to assume you have a password variable defined and your program looks something like this:

Scanner userInput = new Scanner(System.in);
String password = "Default01";
System.out.print("Enter new password: ");
password = userInput.next();

每次运行程序时,它都会在RAM中创建一个全新的密码变量实例。程序关闭时,RAM中的任何内容都会被破坏。您需要某种持久存储,并将该信息写入变量。文本文件是一种简单的方法。添加它会使您的程序看起来像:

Each time you run the program, it will create in RAM, a brand new password variable instance. When the program is closed, anything in RAM is destroyed. You need some sort of persistent storage where you are writing that information to a variable. A text file is an easy way to start. Adding that would make your program look like:

Scanner userInput = new Scanner(System.in);
File passwordFile = new File("passwordfile.txt");
//this is where the password is stored.
Scanner passwordScanner = new Scanner(passwordFile);
//this is how you read the file.
String password = passwordScanner.next();
//password has been read.

...然后提示输入新密码。

... Then prompt for a new password.

System.out.print("Enter new password: ");
password = userInput.next(); //prompt for new password

...然后将新密码写入文件以进行持久存储。

... Then write that new password to a file for persistent storage.

PrintWriter passwordWriter = new PrintWriter("passwordfile.txt");
// overwrites the current passwordfile.txt, so you now have an empty file
passwordWriter.print(password);
//writes the password to passwordfile.txt so it can be used next time.

希望这有点帮助!

这篇关于关闭jframe并在java中重新打开后保存变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆