繁体   English   中英

从jframe传递值并将其用于另一个

[英]passing a value from a jframe and use it to another

##这是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);
        }
    });
}

}

这是第二个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.

让我们更加清楚。 我想制作一个必须对JFrame进行编程的程序。 第一个是登录框架。 我想获取用户在用户名文本字段中输入的值,并使用它来加载每个用户唯一的表。

更简单地说,我想在此查询中替换userName

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

让我知道这是否令人困惑。 基本上发生的是当您创建一个Welcome_Screen的新实例时,您的构造函数如下所示。 update_elements(); 被称为...然后在创建新框架的地方给了您的userName值。 这只是订单的问题。 你虽然做得对。

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();
}

同样,现在只要在使用Welcome_Screen进行new调用时,构造函数上就有一个参数,就需要将其传递给您选择的字符串。 但是,这不是您目前在此程序中的选择。 您必须像这样拨打电话才能正常工作。

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

您无法通过它,因为您不会将其存储在任何地方。 您应该完成以下方法体:

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

然后,您可以在任意位置传递用户名。

更好的是,您根本不需要使用侦听器,而在类级别上声明txt_username。 然后,您随时可以通过调用txt_username.getText()获得用户输入。

您的代码看起来是由某些GUI工具生成的。 我建议从手写开始,直到您确切生成了什么为止。

第二次回复

好吧,看来您更改了代码。 我看不到initComponents(); 方法了。 我认为您需要将其放回原处。 您在该方法中声明了JtextField txt_username = new ...(或netbeans为您完成了此操作)。 如果将其移至LoginFrame类的顶部,即连接和结果集的正确位置,则可以在Login_frame内部的任何位置(不仅在initComponents()中)使用此方法。 BTW。 在Java中,您应该命名类似LoginFrame的类(不要使用下划线,但这仅是约定)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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