2017-03-09 21 views
0

我想製作一個程序,但我有一個問題。我試圖做出下一個按鈕,但它顯示最後一個「soal」和最後一個「jawaban」。我想看到每個SOAL當我按下一個button.I上傳這張截圖和我的代碼嘗試在java中建立一個按鈕netbeans

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package guiandtests1; 

import static guiandtests1.NewJFrame.answer1; 
import static guiandtests1.NewJFrame.answer2; 
import static guiandtests1.NewJFrame.answer3; 
import static guiandtests1.NewJFrame.answer4; 
import static guiandtests1.NewJFrame.question; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Iterator; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 

/** 
* 
* @author abc 
*/ 
public class Guiandtests1 { 




    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws ParseException, IOException { 
     NewJFrame form = new NewJFrame(); 
     form.setVisible(true); 

     JSONParser parser = new JSONParser(); 
     Object obj = null; 

      obj = parser.parse(new FileReader("c:\\Matematika.json")); 


    JSONObject jsonObject = (JSONObject) obj; 
    JSONArray array = (JSONArray) jsonObject.get("data"); // it should be any array name 

    Iterator<Object> iterator = array.iterator(); 
     while (iterator.hasNext()) { 

      JSONObject element=(JSONObject)iterator.next(); 

      System.out.println(element.get("soal")); 

      question=(String) element.get("soal"); 
      JSONArray abc = (JSONArray) element.get("jawaban"); 

      Iterator<Object> iterator1 = abc.iterator(); 

      ArrayList<String> results = new ArrayList<>(); 

      while (iterator1.hasNext()) { 
       results.add(iterator1.next().toString()); 
       //System.out.println(iterator1.next()); 

       } 

      System.out.println(results.get(0)); 
      System.out.println(results.get(1)); 
      answer1=results.get(0); 
      answer2=results.get(1); 
      answer3=results.get(2); 
      answer4=results.get(3); 
    } 

} 
} 
    /* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package guiandtests1; 

import java.io.FileReader; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.Iterator; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 

/** 
* 
* @author abc 
*/ 
public class NewJFrame extends javax.swing.JFrame { 
    public static String question; 
    public static String answer1; 
    public static String answer2; 
    public static String answer3; 
    public static String answer4; 


    /** 
    * Creates new form NewJFrame 
    */ 
    public NewJFrame() { 
     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() { 

     jLabel1 = new javax.swing.JLabel(); 
     jButton1 = new javax.swing.JButton(); 
     jButton2 = new javax.swing.JButton(); 
     jButton3 = new javax.swing.JButton(); 
     jButton4 = new javax.swing.JButton(); 
     jButton5 = new javax.swing.JButton(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jLabel1.setFont(new java.awt.Font("Microsoft YaHei", 0, 48)); // NOI18N 
     jLabel1.setText("jLabel1"); 

     jButton1.setText("jButton1"); 
     jButton1.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton1ActionPerformed(evt); 
      } 
     }); 

