我目前正在使用Java应用程序,并且刚创建了一个登录框架。它可以正常工作,但是由于每次我要访问第二个JFrame时都必须登录,所以我想到,无法通过按密码文本字段上的Enter来登录,这很烦人。有没有一种方法可以使文本字段使用与按钮相同的actionlistner?
这是我当前正在使用的代码。随意将其用于您自己的登录系统!
package presentation;
/**
*
* @author Jessie den Ridder
*/
import javax.swing.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import presentation.ScreenInfoFrame;
public class MyLogin {
private JFrame frame = new JFrame("Login");
private final JLabel inputLabel1 = new JLabel("Gebruikersnaam");
private final JLabel inputLabel2 = new JLabel("Wachtwoord");
private JTextField input1 = new JTextField();
private JPasswordField input2 = new JPasswordField();
private final JButton button = new JButton("Login");
private final JLabel inputLabel3 = new JLabel("");
public MyLogin() {
inputLabel1.setBounds(850, 405, 180, 20);
input1.setBounds(1000, 400, 180, 30);
inputLabel2.setBounds(850, 455, 180, 20);
input2.setBounds(1000, 450, 180, 30);
button.setBounds(1000, 520, 180, 30);
frame.getContentPane().add(button);
frame.getContentPane().add(inputLabel1);
frame.getContentPane().add(input1);
frame.getContentPane().add(input2);
frame.getContentPane().add(inputLabel2);
frame.getContentPane().add(inputLabel3);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
String sql = "SELECT id, userName, password, firstName, lastName FROM employee ;";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"Database", "user", "Password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
String user = input1.getText();
String pwd = (input2.getText());
while (rs.next()) {
String uname = rs.getString("userName");
//Username is the coloumn name in the database table
String password = rs.getString("password");
if ((user.equals(uname)) && (pwd.equals(password))) {
frame.dispose();
ScreenInfoFrame ui = new ScreenInfoFrame();
ui.setVisible(true);
}
}
} catch (ClassNotFoundException | SQLException k) {
JOptionPane.showMessageDialog(null, k.getMessage());
}
}
});
}
}
无需向按钮添加新的动作侦听器,而是创建动作侦听器
ActionListener myActionListener = new ActionListener() {
// Action listener body here
}
然后使用button.addActionListener(myActionListener);
和将其添加到元素中input2.AddActionListener(myActionListener);
。
附带说明一下,我建议您不要给您的组件起通用名称button
,input#
因为这样会使它们难以分辨其功能。选择更具体的名称,例如passwordField
或submitButton
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句