2015-04-30 101 views
1

我想將客戶名稱傳遞給類StartSearchByName2,我正在使用netbeans IDE。客戶名稱來自Jtextfield。 請給我提供一些解決方案。我有關於Java的基本知識,我堅持了約6個小時。將字符串從TextField傳遞到另一個類

類StartSByName

public class StartSByName extends javax.swing.JFrame { 
String Customername; 
    public void close() { 
    WindowEvent winClosingEvent = new WindowEvent(this, WindowEvent.WINDOW_CLOSING); 
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(winClosingEvent); 
} 


    String NameM(String Name){ 
    Name = Customername; 
    System.out.println(Name); 
    return Name; 
} 
public StartSByName() { 
    initComponents(); 
} 

private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {           
jButtonAction5(evt); 
}                     
public void jButtonAction5(ActionEvent evt) { 
    Connection con = null; 
    PreparedStatement st = null; 
    ResultSet rs = null; 

    try { 
     Class.forName("com.mysql.jdbc.Driver"); 
     con=DriverManager.getConnection("jdbc:mysql://localhost:3306/holt", "root", ""); 
     st=con.prepareStatement("select * from customers where Name=?"); 
     Customername = jTextField1.getText(); 
     st.setString(1, Customername); 
     rs = st.executeQuery();   
     jTextField1.setText(Customername); 
     if (rs.next()) { 
     JOptionPane.showMessageDialog(null, "Customer Found With ID = " + rs.getString("ID")); 
      jTextField1.setText(Customername); 
      String Name = null; 
      NameM(Name); // Calling NameM 
      StartSearchByName2 SB = new StartSearchByName2(); 
      SB.setVisible(true); 
      close(); 
     } else { 
      JOptionPane.showMessageDialog(null, "Customer Does Not Exist"); 
     } 
    } catch (ClassNotFoundException | SQLException | HeadlessException ex) { 
     System.out.println("Error " + ex); 
    } } 

類StartSearchByName2

public class StartSearchByName2 extends javax.swing.JFrame { 
String Name; 
StartSByName Sb= new StartSByName(); 
public StartSearchByName2() { 
    System.out.println(Sb.NameM(Name)); 

輸出

Tabish Raza // This Output from StartSByName Class and when calling NameM 
null // From StartSearchByName2, its twice null, but i called once and it is not giving me Correct String. 
null // 
+0

您需要先設置這些值,您可以將它們傳遞給構造函數或使用setter方法。 請具體說明您的問題,沒有機構有時間閱讀您發佈的所有內容。 –

回答

1
public class StartSearchByName2 extends javax.swing.JFrame { 

    String Name; 

    public StartSearchByName2(String pName) { 
     Name = pName; 
     System.out.println(Name); 
} 

在你的第一類更改下面的語句

StartSearchByName2 SB = new StartSearchByName2(); 

StartSearchByName2 SB = new StartSearchByName2(Name); 
+0

我正在嘗試。 – Tabi

+0

有關構造函數的更多信息:http://www.javabeginner.com/java-constructors/ – User404

0

我能夠只使用靜態字符串客戶名稱來解決這個問題。 然後稍後當我在第二個類中調用此字符串時,我將獲取此字符串的最後一個更新值。

相關問題