     jButton2.setText("jButton2"); 
     jButton2.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton2ActionPerformed(evt); 
      } 
     }); 

     jButton3.setText("jButton3"); 
     jButton3.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton3ActionPerformed(evt); 
      } 
     }); 

     jButton4.setText("jButton4"); 
     jButton4.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton4ActionPerformed(evt); 
      } 
     }); 

     jButton5.setText("Next"); 
     jButton5.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButton5ActionPerformed(evt); 
      } 
     }); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addGap(157, 157, 157) 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addComponent(jButton4) 
        .addComponent(jButton3) 
        .addComponent(jButton2) 
        .addComponent(jButton1)) 
       .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
       .addContainerGap(121, Short.MAX_VALUE) 
       .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
         .addComponent(jLabel1) 
         .addGap(115, 115, 115)) 
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
         .addComponent(jButton5) 
         .addGap(18, 18, 18)))) 
     ); 
     layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
      .addGroup(layout.createSequentialGroup() 
       .addGap(29, 29, 29) 
       .addComponent(jLabel1) 
       .addGap(49, 49, 49) 
       .addComponent(jButton1) 
       .addGap(18, 18, 18) 
       .addComponent(jButton2) 
       .addGap(18, 18, 18) 
       .addComponent(jButton3) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
       .addComponent(jButton4) 
       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE) 
       .addComponent(jButton5) 
       .addContainerGap()) 
     ); 

     pack(); 
    }// </editor-fold>       

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {           
     //this.jButton1.setText(answer1); 
    }           

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {           
     jLabel1.setText(question); 
     jButton1.setText(answer1); 
     jButton2.setText(answer2); 
     jButton3.setText(answer3); 
     jButton4.setText(answer4); 

    }           

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
    }           

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
    }           

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {           
     // TODO add your handling code here: 
    }           

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) throws IOException, ParseException { 
     /* 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 
        JSONParser parser = new JSONParser(); 
     Object obj = null; 

      obj = parser.parse(new FileReader("c:\\Matematika.json")); 


    JSONObject jsonObject = (JSONObject) obj; 
    JSONArray array = (JSONArray) jsonObject.get("data"); // it should be any array name 

    Iterator<Object> iterator = array.iterator(); 
     while (iterator.hasNext()) { 
      JSONObject element=(JSONObject)iterator.next(); 

      System.out.println(element.get("soal")); 
      JSONArray abc = (JSONArray) element.get("jawaban"); 
      Iterator<Object> iterator1 = abc.iterator(); 
      ArrayList<String> results = new ArrayList<>(); 
      while (iterator1.hasNext()) { 
       results.add(iterator1.next().toString()); 
       //System.out.println(iterator1.next()); 

       } 
      System.out.println(results.get(0)); 
      answer1=results.get(0); 
      answer2=results.get(0); 
     /* Create and display the form */ 
     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new NewJFrame().setVisible(true); 
      } 
     }); 
    } 
    } 
    // Variables declaration - do not modify      
    private javax.swing.JButton jButton1; 
    private javax.swing.JButton jButton2; 
    private javax.swing.JButton jButton3; 
    private javax.swing.JButton jButton4; 
    private javax.swing.JButton jButton5; 
    private javax.swing.JLabel jLabel1; 
    // End of variables declaration     

} 

JSON文件位置:

{ 
"data":[ 
{ 
    "id":"1", 
    "soal":"3 * 3 + 2 =", 
    "jawaban":[ 
     "11", 
     "15", 
     "17", 
     "19" 
    ] 

}, 
{ 
    "id":"2", 
    "soal":"20/5 =", 
    "jawaban":[ 
     "4", 
     "3", 
     "2", 
     "1" 
    ] 
}, 
{ 
    "id":"3", 
    "soal":"16 + 6 = ", 
    "jawaban":[ 
     "22", 
     "21", 
     "20", 
     "24" 
    ] 
}, 
{ 
    "id":"4", 
    "soal":"2 * 4 =", 
    "jawaban":[ 
     "8", 
     "6", 
     "10", 
     "12" 
    ] 
}, 
{ 
    "id":"5", 
    "soal":"1+4*2", 
    "jawaban":[ 
     "8", 
     "10", 
     "12", 
     "14" 
    ] 
}, 
{ 
    "id":"6", 
    "soal":"Jika A+1=10 , B+A=11 C= ?", 
    "jawaban":[ 
     "EGP", 
     "1", 
     "12", 
     "22" 
    ] 
}, 
{ 
    "id":"7", 
    "soal":"44/11", 
    "jawaban":[ 
     "4", 
     "2", 
     "5", 
     "8" 
    ] 
}, 
{ 
    "id":"8", 
    "soal":"1+1+1+1+1+1+1+1+1+1+1+1+1+1+1+1 = ", 
    "jawaban":[ 
     "16", 
     "15", 
     "17", 
     "10" 
    ] 
}, 
{ 
    "id":"9", 
    "soal":"Berapakah jawaban sebelumnya ", 
    "jawaban":[ 
     "16", 
     "17", 
     "18", 
     "19" 
    ] 
} 
] 
} 

click to see the first image

click to see the image after next button click

回答

0

您的代碼組織得非常糟糕。一個顯而易見的問題是,您嘗試在輸入文件的迭代內部創建UI。雖然這種方法可以起作用,但通常這是非常糟糕的主意,這就是爲什麼你只看到一個問題的原因。更好的方法是將文件中的數據首先讀入某些內存中的數據結構,然後對其進行處理。

