简体   繁体   中英

passing a value from a jframe and use it to another

## this is the code of loginframe ##

    public class Login_frame extends javax.swing.JFrame {

  Connection conn = null;
  ResultSet rs = null;
  PreparedStatement pst = null;



public Login_frame() {
    initComponents();
    conn = javaconnect.ConnecrDB();
}


private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {                                          
    String sql ="select * from userinfo where username =? and password =? ";
    try{
        pst = conn.prepareStatement(sql);
        pst.setString(1,txt_username.getText());
        pst.setString(2,txt_password.getText());

        rs = pst.executeQuery();

        if(rs.next()){
        JOptionPane.showMessageDialog(null, "Username and Password is correct");
        rs.close();
        pst.close();
       close();
        Welcome_Screen w = new Welcome_Screen();
        w.userName = this.txt_username.getText();
        w.setVisible(true);

        }

}catch(Exception e){

         JOptionPane.showMessageDialog(null, "Invalid username or password");
}finally{
        try{
            rs.close();
            pst.close();


        }catch(Exception e){

        }

    }
}                                         

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            this.setVisible(false);
            Register_frame r = new Register_frame();
           r.setVisible(true);

}                                        

public void close(){
    WindowEvent winClosingEvent= new WindowEvent(this,WindowEvent.WINDOW_CLOSING);
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent);
}    

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

}

this is the code of the second Jframe

public class Welcome_Screen extends javax.swing.JFrame {
static Object txt_username;
     Connection conn = null;
     ResultSet rs = null;
     PreparedStatement pst = null;
      String username="";
/**     
 * Creates new form Welcome_Screen
 */
public Welcome_Screen() {
    initComponents();
     conn = javaconnect.ConnecrDB();
     Update_table();
      Update_table2();
      update_elements();

}




private void update_elements(){

    try{
      String sql ="select league from Teams where team_owner= '"+username+"' ";
      pst = conn.prepareStatement(sql);
      rs = pst.executeQuery();
            while(rs.next())
            {
             String result =rs.getString("league");
             league_txt.setText(result);

             }


    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);

    }finally{
        try{
            rs.close();
            pst.close();


        }catch(Exception e){

        }

    }

}

 private void Update_table2(){
    try{

          String sql ="select Player,Pos,Age from user_team ";
          pst = conn.prepareStatement(sql);
          rs = pst.executeQuery();
          myTeam.setModel(DbUtils.resultSetToTableModel(rs));


    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);

    }finally{
        try{
            rs.close();
            pst.close();


        }catch(Exception e){

        }

    }

}

  private void Update_table(){
    try{

           String sql ="select * from Teams ";
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            league_table.setModel(DbUtils.resultSetToTableModel(rs));


    }catch(Exception e){
    JOptionPane.showMessageDialog(null, e);

    }finally{
        try{
            rs.close();
            pst.close();


        }catch(Exception e){

        }

    }



}
`I have a problem regarding on how to pass value from one `JFrame` to another and use it to an `sql` query.

Let's be more clear. I want to make a programm which has to JFrame s. the first is a login frame. I want to take the value which the user has entered in the username textfield and use it to load a table which is unique for the each user.

More simply i want to replace the userName in this query

String sql ="select league from Teams where team_owner= '"+userName+"' "; 

Let me know if any of this is confusing. Basically what was happening is when you created a new instance of Welcome_Screen your constructor seen below. update_elements(); was called... THEN your userName was given its value where you made the new frame. It was just an issue with line order. You were doing everything right though.

String username="";
/**     
 * Creates new form Welcome_Screen
 */
public Welcome_Screen(String userName) {
    initComponents();
     conn = javaconnect.ConnecrDB();
     //this. keyword is very important otherwise the 
     //local variable won't set the frame variable.
     this.userName = userName;
     Update_table();
     Update_table2();
     update_elements();
}

Also now that you have a parameter on your constructor whenever you make a new call with Welcome_Screen you'll need to pass it a String of your choice. However, it's not your choice in this program at this point. You must make the call like this for it to work.

//I lied either should be fine.
Welcome_Screen w = new Welcome_Screen(userName);
Welcome_Screen w = new Welcome_Screen(yourTextField.getText());

You cannot pass it, because you don't store it anywhere. You should either finish this method body:

String username;
private void txt_usernameActionPerformed(java.awt.event.ActionEvent evt)     {                                             
    // TODO add your handling code here:
    username = ((JTextField)evt.getSource()).getText();
}  

Then you can pass username anywhere you want.

Better you don't need to use listener at all and declare txt_username on class level. Then you get user input any time just by calling txt_username.getText()

Your code looks generated by some GUI tool. I would recommend to start with hand writes until you exactly whats being generated...

Second reply

Well, it seems that you changed your code. I can't see initComponents(); method anymore. I think you will need to put it back. You declared (or netbeans did it for you) JtextField txt_username = new ... in that method. If you move it to the top of LoginFrame class, right where your connection and resultset is then you can use this anywhere inside Login_frame and not only in initComponents(). BTW. in java you should name classes like LoginFrame (don't use underbar, but thats just convention)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM