我有一个名为LoginScreen的jframe用于连接到DB。一个文本字段用于uname输入,一个密码字段用于密码输入,一个登录按钮和一个用于记住用户名值的复选框。我希望当用户单击Uname Remember复选框并尝试登录时,如果从DB值接受uname和密码,则必须将其存储在pref键中。让我分享代码;
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。有什么想法吗?
答案 0 :(得分:2)
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