0

I have the following login made in java It has 2 Jframes, Login JFrame and another JFrame that I call Main. What do I want to do is : When I log in successfully I want to parse to my label from 2'nd form the username which I used to log in with.

So If I log in with eddye, I want 'eddye' to be parsed to my 2'nd form

Code for the 1'st JFrame :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package mysqltryouts;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author ExtremeSwat
 */





public class login_panel extends javax.swing.JFrame {


  private Connection connect = null;
  private Statement statement = null;
  private PreparedStatement preparedStatement = null;
  private ResultSet resultSet = null;




  public void readDataBase() throws Exception
  {

       String username = jTextField1.getText();

      String password = jPasswordField1.getText();

//    System.out.println(username);
//    System.out.println(password);
//    System.out.println("test");

      //---------------------

//      String databaseUsername = "";
//      String databasePassword = "";

    try {
      // this will load the MySQL driver, each DB has its own driver

      Class.forName("com.mysql.jdbc.Driver");

      // setup the connection with the DB.

      connect = DriverManager
          .getConnection("jdbc:mysql://localhost/cards?"
              + "user=root&password=password");





     //String sqlQuery = "select count(*) > 0 as match_found FROM username WHERE username = ? and password = MD5(?)";
      String sqlQuery = "SELECT * FROM username WHERE username = ? and password = MD5(?)";
       // String sqlQuery = "select count(*) > 0 as cnt FROM username WHERE username = ? and password = MD5(?)";

      PreparedStatement pst = connect.prepareStatement( sqlQuery );
pst.setString( 1, username );
pst.setString( 2, password );

ResultSet rs = pst.executeQuery();

if( rs.next() ) 
{

JOptionPane.showMessageDialog(null, "Succesfully Logged In", "Success", JOptionPane.INFORMATION_MESSAGE);

//        int width = this.getWidth();
//        int height = this.getHeight();
//        
//        System.out.println(width);
//        System.out.print(height);

this.setVisible(false);
new FrmMain().setVisible(true);


}
else
{
  JOptionPane.showMessageDialog(null, "Failed to log in", "Failure", JOptionPane.WARNING_MESSAGE);
}

    } catch (Exception e) {
      throw e;
    } finally {
      close();
    }

  }


            private void close() {
    close(resultSet);
    close(statement);
    close(connect);
  }

  private void close(AutoCloseable c) throws UnsupportedOperationException {
    try {
      if (c != null) {
        c.close();
      }
    } catch (Exception e) {
    // don't throw now as it might leave following closables in undefined state
    }

}



    /**
     * Creates new form login_panel
     */
    public login_panel() {
        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() {

        jTextField1 = new javax.swing.JTextField();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

        jLabel1.setText("Username");

        jLabel2.setText("Password");

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

        jButton2.setText("eXIT");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Old English Text MT", 1, 36)); // NOI18N
        jLabel3.setText("Login B0$$");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(66, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(53, 53, 53))))
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                .addComponent(jButton2))
        );

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

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

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         








  try{ 


//   login_panel dao = new login_panel();
//   
//   
//   dao.readDataBase();

      this.readDataBase();

     }
  catch(Exception e)
  {
      System.out.println(e.getMessage());
  }


    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         


   int dialogButton = JOptionPane.YES_NO_OPTION;

    int dialogResult = JOptionPane.showConfirmDialog(null, "Exit? ", "Information",dialogButton);

        if(dialogResult == JOptionPane.YES_OPTION)
        {
            JOptionPane.showMessageDialog(null, "Thanks for the stay","Confirm",JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);

        }else
        {
            JOptionPane.showMessageDialog(null, "Remaining...","Remaining....",JOptionPane.INFORMATION_MESSAGE);

        }

    }                                        

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




                login_panel frame = new login_panel();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

The code for the 2'nd JFrame

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package mysqltryouts;

import java.awt.Dimension;
import java.awt.Toolkit;

/**
 *
 * @author ExtremeSwat
 */
