2017-06-06 270 views
1

我已經在Netbeans(Booking,ConfirmBooking)中創建了2個JFrame,這兩個框架都連接到SQL數據庫。在Booking類中,用戶通過在jtextfield中輸入一個數字來選擇度假村形式。如果用戶按下下一個按鈕。課程預訂已處理,並且「確認預訂」已打開。我想在ConfirmBooking的jtextfield中訪問在Booking中輸入的變量,以訪問用戶預訂的度假村的名稱。在類之間共享變量

預訂分類編碼,我想訪問在類中設置爲public int的ID。

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
    String x = jTextFieldID.getText(); 
    ID = Integer.valueOf(x); 
    String sql = "SELECT RESORT_NAME FROM LouwDataBase.Resorts WHERE ID = "+ ID; 
     try (PreparedStatement pstmt = conn.prepareStatement(sql)) { 

       try (ResultSet rs = pstmt.executeQuery()) { 
        if (rs.next()) { 
        String resortName = rs.getString("RESORT_NAME"); 

        int n = JOptionPane.showOptionDialog(null, 
        "Do you want to make a booking at "+resortName+"?", 
        "Confirm booking?", 
        JOptionPane.OK_CANCEL_OPTION, 
        JOptionPane.INFORMATION_MESSAGE, 
        null, 
        new String[]{"Yes I do", "No I don't"},"default"); 


        if (n == JOptionPane.YES_OPTION) 
        { 
         ConfirmBooking CB = new ConfirmBooking(); 
         dispose(); 
         CB.setLocationRelativeTo(null); 
         CB.setVisible(true); 

        } 
         else if (n == JOptionPane.NO_OPTION) 
        {    
      } 
     } 
    } 

} 
catch (SQLException ex) 
{ 
Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex); 
} 

} 

ConfirmBooking類代碼

public void SetUp() 
    { 
     UserList(); 

     String sql = "SELECT RESORT_NAME, COST_PER_NIGHT_ZAR FROM LouwDataBase.Resorts WHERE ID = "+ ID; 
      try (PreparedStatement pstmt = conn.prepareStatement(sql)) 
      { 
        try (ResultSet rs = pstmt.executeQuery()) 
        { 
         if (rs.next()) 
         { 
         String Name1 = rs.getString("RESORT_NAME"); 
         double Price = rs.getDouble("COST_PER_NIGHT_ZAR"); 
         String Rands = Double.toString(Price); 
         ResortName.setText(Name1); 
         ResortPrice.setText("R "+Rands); 
         } 
        } 
      } 
      catch (SQLException ex) 
      { 
       Logger.getLogger(Booking.class.getName()).log(Level.SEVERE, null, ex); 
      } 
    } 
+0

不能你注入你需要到'ConfirmBooking'構造什麼變量?你禁止修改這些類嗎? –

+0

不,這是我的學校PAT(實踐評估任務)我必須創建自己的課程,並對課程中未學習的編程進行研究。 – Swiper

+0

那麼究竟是什麼阻止你通過構造函數或某種方法傳遞變量? –

回答

1

,你可以修改了一點ConfirmBooking類,所以你可以通過這個變量的類也許

的構造函數,然後你可以這樣做:

if (n == JOptionPane.YES_OPTION) { 
    ConfirmBooking CB = new ConfirmBooking(ID); 
    dispose(); 
    CB.setLocationRelativeTo(null); 
    CB.setVisible(true); 
} 

您將該ID存儲在ConfirmBooking的成員中並在需要時在setUp方法中檢索它!

+0

它的工作謝謝你 – Swiper

+0

你是什麼意思返回?回到哪裏? –

+0

不,我現在犯了一個錯誤 – Swiper

0

你可以嘗試這樣的事:

ConfirmBooking CB = new ConfirmBooking(); 
CB.setResortNumber(resortName);