On my current project i try to implement the MVC pattern and get mouse events in my model. I currently have: (removed some code to make it more readable)
My model
public class Game {
public void checkMouseEvents(ArrayList<MouseEvent> events){
for (MouseEvent mouseEvent : events) {
System.out.println(mouseEvent.getX() + "," + mouseEvent.getY());
}
}
}
My controller
public class GameController {
boolean notClosed = true;
GameView myView;
Game myGame;
boolean _running = true;
public GameController(){
myView = new GameView();
myGame = new Game();
Run();
}
public void Run(){
myGame.start();
while(notClosed){
checkActive();
if(_running)
{
myGame.checkMouseEvents(myView.getMouseEvents());
}
try {
Thread.sleep(1000/20);
} catch (Exception e) {
// TODO: handle exception
}
}
}
public void checkActive(){
_running = myView.getRunning();
}
}
my View
public class GameView implements ActionListener{
JFrame frame;
JButton button;
boolean _running = true;
MyDrawing drawing;
ArrayList<MouseEvent> mouseEvents;
public GameView(){
frame = new JFrame("Hunter");
button = new JButton(""+_running);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mouseEvents = new ArrayList<MouseEvent>();
drawing = new MyDrawing();
drawing.addMouseListener(new MouseAdapter() {// empty implementation of all
// MouseListener`s methods
@Override //I save the mouseclick in an array
public void mousePressed(MouseEvent e) {
mouseEvents.add(e);
}
});
frame.getContentPane().add(BorderLayout.SOUTH,button);
frame.getContentPane().add(BorderLayout.CENTER,drawing);
frame.setResizable(false);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
handleClick();
}
public boolean getRunning(){
return _running;
}
public void handleClick(){
if(_running)
_running = false;
else
_running =true;
frame.repaint();
}
public void Render(){
frame.repaint();
}
public ArrayList<MouseEvent> getMouseEvents(){
ArrayList<MouseEvent> copy = mouseEvents;
// command below returns the right amount
// System.out.println(copy.size());
mouseEvents.clear();
return copy;
}
}
So in short in my view i watch if the user clicks on a jpanel, if the user clicked save it in an array.
In my controller i do a while loop every 1/20th seconds where i pass the mouseclicks to my model.
In my model i try to log all mouse event positions.
I know i can improve the gameloop and that the thread is considered bad practice but it's not about the loop, its about passing the data.
However the program dosn't write the mouse locations. if i place a printLine in the checkMouseEvent I can see it is called. My question, how co i get the locations that i clicked in my view at a model when using the mvc pattern?