public class FrmMain extends javax.swing.JFrame {

    /**
     * Creates new form FrmMain
     */
    public FrmMain() {
        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() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Back");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(297, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 231, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

//        int width = this.getWidth();
//        int height = this.getHeight();
//        
//        System.out.println(width);
//        System.out.print(height);

        this.setVisible(false);

new login_panel().setVisible(true);
    }                                        

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

                FrmMain frame =  new FrmMain();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);




            }
        });
    }

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

I really need some help with this one. I have in mind the code from VB.NET

Dim username as String = "abc" Form2.label1.text = username;

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ExtremeSwat
  • 794
  • 1
  • 12
  • 34

1 Answers1

1

If your User logged in successfully the you call the Constructor of the second JFrame, this you can do like

new FrmMain(username).setVisible(true);

and you'll have to add another field like private String userName; change the Constructor of your FrmMain() class

// ...
private String userName;

public FrmMain(String username) {
   this.userName = username;
   initComponents();
}


// ... 

And in your initComponents() Method you set the userName to your jLabel

jLabel1.setText(userName);

Thats it. The usage of multiple JFrame's is not the best solution, maybe you can read some articles about MVC and work within one JFrame and only change JPanels!

Update:

Here are your two classes, i changed them, like i suggest.

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author ExtremeSwat
 */





public class LoginPanel extends javax.swing.JFrame {


  private Connection connect = null;
  private Statement statement = null;
  private PreparedStatement preparedStatement = null;
  private ResultSet resultSet = null;




  public void readDataBase() throws Exception
  {

       String username = jTextField1.getText();

      String password = jPasswordField1.getText();

//    System.out.println(username);
//    System.out.println(password);
//    System.out.println("test");

      //---------------------

//      String databaseUsername = "";
//      String databasePassword = "";

      /*
    try {
      // this will load the MySQL driver, each DB has its own driver

      Class.forName("com.mysql.jdbc.Driver");

      // setup the connection with the DB.

      connect = DriverManager
          .getConnection("jdbc:mysql://localhost/cards?"
              + "user=root&password=password");





     //String sqlQuery = "select count(*) > 0 as match_found FROM username WHERE username = ? and password = MD5(?)";
      String sqlQuery = "SELECT * FROM username WHERE username = ? and password = MD5(?)";
       // String sqlQuery = "select count(*) > 0 as cnt FROM username WHERE username = ? and password = MD5(?)";

      PreparedStatement pst = connect.prepareStatement( sqlQuery );
pst.setString( 1, username );
pst.setString( 2, password );

ResultSet rs = pst.executeQuery();
*/
if( username.equalsIgnoreCase("patrick") && password.equalsIgnoreCase("1234") ) 
{

JOptionPane.showMessageDialog(null, "Succesfully Logged In", "Success", JOptionPane.INFORMATION_MESSAGE);

//        int width = this.getWidth();
//        int height = this.getHeight();
//        
//        System.out.println(width);
//        System.out.print(height);

this.setVisible(false);
new FrmMain(username).setVisible(true);


}
else
{
  JOptionPane.showMessageDialog(null, "Failed to log in", "Failure", JOptionPane.WARNING_MESSAGE);
}
/*
    } catch (Exception e) {
      throw e;
    } finally {
      close();
    }
*/
  }


            private void close() {
    close(resultSet);
    close(statement);
    close(connect);
  }

  private void close(AutoCloseable c) throws UnsupportedOperationException {
    try {
      if (c != null) {
        c.close();
      }
    } catch (Exception e) {
    // don't throw now as it might leave following closables in undefined state
    }

}



