1

I want to display username in a jLabelon welcome jFrame when user is successfully logged in. I'm doing this project with Netbeans and used DBMS is MySQL. Basically I created two jFrames.

One as login.java and other as welcome.java. The jLabel is placed in welcome.java and variable name initialized as jLabel_UnameDisplay.

Here is picture explanation of my requirement and total codes of the project:

Requirement

login.java

public class login extends javax.swing.JFrame {

public login() {
    initComponents();
}

@SuppressWarnings("unchecked")                    
private void initComponents() {

    jPanel = new javax.swing.JPanel();
    jLabel_uname = new javax.swing.JLabel();
    jLabel_pass = new javax.swing.JLabel();
    txt_uname = new javax.swing.JTextField();
    txt_pass = new javax.swing.JPasswordField();
    jButton_login = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jLabel_uname.setText("User Name");
    jPanel.add(jLabel_uname, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 110, 100, 40));

    jLabel_pass.setText("Password");
    jPanel.add(jLabel_pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 170, 100, 40));
    jPanel.add(txt_uname, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 110, 160, 40));
    jPanel.add(txt_pass, new org.netbeans.lib.awtextra.AbsoluteConstraints(170, 170, 160, 40));

    jButton_login.setText("Login");
    jButton_login.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton_loginActionPerformed(evt);
        }
    });

    jPanel.add(jButton_login, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 230, 90, 40));

    getContentPane().add(jPanel, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 400, 300));

    pack();
}                      

private void jButton_loginActionPerformed(java.awt.event.ActionEvent evt) {                                              
     if (txt_uname.getText().equals("admin")&&txt_pass.getText().equals("1234")){
        new welcome().setVisible(true);
        this.dispose();

    }else{
        try {
        Connection c;
        Class.forName("com.mysql.jdbc.Driver");
        c=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","123");

        Statement s=c.createStatement();
            ResultSet rs= s.executeQuery("SELECT * FROM user WHERE status='1'");

            while (rs.next()) {                    
                String unmae=rs.getString("username");
                String pass=rs.getString("password");

                if(unmae.equals(txtuname.getText()) && pass.equals(txtpass.getText())){
                    new welcome().setVisible(true);
                    this.dispose();
                }


            }

        } catch (Exception ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(rootPane, "Check Your Username or Password","Error",JOptionPane.ERROR_MESSAGE);
        }

    }
}                                             


public static void main(String args[]) {

    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(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new login().setVisible(true);
        }
    });
}

private javax.swing.JButton jButton_login;
private javax.swing.JLabel jLabel_pass;
private javax.swing.JLabel jLabel_uname;
private javax.swing.JPanel jPanel;
private javax.swing.JPasswordField txt_pass;
private javax.swing.JTextField txt_uname;

}

welcome.java

public class welcome extends javax.swing.JFrame {

public welcome() {
    initComponents();
}

@SuppressWarnings("unchecked")

private void initComponents() {

    jPanel = new javax.swing.JPanel();
    jLabel_UnameDisplay = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jPanel.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

    jLabel_UnameDisplay.setBackground(new java.awt.Color(102, 255, 102));
    jLabel_UnameDisplay.setOpaque(true);
    jPanel.add(jLabel_UnameDisplay, new org.netbeans.lib.awtextra.AbsoluteConstraints(93, 69, 199, 126));

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 400, Short.MAX_VALUE)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGap(0, 300, Short.MAX_VALUE)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    pack();
}                   


public static void main(String args[]) {

    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(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(welcome.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }

    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new welcome().setVisible(true);
        }
    });
}

private javax.swing.JLabel jLabel_UnameDisplay;
private javax.swing.JPanel jPanel;

}
halfer
  • 19,824
  • 17
  • 99
  • 186
Sam De
  • 11
  • 1
  • 4

3 Answers3

1

There's a number of ways you might do it, but what you want to aim for is decoupling the login frame from the welcome frame, so that the decision to show one is not made by the other.

You could

Use some kind of observer/delegate/listener that is notified when the user is correctly authenticated, passing the user information to it. It would then be it's responsibility to decide what to do next, in this, show the welcome view, passing it the user information (as an example)

This is common concept in Swing

You could

Use some kind of dialog (instead of a JFrame) which would allow the code to block at the point the dialog is made visible and continuing when it's closed.

In this case, you would need to provide some kind of getter to get the user details (or null if the user cancelled the dialog for some reason), you would then be able to make a decision about what to do based on the result

Have a look at How to use dialogs for more details.

In any case, you will need to be able to pass the information in the login view to the welcome view, the means is generally very common, make use of setters and getters and basic method calling.

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Sorry @MadProgrammer, I have no idea how to do that. Can show me how to write code for this function and where to add those codes in this project. Plz help. I'm beginner. – Sam De Jan 12 '17 at 03:45
  • As a "simple" [example](http://stackoverflow.com/questions/13693776/java-gui-multiple-frames/13694083#13694083), as a more complex [example](http://stackoverflow.com/questions/34299864/login-system-i-dont-know-hot-to-do-it/34300658#34300658) – MadProgrammer Jan 12 '17 at 04:07
0

The easiest way is to pass the user name to the next frame on creation. So that next fame like welcome-page can use the user name. You can also pass a whole object that can store more user-specific data.

Here is the code samples. Make thin change in welcome page

/**
 * Create the frame and pass the parameter during creation
 */
public welcome (Component parent, String logOnUserName) {
    this.parent = parent; // This is to send the reference of parent login
                          // page. This can be useful if you want to
                          // comeback to loginpage
    this.logOnUserName=logOnUserName;

...

And while calling the welcome page from login make this change

new login(this, username).setVisible(true);

Now username is available in the welcome page. Show it in UI.

Prabir Ghosh
  • 430
  • 3
  • 7
0

I have best answer of this question. When you click on Login button then you have to specify there new frame then go to database and choose which column you want to display on after login frame. You can display with using JLable. Also you can provide reference of this video :

https://youtu.be/vlYLzCzZigg

  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 13 '21 at 06:14