Java代码重组

Java code restructuring

随着我的小程序的进展,我有 4 个按钮,它们遵循相同的规则,我不知道如何减少代码,我几乎可以肯定它可以简化:

private void initGame(Quizz quizz) {

    jLabelScore = new javax.swing.JLabel();
    jLabelComptQ = new javax.swing.JLabel();
    jButtonA = new javax.swing.JButton();
    jButtonB = new javax.swing.JButton();
    jButtonC = new javax.swing.JButton();
    jButtonD = new javax.swing.JButton();

    int i = quizz.aleatQuestion();
    ArrayList<Reponse> listeRep = quizz.showAnswer(i);
    Reponse reponseA = listeRep.get(0);
    Reponse reponseB = listeRep.get(1);
    Reponse reponseC = listeRep.get(2);
    Reponse reponseD = listeRep.get(3);

    jButtonA.setText(reponseA.getReponse());
    jButtonB.setText(reponseB.getReponse());
    jButtonC.setText(reponseC.getReponse());
    jButtonD.setText(reponseD.getReponse());
    jLabelScore.setText("Score : " + quizz.getScore());
    int a = quizz.getCompteurQ()+1;
    jLabelComptQ.setText("Question n°" + a);

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("Jeu en Cours - StudenTest");
    setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    setMaximumSize(new java.awt.Dimension(800, 600));
    setMinimumSize(new java.awt.Dimension(800, 600));
    setResizable(false);
    setSize(new java.awt.Dimension(800, 600));
    getContentPane().setLayout(null);
    getContentPane().removeAll();

    getContentPane().add(jLabelScore);
    jLabelScore.setBounds(0, 20, 250, 250);
    jLabelScore.setVerticalAlignment(SwingConstants.TOP);

    getContentPane().add(jLabelComptQ);
    jLabelComptQ.setBounds(0, 0, 250, 250);
    jLabelComptQ.setVerticalAlignment(SwingConstants.TOP);

    jButtonA.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (reponseA.getVerif()) {
                quizz.win();
            } else {
                quizz.lose();
            }
            quizz.endOfTurn();
            if (quizz.getCompteurQ() >= 5) {
                Component frame = null;
                JOptionPane.showMessageDialog(frame, "Score Final :" + quizz.getScore() + "\nBien Joué");
                initComponents();
            } else {
                initGame(quizz);
            }
        }

    });
    getContentPane().add(jButtonA);
    jButtonA.setBounds(425, 325, 150, 75);

    jButtonB.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (reponseB.getVerif()) {
                quizz.win();
            } else {
                quizz.lose();
            }
            quizz.endOfTurn();
            if (quizz.getCompteurQ() >= 5) {
                Component frame = null;
                JOptionPane.showMessageDialog(frame, "Score Final :" + quizz.getScore() + "\nBien Joué");
                initComponents();
            } else {
                initGame(quizz);
            }
        }
    });
    getContentPane().add(jButtonB);
    jButtonB.setBounds(225, 325, 150, 75);

    jButtonC.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (reponseC.getVerif()) {
                quizz.win();
            } else {
                quizz.lose();
            }
            quizz.endOfTurn();
            if (quizz.getCompteurQ() >= 5) {
                Component frame = null;
                JOptionPane.showMessageDialog(frame, "Score Final :" + quizz.getScore() + "\nBien Joué");
                initComponents();
            } else {
                initGame(quizz);
            }
        }
    });
    getContentPane().add(jButtonC);
    jButtonC.setBounds(425, 450, 150, 75);

    jButtonD.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (reponseD.getVerif()) {
                quizz.win();
            } else {
                quizz.lose();
            }
            quizz.endOfTurn();
            if (quizz.getCompteurQ() >= 5) {
                Component frame = null;
                JOptionPane.showMessageDialog(frame, "Score Final :" + quizz.getScore() + "\nBien Joué");
                initComponents();
            } else {
                initGame(quizz);
            }
        }
    });
    getContentPane().add(jButtonD);
    jButtonD.setBounds(225, 450, 150, 75);

    pack();

    setLocationRelativeTo(null);
}

您可以看到 reponseA/B/C/D 和 jButtonA/B/C/D 遵循相同的指令。 我回顾了我的课程,但我没有找到任何解决这个问题的帮助,即使它对我有很大帮助。 我曾尝试进行在线研究,但它不相关或解决方案不适合... 我希望你能理解我说的(我英语不流利)。

Ps: 我已经放了方法的所有代码,但如果需要我可以删除不是完全必要的部分。

你要找的其实是code refactoring,所以你需要搜索how to重构代码?

您需要 refactor 您的代码并编写 单一职责 classes 和更小的方法 以便它可以更好 understandable/readable/supportable.

首先,您可以将所有 MouseListener 实现到单独的 class 中,如下所示:

public class ButtonAMouseListener implements java.awt.event.MouseAdapter {
     //implement ButtonA MouseListener code here
}

public class ButtonBMouseListener implements java.awt.event.MouseAdapter {
     //implement ButtonB MouseListener code here
}

public class ButtonCMouseListener implements java.awt.event.MouseAdapter {
     //implement ButtonC MouseListener code here
}

public class ButtonDMouseListener implements java.awt.event.MouseAdapter {
     //implement ButtonD MouseListener code here
}

现在,为这些 class 创建对象并在原始 class 中使用它们。

减少代码的最好方法是将组件分组到数组中,这样您就可以使用 for 完成相同的任务(添加、命名、创建、添加侦听器)当然这并不总是被推荐,或者可能,因为 UI 可以有很多不同类型的按钮,在你的情况下可以将按钮分组在一个数组中,我也会使用 actionsPerformed 而不是 MouseEvent

JButton jButtons[] = new javax.swing.JButton[4];

for(int i=0;i<4;i++){
 jButtons[i] = new javax.swing.JButton();
 jButtons[i].setText(listeRep.get(i).getReponse());
 jButtons[i].setActionCommand(""+i);
 jButtons[i].addActionListener(new ActionListener() { 
 public void actionPerformed(ActionEvent e) { 
  System.out.println("Button Pressed");
   switch (e.getActionCommand()) {
        case "0":
            //response A
            break;
        case "1":
            //reponse B
            break;
        case "2":
            //response C
            break;
        case "3":
            //Response D
            break;
        default:
            break;

  } 
});

 getContentPane().add(jButtons[i]);
 jButtons[i].setBounds(425, 325+i*75, 150, 75);
}