    /**
     * Creates new form login_panel
     */
    public LoginPanel() {
        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() {

        jTextField1 = new javax.swing.JTextField();
        jPasswordField1 = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

        jLabel1.setText("Username");

        jLabel2.setText("Password");

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

        jButton2.setText("eXIT");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Old English Text MT", 1, 36)); // NOI18N
        jLabel3.setText("Login B0$$");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(66, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(53, 53, 53))))
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addGap(38, 38, 38)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 63, Short.MAX_VALUE)
                .addComponent(jButton2))
        );

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

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

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         








  try{ 


//   LoginPanel dao = new LoginPanel();
//   
//   
//   dao.readDataBase();

      this.readDataBase();

     }
  catch(Exception e)
  {
      System.out.println(e.getMessage());
  }


    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         


   int dialogButton = JOptionPane.YES_NO_OPTION;

    int dialogResult = JOptionPane.showConfirmDialog(null, "Exit? ", "Information",dialogButton);

        if(dialogResult == JOptionPane.YES_OPTION)
        {
            JOptionPane.showMessageDialog(null, "Thanks for the stay","Confirm",JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);

        }else
        {
            JOptionPane.showMessageDialog(null, "Remaining...","Remaining....",JOptionPane.INFORMATION_MESSAGE);

        }

    }                                        

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




                LoginPanel frame = new LoginPanel();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

And the FrmMain()

import java.awt.Dimension;
import java.awt.Toolkit;

/**
 *
 * @author ExtremeSwat
 */
public class FrmMain extends javax.swing.JFrame {

    private String userName;
    /**
     * Creates new form FrmMain
     */
    public FrmMain(final String userName) {
        this.userName = userName;
        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() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel1.setText(userName);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("Back");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(297, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 231, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

//        int width = this.getWidth();
//        int height = this.getHeight();
//        
//        System.out.println(width);
//        System.out.print(height);

        this.setVisible(false);

new LoginPanel().setVisible(true);
    }                                        



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

I had to comment the Database part, i replaced it with a String equals check, so copy & paste the two classes and test it with Patrick / 1234 and you should see Patrick as Username on your new JFrame, if you are logged in successful.

Patrick
  • 4,532
  • 2
  • 26
  • 32
  • Sorry for being an idiot, but I have no Idea where to add those. Am I supposed to add the new FrmMain(username) in my If statement where I check out my user & pass ? Sorry for asking for more, but it's my 1'st time when I play around with JFrames and I am a bit confuse – ExtremeSwat Apr 25 '14 at 19:13
  • Yes, you call the new FrmMain() Constructor in your If Statement, when the successful loginmessage is displayed by the JOptionPane. And in your FrmMain Class you have to add the new field userName and in the initComponents() Method you pass this userName variable to your jLabel1. – Patrick Apr 25 '14 at 19:32
  • I have a problem, I am not able to modify the initComponents() from my JPanel I cannot edit them. (I am working in netBeans) – ExtremeSwat Apr 25 '14 at 20:24
  • I updated my Answer, copy&paste the two classes and try it again. Uncomment the Database part, so that you can query Username and Password against your DB. – Patrick Apr 25 '14 at 20:36
  • I don't understand one thing. how's the username parsed to the second form ? (it works), but I don't understand this line of code : new FrmMain(username).setVisible(true); So basically it creates the new frame with this parameter included in it ? And after that how does it tell the diffrence between username and userName ? And why did I have to comment/eliminate the void_run from my FrmMain ? I'm a bit confuse about that one, thanks – ExtremeSwat Apr 26 '14 at 08:17
  • Can't modify the MainFrame , it claims it's corrupted. – ExtremeSwat Apr 26 '14 at 08:23
  • Okay, the new FrmMain(username) is the Constructor of this new Window, which opens after you logged in successful. A constructor is a special method, which can have one or more parameters like this String userName. I wrote userName because it is the hungarian notation (http://en.wikipedia.org/wiki/Hungarian_notation) and i lerned programming with this notation because it is better readable for other humans. But what is it with MainFrame, why you can't modify it and where is the code of this MainFrame. – Patrick Apr 26 '14 at 12:58
  • And i also would suggest to work with only one JFrame (Window) and display the LoginPanl after you start your application and when the user is successful logged in you remove the LoginPanel (JPanel) and show another Panel. – Patrick Apr 26 '14 at 13:00