0

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

mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • I would suggest to do the calculation about the current position of the object, whenever your paint method is called. This will make your animation smoother, than to update the model repeatedly. (Only possible, if the calculations can be done real fast) – slartidan Jun 20 '15 at 18:23

2 Answers2

3
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).

StanislavL
  • 56,971
  • 9
  • 68
  • 98
2

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.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045