0

I am writing a program, which is supposed to update and render animation for each frame. I have an AnimationPanel class which extends JPanel and an Animation class, which maintains my animation with an infinity loop. I was invoking paintComponent method by JPanel's paintImmediately method from animation (Animation object) and everything was working fast and well, until I added a new component to the JFrame. Then, components started to overlap one another, because new components were working on the EDT thread, but my animation was working on the main thread and somehow it was calling paintImmediately and then paintComponent also in the main thread, but of course it shouldn't. I tried to put the paintImmediately part of code to EDT thread and it worked, but the performance was really poor (instead of >100fps only ~40fps) and animation started lagging and it was behaving the same way as if it was repaint() method instead. So I guess I did something wrong, but I totally don't know what.
The paintComponent method looks like this:

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    animation.render(g2d);
}

and render method look like this:

public void render(Graphics2D g2d) {
    objects.forEach((o) -> o.render(g2d));
}

Each object has its own render method, which usually is g2d.fill(/*object's shape*/)

The render() method called by loop:

private void render() {
    //It calls paintComponent in the main thread
    panel.paintImmediately(0, 0, panel.getWidth(), panel.getHeight());
}

and its modification which was laggy:

private void render() {
    //It calls paintComponent int the EDT thread
    SwingUtilities.invokeAndWait(()->panel.paintImmediately(0, 0, panel.getWidth(), panel.getHeight()));
}

Thank you for your help!

4

0 回答 0