另一個問題是,你需要明白,並非所有事情都應該(甚至可能)使用視覺所見即所得的設計師來完成。整個一堆的分開jButton3ActionPerformed是一個肯定的地獄!

爲什麼你有兩個幾乎相同的main方法?

還有一,我注意到知道你在哪裏有你的org.simple.json,我用一個從https://code.google.com/archive/p/json-simple/downloads又名https://github.com/fangyidong/json-simple但我想提醒你,這是遠離最流行的Java庫的JSON

說了這麼多,這是在你的代碼中的一些改進,還挺更好地工作:

import org.json.simple.JSONArray; 
import org.json.simple.JSONObject; 
import org.json.simple.parser.JSONParser; 
import org.json.simple.parser.ParseException; 

import javax.swing.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.FileReader; 
import java.io.IOException; 
import java.util.*; 


public class NewJFrame extends javax.swing.JFrame { 


    public static class Question { 
     public final int id; 
     public final String question; 
     public final String[] answers; 
     public int selectedAnswerIndex = -1; 

     public Question(int id, String question, String[] answers) { 
      this.id = id; 
      this.question = question; 
      this.answers = answers; 
     } 

     @Override 
     public String toString() { 
      return "Question{" + 
        "id=" + id + 
        ", question='" + question + '\'' + 
        ", answers=" + Arrays.toString(answers) + 
        '}'; 
     } 
    } 


