0

I working on java mini game with swing so its look like a program(Cause i just learn java + database).Now i have login system but i don't know how to do it:

*when i login i stay logged in until o do not close program

*because i want to make a char for my account and save character stats to my account id so

  ----> table account 
  ID: 2 
  Account:Yolo 
  Password:Swag
  -----------------> table Character 
  ID:"my id " 

Char name what i want etc so i want to ask how to get current accountid and insert it to another table with char stats?i learning so don't blame me:)


`

static Connection connection = null;
Statement stmt = null;

    public JFrame LoginF;
    public JLabel UsernameL;
    public JLabel PasswordL;
    public JButton LoginB;
    public JTextField User;
    public JPasswordField Pass;


    public static void main(String args[]){

        Login log = new Login();
        log.Swing();
        connection=LoginIn.connector();
    }

    public void Swing(){
        LoginF = new JFrame("Game");
        LoginF.setSize(400,400);
        LoginF.getContentPane().setLayout(null);

        User = new JTextField();
        User.setBounds(219, 63, 86, 20);
        LoginF.getContentPane().add(User);
        User.setColumns(10);

        Pass = new JPasswordField();
        Pass.setBounds(219, 122, 86, 20);
        LoginF.getContentPane().add(Pass);

        JLabel UsernameL = new JLabel("Username");
        UsernameL.setBounds(65, 66, 69, 14);
        LoginF.getContentPane().add(UsernameL);

        JLabel PasswordL = new JLabel("Password");
        PasswordL.setBounds(65, 125, 69, 14);
        LoginF.getContentPane().add(PasswordL);

        JButton LoginB = new JButton("Login");
        LoginB.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try{
                    String query="select * from AccountAdatok where Username=? and Password=?";
                    PreparedStatement pst=connection.prepareStatement(query);
                    pst.setString(1, User.getText());
                    pst.setString(2, Pass.getText());

                    ResultSet rs=pst.executeQuery();
                    int count=0;
                    while(rs.next()){
                        count=count+1;
                    }
                    if(count ==1)
                    {
                        JOptionPane.showMessageDialog(null, " Correct!");
                        LoginF.dispose();
                        MakeCharacter.main(arg0);
                    }
                    else if (count>1)
                    {
                        JOptionPane.showMessageDialog(null, " Cannot Duplicate!");
                    }
                    else
                    {
                        JOptionPane.showMessageDialog(null, " InCorret!");
                    }
                    rs.close();
                    pst.close();
                }catch(Exception e){
                    JOptionPane.showMessageDialog(null, e);
                }
                finally{
                    try{

                    }catch(Exception e){
                        JOptionPane.showMessageDialog(null, e);
                    }
                }
            }
        });
        LoginB.setBounds(145, 201, 89, 23);
        LoginF.getContentPane().add(LoginB);

        LoginF.setVisible(true);
    }

}`

Iliiaz Akhmedov
  • 867
  • 7
  • 17
  • 2
    Avoid using `null` layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify – MadProgrammer Dec 15 '15 at 21:50
  • You login UI should do a very basic job, it should get the details from the user. It should then pass those details to some kind "authenticator" to process and verify the details, if the details are valid, you should provide notification back to some listener, who would then decide what should be done. This way you decouple you code and improve re-usability – MadProgrammer Dec 15 '15 at 21:52
  • When a user is authenticated, you should return some "token" which can be used to identify the user within your system, you might consider using a `User` object, which contains the user name and database id for the user, for example. – MadProgrammer Dec 15 '15 at 21:53
  • Updated my answer, if you need more help, shout for it, If you feel this has helped you, upvote and accept the answer, thanks – Kebab Programmer Dec 15 '15 at 22:11

2 Answers2

1

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

Login View

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"

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

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<User> 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<User>();
    initialize();
}

construct 2

public LoginScreen(JFrame frame, ArrayList<User> usrList) {
    this.frame = frame;
    this.usrList= usrList;
}

Simple (I will update this more for you if you need it)

Kebab Programmer
  • 1,213
  • 2
  • 21
  • 36
  • 1
    Personally, I don't think I'd be storing all the user details in an `ArrayList` until AFTER the particular user has been authenticated and then I wouldn't be storing the password in memory :P. – MadProgrammer Dec 15 '15 at 22:41
  • I know, but taking in the fact that he is a beginner, I wanted to make things easy for him, this still works :D – Kebab Programmer Dec 15 '15 at 22:42
  • Thanks for your answer too :) i will try this too! – Balázs Szmetana Dec 15 '15 at 22:44
  • Good, then lets take the opportunity to teach them professional/best practices (after all SO is for professionals, by professionals), these are simple and easy to learn and will make the OP a better developer in the long run ;) - Doing the "right" thing is lot easier then people make it out to be ;) – MadProgrammer Dec 15 '15 at 22:44