The following code is a pop-up window (JOptionPane) for login and password.
How can I make my Java program to remember these two Strings: log
and pass
so that when the user turns off the program and next time turns it on ... the log
and pass
inserted last time would be there already as default?
import javax.swing.*;
public class TestJP {
public static String log;
public static String pass;
public static void main(String[] args) {
JTextField login = new JTextField(5);
JPasswordField password = new JPasswordField(5);
JPanel myPanel = new JPanel();
myPanel.add(new JLabel("login:"));
myPanel.add(login);
myPanel.add(Box.createHorizontalStrut(15));
myPanel.add(new JLabel("password:"));
myPanel.add(password);
int result = JOptionPane.showConfirmDialog(null, myPanel,
"Please Login", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
log = login.getText();
pass = password.getText();
System.out.println("login: " + log);
System.out.println("password: " + pass);
}
}
}
There are a number choices available to you, which you choose will come down to what it is you want to achiieve.
A word of warning. I wouldn't save the password if I was you, none of the methods are hack proof.
You could:
Properties
API and save and load the contents to/from a filePreferences
API which takes care of the persistenace for youEach has it pros and cons. You will need to weigh each and decide which best meets your immediate needs.
Personally, I like the Preferences
API, but it does mean that you lose control over where the data is stored.