I’m teaching myself Java. I am a fairly proficient programmer in other languages, but this is the first OO language I’m doing.
I have a question that is a bit hard to summarize. Or it should be: how can I pass on an object (or variable) to an event listener?
I am writing an application in which you can play a Sudoku game. I have separated the “logic” or the “model”(the classes with Sudoku data structures and methods to manipulate them) from the presentation (the view and the controller).
The main method starts off as follows:
SudokuModel model = new SudokuModel(); SudokuView viewController = new SudokuViewController(model);
The first line creates class for the logic and the second line creates the class for the view and the controller. Since the view and the controller need access to the business logic, the model is passed on to the ViewController class.
The SudokuViewController class creates the user interface in Swing and it handles the user input. For the user input I have created a number of listeners, like this:
table.addKeyListener(this);
Now these listeners need access to the model since they update it. However, as far as I’m aware the only parameter passed on to an event listener is the event itself. So these event listeners do not have direct access to the model, even though it is passed on to the constructor of the class SudokuViewController.
To circumvent this, I made model2 an attribute (variable) of the class SudokuViewController. The constructor of the class sets this variable as follows:
model2 = model;
Now the event listeners have access to model2, which they can manipulate.
This works. However, I think it is an ugly solution, introducing an additional object (model2). How can I solve my problem without doing so? I’d like to pass on the object model to the event listener, but this doesn’t seem to be possible.