java重新打开jframe,关闭jframe并在java中重新打开后保存变量

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:

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?

Thanks in advance

解决方案

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();

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.

Hopefully that helps a bit!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值