【发布时间】:2014-02-28 21:06:38
【问题描述】:
我有一个名为 LoginScreen 的 jframe 用于连接数据库。一个用于用户名输入的文本字段,一个用于密码输入的密码字段,一个登录按钮和一个用于记住用户名值的复选框。我希望当用户单击用户名记住复选框并尝试登录时,当从 DB 值接受用户名和密码时,必须将其存储在 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。有什么想法吗?
【问题讨论】:
-
你为什么这样做:
String PREF_NAME = "null";? -
我必须为首选项创建一个密钥?
-
和价值
"null"?你也应该让它成为最终的 -
我把它变成了最终但同样的问题发生了。 System.out.println(PREF_NAME);在按钮动作中仍然变成“null”
-
当然,它不应该解决问题。在 java 中创建常量
final是一个好习惯。这是因为PREF_NAME只是您偏好的key,它不应该改变它的值。您正在寻找的是键PREF_NAME的首选项值
标签: java swing preferences