Обновление переменной Java из текстового поля работает только один раз

John Shanks спросил: 01 сентября 2018 в 09:57 в: java

Я стараюсь изо всех сил работать над этим и редко приходится публиковать, но пробовал в течение недели и не могу понять, почему это текстовое поле возвращает одно и то же строковое значение даже после его обновления! Я получаю текстовое поле от пользователя, разбор его на целое и отправка его в базу данных, чтобы вернуть файл студента. Он будет работать в первый раз, но каждый раз, когда я пытаюсь выполнить поиск второго ученика, он вернет идентификатор от первого ученика. Я попытался поставить resetStudent () метод в (ниже), и теперь он просто возвращает последнего ученика.

Почему я не могу получить getText (ID) второй раз? Я смотрел на это неустанно, но не могу понять, почему он работает один раз, но потом не снова.

Я добавил почти весь код (включая сгенерированный код для JFrame) в надежде, что есть что-то маленькое где-то который я пропустил.

Если вы хотите более сжатую версию областей, которые, я думаю, могут быть проблемой, дайте мне знать. У меня есть скриншот проблемы, но недостаточно репутации для публикации фотографий ...

enter code here
    package ass3_task1_shanks;    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JOptionPane;    /**
    *
    * @author Dr Migoreng
    */
   public class GradeViewer extends javax.swing.JFrame {       int studentID = 0;
       String ID = "";       /**
        * Creates new form GradeViewer
        */
       public GradeViewer() {
           initComponents();
       }       /**
        * This method is called from within the constructor to initialize the form.
        * WARNING: Do NOT modify this code. The content of this method is always
        * regenerated by the Form Editor.
        */
       @SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    insertRecordPanel = new javax.swing.JPanel();
    IDInputField = new javax.swing.JTextField();
    studentNameInputField = new javax.swing.JTextField();
    quizInputField = new javax.swing.JTextField();
    A1InputField = new javax.swing.JTextField();
    A2InputField = new javax.swing.JTextField();
    A3InputField = new javax.swing.JTextField();
    examInputField = new javax.swing.JTextField();
    resultOutputField = new javax.swing.JLabel();
    gradeOutputField = new javax.swing.JLabel();
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jLabel3 = new javax.swing.JLabel();
    jLabel4 = new javax.swing.JLabel();
    jLabel5 = new javax.swing.JLabel();
    jLabel6 = new javax.swing.JLabel();
    jLabel7 = new javax.swing.JLabel();
    jLabel8 = new javax.swing.JLabel();
    jLabel9 = new javax.swing.JLabel();
    searchButton = new javax.swing.JButton();
    updateButton = new javax.swing.JButton();
    calculateResultsButton = new javax.swing.JButton();    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);    jButton1.setText("Insert Record");    jButton2.setText("Search or Update Grades Database");    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(21, Short.MAX_VALUE))
    );    IDInputField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            IDInputFieldActionPerformed(evt);
        }
    });    resultOutputField.setBackground(new java.awt.Color(255, 255, 255));
    resultOutputField.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
    resultOutputField.setText("-");    gradeOutputField.setBackground(new java.awt.Color(255, 255, 255));
    gradeOutputField.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
    gradeOutputField.setText("-");    jLabel1.setText("Student ID:");    jLabel2.setText("Student Name:");    jLabel3.setText("Quiz Mark:");    jLabel4.setText("Assignment 1 Mark:");    jLabel5.setText("Assignement 2 Mark:");    jLabel6.setText("Assignment 3 Mark:");    jLabel7.setText("Exam Grade:");    jLabel8.setText("Overall Result:");    jLabel9.setText("Overall Grade:");    searchButton.setText("Search");
    searchButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            searchButtonActionPerformed(evt);
        }
    });    updateButton.setText("Update");
    updateButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            updateButtonActionPerformed(evt);
        }
    });    calculateResultsButton.setText("Calculate Results");
    calculateResultsButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            calculateResultsButtonActionPerformed(evt);
        }
    });    javax.swing.GroupLayout insertRecordPanelLayout = new javax.swing.GroupLayout(insertRecordPanel);
    insertRecordPanel.setLayout(insertRecordPanelLayout);
    insertRecordPanelLayout.setHorizontalGroup(
        insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(insertRecordPanelLayout.createSequentialGroup()
            .addContainerGap(45, Short.MAX_VALUE)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(insertRecordPanelLayout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 92, Short.MAX_VALUE)
                        .addComponent(gradeOutputField, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(insertRecordPanelLayout.createSequentialGroup()
                        .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(insertRecordPanelLayout.createSequentialGroup()
                                .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel7))
                                .addGap(62, 62, 62))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, insertRecordPanelLayout.createSequentialGroup()
                                .addComponent(jLabel8)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(resultOutputField, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
                            .addComponent(A3InputField)
                            .addComponent(A2InputField)
                            .addComponent(A1InputField)
                            .addComponent(quizInputField)
                            .addComponent(studentNameInputField)
                            .addComponent(IDInputField)
                            .addComponent(examInputField))))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, insertRecordPanelLayout.createSequentialGroup()
                    .addComponent(updateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(calculateResultsButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE))))
            .addContainerGap())
    );
    insertRecordPanelLayout.setVerticalGroup(
        insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(insertRecordPanelLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(updateButton)
                .addComponent(searchButton))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(calculateResultsButton)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(IDInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(studentNameInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel2))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(quizInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel3))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(A1InputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel4))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(A2InputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel5))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(A3InputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel6))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(examInputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel7))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(resultOutputField, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING))
            .addGap(18, 18, 18)
            .addGroup(insertRecordPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(gradeOutputField, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))
    );    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(insertRecordPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(insertRecordPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(0, 0, 0))
    );    pack();
}// </editor-fold>                                private void searchStudent(int ID) {
                    System.out.println("searching for "+ID);
                    studentNameInputField.setText("");
                    quizInputField.setText("");
                    A1InputField.setText("");
                    A2InputField.setText("");
                    A3InputField.setText("");
                    examInputField.setText("");
                    resultOutputField.setText("");
                    gradeOutputField.setText("");
                    IDInputField.setText(Integer.toString(ID));
            try {       
                initComponents();
                Connection con;
                MyConnection searchStudents = new MyConnection();
                con = searchStudents.getConnection();
                String sqlQuery = "SELECT * FROM gradeprocessing WHERE ID=" + ID;
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sqlQuery);
                try {  
                    if (!rs.isBeforeFirst() ) {    
                            JOptionPane.showMessageDialog(null, "This student cannot be found in the database", "Cannot find student", JOptionPane.WARNING_MESSAGE);
                        }
                    else{
                        while (rs.next()){
                            String studentName = rs.getString("StudentName");
                            int quiz = rs.getInt("Quiz");
                            int A1 = rs.getInt("A1");
                            int A2 = rs.getInt("A2");
                            int A3 = rs.getInt("A3");
                            int examResult = rs.getInt("Exam");
                            double result = rs.getInt("Results");
                            String grade = rs.getString("Grade");
                            IDInputField.setText(Integer.toString(ID));
                            studentNameInputField.setText(studentName);
                            quizInputField.setText(Integer.toString(quiz));
                            A1InputField.setText(Integer.toString(A1));
                            A2InputField.setText(Integer.toString(A2));
                            A3InputField.setText(Integer.toString(A3));
                            examInputField.setText(Integer.toString(examResult));
                            resultOutputField.setText(Double.toString(result));
                            gradeOutputField.setText(grade);
                        }   
                    }                 if (rs != null) {
                    rs.close();
                    System.out.println("the rs is closing OK");
                 }
                 if (stmt != null) {
                    stmt.close();
                    System.out.println("the stmt is closing OK");
                 }
                 if(con != null) {
                    con.close();
                     System.out.println("the con is closing OK");
                }  
                } catch (SQLException ex) {
                    System.out.println("SQL EXCEPTION");
                    Logger.getLogger(GradeViewer.class.getName()).log(Level.SEVERE, null, ex);
                }
               finally {
                        try { if (rs != null) rs.close(); } catch (Exception e) {};
                        try { if (stmt != null) stmt.close(); } catch (Exception e) {};
                        try { if (con != null) con.close(); } catch (Exception e) {};
                    }
              con.close();
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(GradeViewer.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("CLASS NOT FOUND EXCEPTION");
            } catch (SQLException ex) {
                Logger.getLogger(GradeViewer.class.getName()).log(Level.SEVERE, null, ex);
                System.out.println("SECOND SQL EXCEPTION");
            }
        }
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
          System.out.println("This update function is not a problem");}                                            private void calculateResultsButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       
            int quiz = Integer.parseInt(quizInputField.getText());
            int A1 = Integer.parseInt(A1InputField.getText());
            int A2 = Integer.parseInt(A2InputField.getText());
            int A3 = Integer.parseInt(A3InputField.getText());
            int examResult = Integer.parseInt(examInputField.getText());
            double result = calculateResults(quiz,A1,A2,A3,examResult);
            String endResult = Double.toString(result);
            String grade = checkGrade(result);
            resultOutputField.setText(endResult);
            gradeOutputField.setText(grade);
}                                                      private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.out.println("seeing " +IDInputField.getText());
    setStudentID(Integer.parseInt(IDInputField.getText()));
    getStudentID();
    quizInputField.setText("");
    A1InputField.setText("");
    A2InputField.setText("");
    A3InputField.setText("");
    examInputField.setText("");
    resultOutputField.setText("");
    gradeOutputField.setText("");
    try{searchStudent(studentID);
    }
    catch(NumberFormatException ex){
     JOptionPane.showMessageDialog(null, "The student number must only contain numbers atm it contains " + IDInputField.getText(), "Incorrect student number", JOptionPane.WARNING_MESSAGE);    
    }
    //if the resetID method is not run then the searchStudent will just search the old string which was searched the first time
    resetStudentID();
}                                            private void IDInputFieldActionPerformed(java.awt.event.ActionEvent evt) {                                             
    ID = IDInputField.getText();     
}                                            private void setStudentID(int ID){
    studentID = ID;
}private int getStudentID(){
    return studentID;
}private int resetStudentID(){
    studentID = 0;
    IDInputField.setText("");
    return studentID;
}public double calculateResults(int quiz, int A1, int A2, int A3, int examResult){
    double results = 0;
    results = (quiz * 0.05)+(A1 * 0.15) +(A2 * 0.2) + (A3 * 0.10) + (examResult * 0.5);
    return results;
}
public String checkGrade(double results){
    String grade = "NUTTIN";
    if(results>=85){
        grade = "HD";
    }
    else if(results>=75){
        grade = "DI";
    }
    else if(results>=65){
        grade = "CR";
    }
    else if(results>=50){
        grade = "PS";
    }
    else if(results<50){
        grade = "FL";
    }   
    return grade;
}/**
 * @param args the command line arguments
 */
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(GradeViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
     java.util.logging.Logger.getLogger(GradeViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(GradeViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(GradeViewer.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 GradeViewer().setVisible(true);
        }
    });
}

0 ответов