0

I'm currently making a gui program and I'm clueless to how I am meant to set up my program so when the user inputs a username and password, and then clicks the login button it checks the database for the username and password, and if the username and password is in the database, they accepted, if not declined.

This is my Welcome screen, its bad at the moment I plan to tidy it up.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * @author 
 */
public class Welcome extends JFrame {

    private JButton Existing, New, Exit;
    private JLabel Welcome, Date, Version;
    private JPanel WelcomeP;
    private JMenuItem jmiNew, jmiExisting, jmiExit, jmiAbout;

    public Welcome() {
        //create menu bar
        JMenuBar regMenuBar = new JMenuBar();

        //set menu bar to the applet
        setJMenuBar(regMenuBar);
        //add menu "operation" to menu bar
        JMenu optionsMenu = new JMenu("Options");
        optionsMenu.setMnemonic('O');
        regMenuBar.add(optionsMenu);

        //add menu "help"
        JMenu helpMenu = new JMenu("Help");
        helpMenu.setMnemonic('H');
        helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
        regMenuBar.add(helpMenu);

        //add menu items with mnemonics to menu "options"
        optionsMenu.add(jmiNew = new JMenuItem("New", 'N'));
        optionsMenu.add(jmiExisting = new JMenuItem("Existing", 'E'));
        optionsMenu.addSeparator();
        optionsMenu.add(jmiExit = new JMenuItem("Exit", 'E'));


        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        WelcomeP = new JPanel();
        WelcomeP.setLayout(new GridLayout(2, 1));


        Welcome = new JLabel("Welcome");
        Date = new JLabel("Date: 01/10/2013");
        Version = new JLabel("Version 0.1");
        Exit = new JButton("Exit");
        Existing = new JButton("Existing User");
        New = new JButton("New User");
        
        WelcomeP.add(Welcome);
        WelcomeP.add(Date);
        WelcomeP.add(Version);
        WelcomeP.add(Existing);
        WelcomeP.add(Exit);
        WelcomeP.add(New);


        Exit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        New.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                registerInterface regFace = new registerInterface();
                regFace.setVisible(true);
                Welcome.this.dispose();
                Welcome.this.setVisible(false);

            }
        });
        Existing.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                log login = new log();
                login.setVisible(true);
                login.setSize(500, 300);
                Welcome.this.dispose();
                Welcome.this.setVisible(false);

            }
        });
        jmiExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        jmiNew.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                registerInterface regFace = new registerInterface();
                regFace.setVisible(true);
                Welcome.this.dispose();
                Welcome.this.setVisible(false);

            }
        });
        jmiExisting.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                log shoeFace = new log();
                shoeFace.setVisible(true);
                shoeFace.setSize(500, 300);
                Welcome.this.dispose();
                Welcome.this.setVisible(false);

            }
        });
        //listner for about menuitem
        jmiAbout.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                JOptionPane.showMessageDialog(null, 
                    "Program Dedicated to researchers of eAgriculture"
                                        + "\n Assignment for University", 
                        "About", JOptionPane.INFORMATION_MESSAGE);
            }
        });
        c.add(WelcomeP, BorderLayout.CENTER);

        setSize(500, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
        Welcome app = new Welcome();
    }
}

When I click existing user it takes me to the login panel which is :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Login {
//  public static void main(String arg[])
//  {
//      log frame=new log();
//      frame.setSize(500,500);
//      frame.setLocationRelativeTo(null);
//      frame.setVisible(true);     
//  }
}

class log extends JFrame {

    private JTextField jtfUsername, jtfPassword;
    private JButton backButton, loginButton;
    private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;

    log() {
        //create menu bar
        JMenuBar jmb = new JMenuBar();

        //set menu bar to the applet
        setJMenuBar(jmb);

        //add menu "operation" to menu bar
        JMenu optionsMenu = new JMenu("Options");
        optionsMenu.setMnemonic('O');
        jmb.add(optionsMenu);

        //add menu "help"
        JMenu helpMenu = new JMenu("Help");
        helpMenu.setMnemonic('H');
        helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
        jmb.add(helpMenu);

        //add menu items with mnemonics to menu "options"
        optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
        optionsMenu.addSeparator();
        optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));

        //panel p1 to holds text fields
        JPanel p1 = new JPanel(new GridLayout(2, 2));
        p1.add(new JLabel("Username"));
        p1.add(jtfUsername = new JTextField(15));
        p1.add(new JLabel("Password"));
        p1.add(jtfPassword = new JPasswordField(15));

        //panel p2 to holds buttons
        JPanel p2 = new JPanel(new FlowLayout());
        p2.add(backButton = new JButton("Back"));
        p2.add(loginButton = new JButton("Login"));

        //Panel with image??????

        //add panels to frame
        JPanel panel = new JPanel(new GridLayout(2, 1));
        panel.add(p1, BorderLayout.CENTER);
        panel.add(p2, BorderLayout.SOUTH);
        add(panel, BorderLayout.CENTER);
        setTitle("Main Page");


        //listners for exit menuitem and button
        jmiBack.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Welcome welcome = new Welcome();
                welcome.setVisible(true);
                welcome.setSize(500, 500);
                welcome.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                log.this.dispose();
                log.this.setVisible(false);
            }
        });

        backButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Welcome welcome = new Welcome();
                welcome.setVisible(true);
                welcome.setSize(500, 500);
                welcome.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                log.this.dispose();
                log.this.setVisible(false);
            }
        });

        //listner for about menuitem
        jmiAbout.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null,
                        "This is the login panel"
                        + "\n Assignment for University",
                        "About", JOptionPane.INFORMATION_MESSAGE);
            }
        });

        //action listeners for Login in button and menu item
        loginButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MainMenu mainmenu = new MainMenu();
                mainmenu.setVisible(true);
                mainmenu.setSize(500, 500);
                mainmenu.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                log.this.dispose();
                log.this.setVisible(false);
            }
        });

        jmiLogin.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MainMenu mainmenu = new MainMenu();
                mainmenu.setVisible(true);
                mainmenu.setSize(500, 500);
                mainmenu.setLocationRelativeTo(null);
                registerInterface regFace = new registerInterface();
                regFace.setVisible(false);
                log.this.dispose();
                log.this.setVisible(false);
            }
        });
    }
}

