我在Netbeans中创建了2个JFrame(预订,确认预订),两个框架都连接到SQL数据库。在Booking类中,用户通过在jtextfield中输入数字,从显示的表中选择一个度假胜地。如果用户按下下一步按钮。处置类预订并打开ConfirmBooking。我想访问在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);
            }
    }

最佳答案

您可以修改一点ConfirmBooking类,以便可以在类的构造函数中传递该变量

然后您可以执行以下操作:

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


您可以将该ID存储在ConfirmBooking的成员中,并在需要时在setUp方法中检索它!

07-27 13:34