How to paint/repaint/animate (MVC)

767 views Asked by At

Iam trying to write a program that animates Objects(fish,bubble,shark etc) using the MVC pattern.

The Model has a LinkedList with Objects with x and y values. The View has buttons to start and stop the animation. I added the buttons and a Jpanel to the JFrame in the View. But iam not sure how to draw/animate my Objects. The View looks like this:

  public class View extends JFrame {
.
.
.
   this.add(paintingSheet, BorderLayout.CENTER);
.
.
.
}


    public class PaintingSheet extends JPanel {
    private Image background;
    public PaintingSheet() {
        this.background = Toolkit.getDefaultToolkit().createImage("src/resources/background.jpg");
    }
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(this.background, 0,0, this);
    }
}

My plan was to make a Thread in the Controller to update the Objects in Model and repaint them. Something like this:

Model.updateOjects;
View.PaintingSheet.repaint();
Thread.sleep(x); 

1) is it allowed to call repaint in a Thread outside of the View?

2) are there better ways to do this?

3) how do i call repaint with the updated LinkedList from the Model?

4) how can i exclude the background from beeing repainted (it doesnt move)?

Thank you

2

There are 2 answers

0
StanislavL On
Thread.sleep(x);

blocks EDT and does not allow repainting.

Use javax.swing.Timer instead. move the code

Model.updateOjects;
View.PaintingSheet.repaint();

In the Timer's action (invoke inside actionPerformed() method).

0
trashgod On

Is it allowed to call repaint in a Thread outside of the View?

Trivially, yes; practically, no, as discussed here: "You still need to synchronize access to any data that is shared between threads." If your Model iterates in a fixed time that is comfortably less than your acceptable frame period, use javax.swing.Timer, as shown here. If not, iterate the Model in the doInBackground() of a SwingWorker, as shown here.