    /** 
    * Creates new form NewJFrame 
    */ 
    public NewJFrame() { 
     initComponents(); 

     answerButtons.add(jButton1); 
     answerButtons.add(jButton2); 
     answerButtons.add(jButton3); 
     answerButtons.add(jButton4); 

     for (int i = 0; i < answerButtons.size(); i++) { 
      int localCopy = i; 
      answerButtons.get(i).addActionListener(new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        answerWasSelected(localCopy); 
       } 
      }); 
     } 
    } 


    /** 
    * 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() { 

     jLabelQuestion = new javax.swing.JLabel(); 
     jButton1 = new javax.swing.JButton(); 
     jButton2 = new javax.swing.JButton(); 
     jButton3 = new javax.swing.JButton(); 
     jButton4 = new javax.swing.JButton(); 
     jButtonNext = new javax.swing.JButton(); 

     setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

     jLabelQuestion.setFont(new java.awt.Font("Microsoft YaHei", 0, 48)); // NOI18N 
     jLabelQuestion.setText("jLabelQuestion"); 

     jButton1.setText("jButton1"); 
     jButton2.setText("jButton2"); 
     jButton3.setText("jButton3"); 
     jButton4.setText("jButton4"); 


     jButtonNext.setText("Next"); 
     jButtonNext.addActionListener(new java.awt.event.ActionListener() { 
      public void actionPerformed(java.awt.event.ActionEvent evt) { 
       jButtonNextActionPerformed(evt); 
      } 
     }); 

     javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
     getContentPane().setLayout(layout); 
     layout.setHorizontalGroup(
       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
         .addGroup(layout.createSequentialGroup() 
           .addGap(157, 157, 157) 
           .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
             .addComponent(jButton4) 
             .addComponent(jButton3) 
             .addComponent(jButton2) 
             .addComponent(jButton1)) 
           .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
         .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
           .addContainerGap(121, Short.MAX_VALUE) 
           .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
               .addComponent(jLabelQuestion) 
               .addGap(115, 115, 115)) 
             .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
               .addComponent(jButtonNext) 
               .addGap(18, 18, 18)))) 
     ); 
     layout.setVerticalGroup(
       layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
         .addGroup(layout.createSequentialGroup() 
           .addGap(29, 29, 29) 
           .addComponent(jLabelQuestion) 
           .addGap(49, 49, 49) 
           .addComponent(jButton1) 
           .addGap(18, 18, 18) 
           .addComponent(jButton2) 
           .addGap(18, 18, 18) 
           .addComponent(jButton3) 
           .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) 
           .addComponent(jButton4) 
           .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE) 
           .addComponent(jButtonNext) 
           .addContainerGap()) 
     ); 

     pack(); 
    }// </editor-fold> 


    private void answerWasSelected(int answerIndex) { 
     // process answer 
     // one of possible solutions 
     questions.get(currentQuestionIndex).selectedAnswerIndex = answerIndex; 

     showNextQuestion(); 
    } 

    private void jButtonNextActionPerformed(java.awt.event.ActionEvent evt) { 
     showNextQuestion(); 
    } 

    static List<Question> readQuestions(String fileName) throws IOException, ParseException { 
     JSONParser parser = new JSONParser(); 


     List<Question> questions = new ArrayList<>(); 
     try (FileReader fileReader = new FileReader(fileName)) { 
      JSONObject jsonObject = (JSONObject) parser.parse(fileReader); 
      JSONArray array = (JSONArray) jsonObject.get("data"); // it should be any array name 

      for (Object rawQuestion : array) { 
       JSONObject element = (JSONObject) rawQuestion; 

       String idStr = (String) element.get("id"); 
       String question = (String) element.get("soal"); 
       JSONArray jsonAnswers = (JSONArray) element.get("jawaban"); 
       ArrayList<String> answers = new ArrayList<>(); 
       for (Object rawAnswer : jsonAnswers) { 
        answers.add((String) rawAnswer); 
       } 
       Question q = new Question(Integer.parseInt(idStr), question, answers.toArray(new String[0])); 
       questions.add(q); 
       System.out.println(q); 
      } 
     } 
     return questions; 
    } 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String args[]) throws IOException, ParseException { 
    /* 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
      java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
     } 
     //</editor-fold> 

//  List<Question> questions = readQuestions("c:\\Matematika.json"); 
     List<Question> questions = readQuestions("Matematika.json"); 

     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       NewJFrame jFrame = new NewJFrame(); 
       // use setter to preserve a no-args constructor that is probably used by UI-designer 
       jFrame.setQuestions(questions); 
       jFrame.showFirstQuestion(); 
       jFrame.setVisible(true); 
      } 
     }); 
    } 

    public void setQuestions(List<Question> questions) { 
     this.questions = questions; 
    } 

    public void showFirstQuestion() { 
     showQuestion(0); 
    } 

    private void showNextQuestion() { 
     showQuestion(currentQuestionIndex + 1); 
    } 

    private void showQuestion(int questionIndex) { 
     currentQuestionIndex = questionIndex; 

     jButtonNext.setVisible(currentQuestionIndex < questions.size() - 1); //hide "Next" for last question 

     Question q = questions.get(questionIndex); 
     jLabelQuestion.setText(q.question); 
     for (JButton jButton : answerButtons) { 
      jButton.setVisible(false); 
     } 

     // and if there are more answers than question you'll get an exception :) 
     for (int i = 0; i < q.answers.length; i++) { 
      JButton jButton = answerButtons.get(i); 
      jButton.setText(q.answers[i]); 
      jButton.setVisible(true); 
     } 


    } 

    private int currentQuestionIndex; 
    private List<Question> questions; 
    private List<JButton> answerButtons = new ArrayList<>(); // list of all buttons for answers 

    // Variables declaration - do not modify 
    private javax.swing.JButton jButton1; 
    private javax.swing.JButton jButton2; 
    private javax.swing.JButton jButton3; 
    private javax.swing.JButton jButton4; 
    private javax.swing.JButton jButtonNext; 
    private javax.swing.JLabel jLabelQuestion; 
    // End of variables declaration 

} 

有些亂評:

  • 有是一種將文件中的數據讀入內存ListQuestion - 代表單個問題的簡單數據類的方法。注意所有的數據如何在手和輸入文件關閉之前被讀取(感謝「試用資源」糖在try (FileReader fileReader = new FileReader(fileName))
  • 上述問題列表設置爲NewJFrame對象(真是壞的名字,順便說一下)並顯示第一個問題
  • NewJFrame構造函數執行一些不能用典型的GUI設計器完成的事情:將所有「答案」按鈕分組到List中,並將幾乎相同的偵聽器附加到它們上面
  • 最後有showQuestion方法可以得到一個Question並配置UI(標籤和按鈕)來顯示它

希望這個存根將幫助你建立一個更易維護的應用程序