简体   繁体   中英

try to built a button in java netbeans

I am trying to make a program but i have a problem.I am trying to make the next button but it displays the last "soal" and the last "jawaban".I would like to see each soal when I press the next button.I upload this screenshot and my code

    /*
 * 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 file here:

{
"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

Your code is organized pretty badly. One obvious issue is that you trying to create UI inside iteration over input file. Although this approach can be made to work, usually it is terribly bad idea and this is the reason why you see only one question. Better approach would be to read data from the file first into some in-memory data-structure and then process it.

Another issue is that you need to understand that not everything should (or even could) be done using visual WYSIWYG designers. Whole bunch of separated jButton3ActionPerformed is a sure way to hell!

And why do you have two almost identical main methods?

And one more, I'm note sure where you've got your org.simple.json , I used one from https://code.google.com/archive/p/json-simple/downloads aka https://github.com/fangyidong/json-simple but I'd like to warn you that this is far from the most popular Java library for JSON

Having said that, this is some improvements over your code that are kinda work better:

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

}

Some random comments:

  • There is a readQuestions method that reads data from the file into the in-memory List of Question - simple data-only class that represents single question. Note how all data are read before hand and the input file is closed (thanks to "try-with-resources" sugar in try (FileReader fileReader = new FileReader(fileName))
  • The said list of questions in set into NewJFrame object (really bad name for class, by the way) and it is shown with first question
  • NewJFrame constructor does a few things that are can't be done with a typical GUI-designer: group all "answer" buttons into a List and attach almost the same listener to them.
  • Finally there is showQuestion method that can get a Question and configure UI (labels and buttons) to show it.

Hope this stub will help you build a more maintainable application

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM