Start by separating the different areas of responsibility, you need
- Some way to gather user details
- Some way to authenticate the user details
- Some way to identify the user after they are logged in
User session...
Let's start with how you might identify the user after they are logged in, for example, you could do something like...
public interface User {
public long getID();
public String getName();
}
public class DefaultUser implements User {
private final long id;
private final String name;
public DefaultUser(long id, String name) {
this.id = id;
this.name = name;
}
@Override
public long getID() {
return id;
}
@Override
public String getName() {
return name;
}
}
This is a very basic concept of a user, they have name and some kind of identifier, which the system can then use to further generate data associated with the user.
Authentication...
Okay, next, we need someway to authenticate the user. Generally speaking, the UI (and the program generally) shouldn't care about the mechanisms by which a user is actually authenticated, only that it is done in a common and well known manner, for example
public interface Authenticator {
public User authenticate(String userName, char[] password) throws AuthenticationException;
}
public class AuthenticationException extends Exception {
public AuthenticationException(String message) {
super(message);
}
public AuthenticationException(String message, Throwable cause) {
super(message, cause);
}
}
So this simply states that you can pass some details to some implementation and it will either return a non-null User
or throw an AuthenticationException
Database authentication...
Next we need some implementation of the Authenticator
which actually performs the authentication process and, if valid, generates a User
object...
public class DatabaseAuthenticator implements Authenticator {
private Connection connection;
public DatabaseAuthenticator(Connection connection) {
this.connection = connection;
}
@Override
public User authenticate(String userName, char[] password) throws AuthenticationException {
User user = null;
String query = "select * from AccountAdatok where Username=? and Password=?";
try (PreparedStatement pst = connection.prepareStatement(query)) {
pst.setString(1, userName);
pst.setString(2, String.copyValueOf(password));
try (ResultSet rs = pst.executeQuery()) {
if (rs.next()) {
long id = rs.getLong("ID");
user = new DefaultUser(id, userName);
} else {
throw new AuthenticationException("Authentication of " + userName + " failed");
}
}
} catch (SQLException exp) {
throw new AuthenticationException("Authentication of " + userName + " failed", exp);
}
return user;
}
}
Now, you might be asking yourself "why go to all the trouble?" Well, apart from providing you with a system which can be easily changed (what to use a web service to authenticate the user? Simple, just implement a new implementation of Authenticator
).
It's also much easier to test, as you can provide a "mocked" implementation of the Authenticator
and test various conditions of your system very easily.
Login View...
Okay, so, that's all fine and good, but how might you actually use all that?
Well, you could, literally, prompt the user for their credentials via the command prompt or read them from a file or, as you seem to want to do, use some kind of Swing based form

Now, you could pretty it up with some additional text/instructions, maybe a logo, but I'll leave that up to you.
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
public class MyAwesomeProgram {
public static void main(String[] args) {
new MyAwesomeProgram();
}
public MyAwesomeProgram() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Authenticator authenticator = new DatabaseAuthenticator(null);
User user = LoginPane.showLoginDialog(null, authenticator);
if (user != null) {
// Next stage of program
} else {
// No valid user, do what you will
}
}
});
}
public static class LoginPane extends JPanel {
private JTextField userNameField;
private JPasswordField passwordField;
public LoginPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(2, 2, 2, 2);
add(new JLabel("User name: "), gbc);
gbc.gridy++;
add(new JLabel("Password: "), gbc);
gbc.gridx++;
gbc.gridy = 0;
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
add(userNameField, gbc);
gbc.gridy++;
add(passwordField, gbc);
}
public String getUserName() {
return userNameField.getText();
}
public char[] getPassword() {
return passwordField.getPassword();
}
public static User showLoginDialog(Component owner, Authenticator authenticator) {
return new LoginDialogView(owner, authenticator).doLogin();
}
protected static class LoginDialogView {
private User user;
private JDialog dialog;
public LoginDialogView(Component owner, Authenticator authenticator) {
dialog = new JDialog(owner == null ? (Window) null : SwingUtilities.windowForComponent(owner));
dialog.setModal(true);
LoginPane loginPane = new LoginPane();
loginPane.setBorder(new EmptyBorder(10, 10, 10, 10));
dialog.add(loginPane);
JPanel buttons = new JPanel();
JButton ok = new JButton("Ok");
JButton cancel = new JButton("Cancel");
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
user = authenticator.authenticate(loginPane.getUserName(), loginPane.getPassword());
dialog.dispose();
} catch (AuthenticationException ex) {
JOptionPane.showMessageDialog(dialog, ex.getMessage());
}
}
});
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
user = null;
dialog.dispose();
}
});
dialog.pack();
dialog.setLocationRelativeTo(owner);
}
public User getUser() {
return user;
}
public User doLogin() {
dialog.setVisible(true);
return getUser();
}
}
}
}
At a conceptual level, this is part of a Model-View-Controller paradigm, where the actual work is not done by the view, but is performed by some other "controller"