0

I'm trying to do a log in I've gotten the username to work but the password is failing hard, I've tried multiple techniques and different ways and all of them have failed, my last effort seems to do nothing at all no error messages either where my previous stuff displayed error. Can you please help me fix this + show me how to navigate to another page if the access is verified and password and username is right?

    import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

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


/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MainMenu extends javax.swing.JFrame {
    private JLabel username;
    private JLabel passwordlbl;
    private JLabel Welco;
    private JPasswordField Passwordfld;
    private JButton Cancelbtn;
    private JButton OKbtn;
    private JTextField Usernametxt;
    private String Password = "pass";

    /**
    * Auto-generated main method to display this JFrame
    */

    public static void main(String[] args) {
        //PASSWORD field to store new password inside
        //Passwordfld.setEchoChar('*');
        //Passwordfld.addActionListener(new AL());

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MainMenu inst = new MainMenu();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);

            }
        });
    }

    public MainMenu() {
        super();
        initGUI();
    }
    private static boolean isPasswordCorrect(char[] input) {
        boolean isCorrect = true;
        char[] correctPassword = { 'b', 'u', 'g', 'a', 'b', 'o', 'o' };

        if (input.length != correctPassword.length) {
            isCorrect = false;
        } else {
            isCorrect = Arrays.equals (input, correctPassword);
        }

        //Zero out the password.
        Arrays.fill(correctPassword,'0');

        return isCorrect;
    }
    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().setLayout(null);

            username = new JLabel();
            getContentPane().add(username);
            username.setText("User Name:");
            username.setBounds(63, 113, 80, 16);

            passwordlbl = new JLabel();
            getContentPane().add(passwordlbl);
            passwordlbl.setText("Password:");
            passwordlbl.setBounds(63, 160, 72, 16);

            Usernametxt = new JTextField();
            getContentPane().add(Usernametxt);
            Usernametxt.setBounds(198, 110, 79, 23);

            OKbtn = new JButton();
            getContentPane().add(OKbtn);
            OKbtn.setText("OK");
            OKbtn.setBounds(102, 217, 59, 23);
            OKbtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                if(Usernametxt.getText().equals("Admin")){} /*&& 
                (Passwordfld.getText().equals("Admin2"))*/

                        String cmd = evt.getActionCommand();

                        if (OKbtn.equals(cmd)) { //Process the password.
                            char[] input = Passwordfld.getPassword();
                            if (isPasswordCorrect(input)) {
                                System.out.println("Password Accepted");
                            } else {
                               System.out.println("Password Rejected");

                            }

                            //Zero out the possible password, for security.
                            Arrays.fill(input, '0');

                            Passwordfld.selectAll();



                /*else{
                        System.out.println("permition Rejected");
                    }*/

                    //else{} 
                    /* if (Passwordfld = Password)= true) {
                         System.out.println("permition granted");}*/
                    }
                }
            }
            );

            Cancelbtn = new JButton();
            getContentPane().add(Cancelbtn);
            Cancelbtn.setText("Exit");
            Cancelbtn.setBounds(198, 217, 61, 23);
            Cancelbtn.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    setDefaultCloseOperation(WindowConstants.setVisible(false);
                    //System.out.println("Cancelbtn.actionPerformed, event="+evt);
                    //TODO add your code for Cancelbtn.actionPerformed
                }
            });

            Welco = new JLabel();
            getContentPane().add(Welco);
            Welco.setText("Welcome to Jstore please log in using your staff acount");
            Welco.setBounds(51, 19, 291, 16);

            JPasswordField Passwordfld = new JPasswordField();
            //Passwordfld.setText("Secret");
            getContentPane().add(Passwordfld);
            Passwordfld.setBounds(198, 157, 79, 23);
            Passwordfld.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    //System.out.println("Passwordfld.actionPerformed, event="+evt);
                    //TODO add your code for Passwordfld.actionPerformed
                }
            });



            pack();
            setSize(400, 300);
        } catch (Exception e) {
            //add your error handling code here
            e.printStackTrace();
        }

    }
    //static class AL implements ActionListener{
    //JPasswordField input = new JPasswordField();

    /*  char [] passy = input.getPassword();
        String p = new String (passy);{
        if (p.equals (Password)){
            JOptionPane.showMessageDialog(null, "Correct"); }
            else
            {       JOptionPane.showMessageDialog(null, "InCorrect");

        }
        */


    }
