Making a login screen is really easy, just make a screen with input and validation and another Java code taking in your frame.
Follow these easy steps and you should be able to log In.
- For authentication, I suggest you create an object to store data from your database and store those objects into an arraylist.
Example
private ArrayList usrList;
private void downloadUsrData() {
dbc = new DBConn(); //Ignore this, I am using a driver
String query1 = "SELECT * FROM user_table";
rs = dbc.getData(query1);
try {
while (rs.next()) {
String username = rs.getString("username");
String passwd = rs.getString("passwd");
String fName = rs.getString("fName");
String lName = rs.getString("lName");
User usr = new User(username, passwd, fName, lName);
usrList.add(usr);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "Request Failed"
+ "\nPossible Reasons are:"
+ "\n1- No connection to database"
+ "\n2- No data in database");
}
- Then when you've entered your data, you then go through your arraylist matching your input with data held by the objects in your arraylist
If data is matched correctly, pass frame from one java code to another
Example
Checker
if (action.equals("Login")) {
String usernameInput = usernameField.getText().toString();
String passwdInput = passwdField.getText().toString();
boolean isLoggedIn = false;
passwdField.setText("");
for (User usr : usrList) {
if (usr.getUserName().equals(usernameInput)) {
if (usr.getPassWd().equals(passwdInput)) {
isLoggedIn = true;
frame.getContentPane().removeAll();
GameScreen gmeScreen = new GameScreen(frame, usrList,
usr);
}
}
}
if (isLoggedIn == false) {
JOptionPane.showMessageDialog(null,
"Username/Password may be In-correct");
}
}
- Also make sure you have another class constructor that you can call if you want to logout, you just recall the second modded constructor
Example
constructor 1
public LoginScreen() {
usrList = new ArrayList();
initialize();
}
construct 2
public LoginScreen(JFrame frame, ArrayList usrList) {
this.frame = frame;
this.usrList= usrList;
}
Simple (I will update this more for you if you need it)