I've set up a JDBC in netbeans and have added tables with username and password and filled the tables up with mock up usernames and passwords, I also want to make it when they click new user they can add new information to the database so that they can long in with the new account.

Below is my JDBC

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 

public class JDBC { 
    private Connection con = null;
    private String query = null; 
    private ResultSet rs; 
    private String url = "jdbc:derby://localhost:1527/Assignment";    
    private String usrName = "root";
    private String pwd = "root";
    
    public JDBC() throws Exception { 
        try { 
            con = DriverManager.getConnection(url, usrName, pwd); 
            query = "SELECT USERNAME, PASSWORD from root.PERSON";
            PreparedStatement stm = con.prepareStatement(query); 
            rs = stm.executeQuery(); 
            while (rs.next()) { 
                String USER = rs.getString("USERNAME"); 
                String PW = rs.getString("PASSWORD"); 
                
                System.out.println(" USERNAME: " + 
                        USER + " PASSWORD: " + PW); 
            } 
            close(); 
        } catch (Exception e) {           
        }
    }
    private void close() { 
        try { 
            if (rs != null) { 
                rs.close(); 
            } 
            if (con != null) {
                con.close(); 
            }
        } catch (Exception e) { 
        }
    }
    
    public static void main(String[] args) throws Exception { 
        JDBC dao = new JDBC();
    } 
} 
13
  • Variable names should not start with upper case characters (Welcome, Date, Version...) Commented Sep 21, 2013 at 4:38
  • @Hayde this is not jdbc,well which database you are using? Commented Sep 21, 2013 at 4:46
  • @javaBeginner I put my jdbc up now. Commented Sep 21, 2013 at 4:59
  • @Hayde i think you need to check the username and password with the entered username password,if susscessful then do some thing else go back.If this is your requirement then in the while loop while(rs.next()) check username and password if matches then go ahead and if not return back Commented Sep 21, 2013 at 5:05
  • @javaBeginner could you show an example? Commented Sep 21, 2013 at 5:35

3 Answers 3

1

Read the JDBC Database Access tutorial for information about SQL.

Edit:

Why are you reading all the userid's and passwords? For a login check you would query the database to see if the values enter in the userid/password text fields are found in the database.

So the query would be something like:

query = "select userid from person where userid = ? and password = ?";
PreparedStatement stm = con.prepareStatement(query); 
stmt.setString(1, useridTextField.getText());
stmt.setString(2, passwordTextField.getPassword().toString());

So your SQL method needs access to the data from the textfields.

Then if the ResultSet is not empty you know you the proper password was entered for the given userid.

Again, read the tutorial for the proper SQL.

Sign up to request clarification or add additional context in comments.

Comments

0

This is a small piece of code that is used for checking username and password and this is for mysql database

public void check(String username,String password)
{
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","username","password");
        PreparedStatement pt=con.prepareStatement("select username,password from authentication_table where username=?");
        pt.setString(1, username);
        ResultSet rs=pt.executeQuery();
        String orgUname="",orPass="";
        while(rs.next())
        {
            orgUname=rs.getString("username");
            orPass=rs.getString("password");

        }
        if(orPass.equals(password))
        {
            //do something
        }
        else
        {
            //do something
        }
    }
    catch(Exception e)
    {

    }

11 Comments

-1, This is a terrible implementation. Why would you read all the userids and passwords when you can just use a "where" clause on the SQL statement.
That is the way to read multiple records returned in a ResultSet. When you do a search on userid you should only ever return one record. So I would have used an if statement to see if the userid was found. Then you need a second if statement to check if the password is a match. I would have thought the code I suggested to do the query on userid and password at the same time was easier. Then you only need a simple rs.next() check.
You miss my point. What if the user for some strange reason has two passwords? Your code would return two records in the ResultSet and your code would only ever set your variables to the last values retrieved. Therefore your "password check" logic should be inside the while loop to make sure you check all records. With my solution you will only ever return 1 or 0 records in the ResultSet. So you only ever need a single if statement to determine when the userid/password match.
I have no idea why you think you should not use an if statement inside the while loop. Lets say you are reading data from the database to display in a JTable. There may be times you need to convert the data from the database in order to display it properly in the JTable. For example maybe your database stores Boolean values as "0" or "1", but a JTable would expect Boolean.TRUE or Boolean.FALSE in order to use the default renderers. So in the loop you would have a simple if statement to do the conversion.
Exactly. When you use a while loop the implication is that you expect multiple records to be found. So in addition to the while loop you also need a separate if statement to validate the password. In my suggestion since the query checks the userid and password, I only need to use a simple if statement to determine if the ResultSet contains the record or not. The code is simpler and will also work if the user happens to have two passwords for some strange reason.
|
0

You should learn about writing DAOs and connection manager class and then plug them in your gui code. Here is how you can approach it:

  1. Create a connection manager class to create database connection using the jdbc contructs.
  2. Write DAO class to operate on table data such as Login table data, call it appropriately such as LoginDAO
  3. Add a service class if required to do some business logic or manipulation on data fetched.
  4. Finally form your action listeners call the service class to do your task

Above approach is totally influenced from MVC architecture to write modular and loosely coupled code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.