Andrew Brēza
  • 7,705
  • 3
  • 34
  • 40
Hava Nasar
  • 29
  • 2

2 Answers2

1

Alternatively you can use this....

package javaapplication7;

 import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 import javax.swing.JOptionPane;

/**
*
* @author akash
 */
public class detail extends javax.swing.JFrame implements ActionListener{

private final String username ="admin";
private final String password = "pass";
public detail() {
    initComponents();
    jButton1.addActionListener(this);
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jTextField2 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Username");

    jLabel2.setText("Password");

    jTextField1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextField1ActionPerformed(evt);
        }
    });

    jButton1.setText("Submit");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(28, 28, 28)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
                    .addGap(37, 37, 37)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jTextField1)
                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 195, Short.MAX_VALUE)))
                .addGroup(layout.createSequentialGroup()
                    .addGap(126, 126, 126)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 147, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(63, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(46, 46, 46)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(47, 47, 47)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(14, 14, 14))
    );

    pack();
}// </editor-fold>                        

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                            
    // TODO add your handling code here:
}                                           

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(detail.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new detail().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
// End of variables declaration                   

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource()== jButton1)
    {
        if("admin".equals(jTextField1.getText()) && "pass".equals(jTextField2.getText()))
        {
             java.awt.EventQueue.invokeLater(() -> {
                 new LoggedIn().setVisible(true);
             });
        }
        else
        {
            JOptionPane.showMessageDialog(rootPane, "Please use admin and pass");
        }
    }

}
}

The above one will be your first class and the next will be....

class LoggedIn extends javax.swing.JFrame {

/**
 * Creates new form LoggedIn
 */
public LoggedIn() {
    initComponents();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("Welcome 2 Store");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(91, 91, 91)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(101, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(68, 68, 68)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(163, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(LoggedIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */

}

// Variables declaration - do not modify                     
private javax.swing.JLabel jLabel1;
// End of variables declaration                   
}

Hoping it helped....

CoderNeji
  • 2,056
  • 3
  • 20
  • 31
  • Thank you so much much appreciated, I would thumbs up but too low rep :( I'll try up my rep and return back to this to give you a +1, once again thank you for taking your time to help me. – Hava Nasar Apr 06 '15 at 15:35
0

Your password field is not inited, it's still null when you try to take char[] from it. You can try with:

    final JPasswordField Passwordfld = new JPasswordField();
    // Passwordfld.setText("Secret");
    getContentPane().add(Passwordfld);
    Passwordfld.setBounds(198, 157, 79, 23);
    Passwordfld.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // System.out.println("Passwordfld.actionPerformed, event="+evt);
        // TODO add your code for Passwordfld.actionPerformed
    }
    });
    OKbtn = new JButton();
    getContentPane().add(OKbtn);
    OKbtn.setText("OK");
    OKbtn.setBounds(102, 217, 59, 23);
    OKbtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        String passText = new String(Passwordfld.getPassword());
        if (Usernametxt.getText().equals("Admin")) {

        String cmd = evt.getActionCommand();

        if (OKbtn.getActionCommand().equals(cmd)) { // Process the password.
            if (isPasswordCorrect(passText.toCharArray())) {
            System.out.println("Password Accepted");
            } else {
            System.out.println("Password Rejected: " + passText);

            }

            // Zero out the possible password, for security.
            Arrays.fill(passText.toCharArray(), '0');

            Passwordfld.selectAll();

            /*
             * else{ System.out.println("permition Rejected"); }
             */

            // else{}
            /*
             * if (Passwordfld = Password)= true) {
             * System.out.println("permition granted");}
             */
        }
        }
    }
    });
chilltouch
  • 281
  • 2
  • 10
  • I have no idea how that happened, I used GUI builder can you help me or tell me how to fix it or what to change I'm quite new to java thanks. – Hava Nasar Apr 06 '15 at 12:55