lundi 28 décembre 2020

Can a ActionListener class include other functionalities like driving the program?

I have 3 Java classes in my program that shows the user True or False questions using Swing GUI and gives the dialog if the answer is correct or not to the user. The questions and answers are in a single file.

1.a driver class TechTest that has the main method. In this method, it reads questions from file and populates the question and answer vector. public class TechTest {

static int numberOfQuestions = 0;
    
static int questionNum = 0;
static Vector  questionSet = new Vector();
static Vector answerSet = new Vector();
    
public static void main(String[] args) {
        // TODO Auto-generated method stub
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                String questionAnsFileName = readQuestionAnswerFileName();
                
                
                parseQuestionAnswerFile(questionAnsFileName);
                if (!noFile) {
                    if (!questionSet.isEmpty()) { 
                        View view = new View();
                        System.out.println("run: " + "questionNum " + questionNum); 
                        view.display((String) questionSet.get((questionNum)));
                    

                   }
                   else
                      showErrorDialog("questions are missing. Check the javaQuestionAns.txt file");
                
                   }
            }
        });

    }
} 
  1. The second class is View public class View { /* Shows the Swing GUI. Registers events to event listener class TestEngine */ ..... .....

    TestEngine testEngine = new TestEngine(this);

    buttonNext.addActionListener(testEngine); answerList.addActionListener(testEngine);

}

  1. Third class is TestEngine.

public class TestEngine implements ActionListener { /* * Check the source of the event, and handle the event accordingly * Possible sources are the answerList Combo box or the Next Button */ @Override public void actionPerformed(ActionEvent e) {

    if (e.getSource() == View.answerList) {
      ...
    }
    if (e.getSource() == View.buttonNext ) {
        ...
    }
 

}

The Test Engine class needs many static variables of the TechTest class. Many static variables are defined in the TechTest class. There are references to these static variables within Test Engine class.

Is this a good design? Or is it better to combine the functionalities of the driver TechTest class into the Test Engine class itself? In this new design, the Test Engine will have the main method driving the program, the actionPerformed method(event handlers) and other application logic that determines the correctness of answers and display of dialog.

Is it OK to combine the Action Listener function with the driver functionality and other application logic?

Aucun commentaire:

Enregistrer un commentaire