我有一个名为LoginScreen的jframe,用于连接到DB。一个用于用户名输入的文本字段,一个用于密码输入的密码字段,一个登录按钮和一个用于记住用户名值的复选框。我希望当用户单击用户名记住复选框并尝试登录时,当从数据库值接受用户名和密码时,必须存储在 pref key 中。让我分享代码;
public class LoginScreen extends javax.swing.JFrame {
/**
* Creates new form LoginScreen
*/
public LoginScreen() {
initComponents(); //initialize components
if ( "null" == PREF_NAME){
rememberCheckBox.setSelected(false);
}
else if ("null" != PREF_NAME){
rememberCheckBox.setSelected(true);
}
if (true == rememberCheckBox.isSelected()){
unameTextField.setText(PREF_NAME);
}
else if(false == rememberCheckBox.isSelected()){
unameTextField.setText("your user name");
}
}
Preferences prefs = Preferences.userNodeForPackage(rememberexample.LoginScreen.class);
String PREF_NAME = "null";
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://192.168.100.100;" + "databaseName=ExampleDB;" + "user=" + unameTextField.getText() + ";" + "password=" + new String (jPasswordField1.getPassword()) + ";";
Connection con = DriverManager.getConnection(connectionUrl);
if (true == rememberCheckBox.isSelected()){
prefs.put(PREF_NAME, unameTextField.getText());
System.out.println(PREF_NAME);
}
else if (false == rememberCheckBox.isSelected()){
prefs.remove(PREF_NAME);
System.out.println(PREF_NAME);
}
con.close();
}
catch (SQLException e) {
JOptionPane.showMessageDialog(this, "Wrong id or password!!");
}
catch (ClassNotFoundException cE) {
System.out.println("Class Not Found Exception: "+ cE.toString());
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new LoginScreen().setVisible(true);
}
});
}
private javax.swing.JPasswordField jPasswordField1;
private javax.swing.JButton loginButton;
private javax.swing.JCheckBox rememberCheckBox;
private javax.swing.JTextField unameTextField;
但PREF_NAME始终返回 null。如您所见,我为执行的按钮操作添加了一个控件。System.out.println(PREF_NAME);单击按钮时返回 null。知道吗?
你说:
String PREF_NAME = "null";
那么你永远不会改变它的值(你不应该,见后面......)并且你正在打印出来:
System.out.println(PREF_NAME);
==>显然你会得到"null"作为输出
你应该做什么:
final String PREF_NAME = "pref_name"; //define the name for your key
然后以后:
prefs.put(PREF_NAME, unameTextField.getText()); //put something in your preference using your key
System.out.println(prefs.get(PREF_NAME, "no value")); //output the preference *value* not the key
请参阅文档