【发布时间】:2015-04-05 09:10:03
【问题描述】:
我正在尝试编写一个带有登录窗口的程序(在 Java 中),我已经成功地进行了登录,但是当用户登录时,我希望程序在数据库中找到他们的名字(使用他们的 ID ) 并将他们的名字写入不同类中的变量(使用登录名初始化)。目的是然后从不同 JFrame 中的变量中检索名称并将其写入标签,从而显示当前用户。
到目前为止,我的代码如下:
public class GUI_Launcher extends javax.swing.JFrame {
private Connection connection;
private Connection getConnection() throws ClassNotFoundException, SQLException {
if (connection == null) {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
String connURL = "jdbc:ucanaccess://"+ new File("databases/Employees.accdb").getAbsolutePath();
connection = DriverManager.getConnection(connURL, "", "");
}
return connection;
}
private boolean validateUser(String STR_UserID, String STR_Password) {
boolean validation = false;
try (Statement statement = getConnection().createStatement();){
try (ResultSet result = statement.executeQuery("SELECT COUNT(*) AS Count FROM Employees WHERE [UserID]='" + STR_UserID.replaceAll("'", "''") + "' AND StrComp([Password],'" + STR_Password.replaceAll("'", "''") + "', 0) = 0 AND [LoginAllowed] = 1" )) {
if(result != null) {
result.next();
}
validation = result != null && result.getInt(1) > 0;
}
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return validation;
}
public GUI_Launcher() {
SYS_Package.SYS_Vars SYS_Vars = new SYS_Package.SYS_Vars();
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
BTN_Login = new javax.swing.JButton();
BTN_Cancel = new javax.swing.JButton();
LBL_UserID = new javax.swing.JLabel();
LBL_Password = new javax.swing.JLabel();
FLD_UserID = new javax.swing.JTextField();
FLD_Password = new javax.swing.JPasswordField();
LBL_Error = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Login [Main] - Philani Sales");
setAlwaysOnTop(true);
setMaximumSize(new java.awt.Dimension(416, 339));
setMinimumSize(new java.awt.Dimension(416, 339));
setResizable(false);
BTN_Login.setText("Login");
BTN_Login.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BTN_LoginActionPerformed(evt);
}
});
BTN_Cancel.setText("Cancel");
BTN_Cancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BTN_CancelActionPerformed(evt);
}
});
LBL_UserID.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
LBL_UserID.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
LBL_UserID.setText("User ID");
LBL_Password.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
LBL_Password.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
LBL_Password.setText("Password");
FLD_Password.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
FLD_PasswordKeyPressed(evt);
}
});
LBL_Error.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
LBL_Error.setForeground(new java.awt.Color(255, 0, 0));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(LBL_Error, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(BTN_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 100, Short.MAX_VALUE)
.addComponent(BTN_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(LBL_UserID, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(LBL_Password, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(FLD_UserID)
.addComponent(FLD_Password))))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(FLD_UserID)
.addComponent(LBL_UserID, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(LBL_Password, javax.swing.GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
.addComponent(FLD_Password))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 86, Short.MAX_VALUE)
.addComponent(LBL_Error, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BTN_Login, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(BTN_Cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
setSize(new java.awt.Dimension(416, 339));
setLocationRelativeTo(null);
}// </editor-fold>
private void BTN_CancelActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
private void BTN_LoginActionPerformed(java.awt.event.ActionEvent evt) {
String STR_UserID = FLD_UserID.getText();
String STR_Password = new String(FLD_Password.getPassword());
validateUser(STR_UserID, STR_Password);
if (validateUser(STR_UserID, STR_Password)) {
GUI_Main GUI_Main = new GUI_Main();
GUI_Main.setExtendedState(JFrame.MAXIMIZED_BOTH);
GUI_Main.setUndecorated(true);
GUI_Main.setVisible(true);
this.dispose();
}
else {
FLD_UserID.setText("");
FLD_Password.setText("");
LBL_Error.setText("Invalid Login Credentials!");
}
}
private void FLD_PasswordKeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == KeyEvent.VK_ENTER){
BTN_Login.doClick();
}
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_Launcher.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new GUI_Launcher().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton BTN_Cancel;
private javax.swing.JButton BTN_Login;
private javax.swing.JPasswordField FLD_Password;
private javax.swing.JTextField FLD_UserID;
private javax.swing.JLabel LBL_Error;
private javax.swing.JLabel LBL_Password;
private javax.swing.JLabel LBL_UserID;
// End of variables declaration
我对 Java 还很陌生,因此非常感谢您提供一些示例代码以及解释。谢谢。
【问题讨论】:
-
“非常感谢您提供一些示例代码以及解释。” 互联网上有很多“查询数据库”Java 示例。请搜索它们并真正尝试一下。如果您有具体问题,请回复我们。
-
Andrew 到目前为止,我已经花了几天时间搜索互联网,测试来自不同站点的示例,但都无济于事。如果我不需要,我不会在这里浪费人们的时间。
-
“到目前为止花了几天时间搜索互联网” 使用了哪些搜索词?发现最有帮助的 3 个示例是什么?为什么它们没有有帮助?