0

I would like to update a panel on my main frame (in class GUI) from my controller. Basically, the panel should be updated every simulation step.

    for (int step = 0; step < simSteps; step++){
         this.gui.updateGUI(this.stats, step);
    }

In my GUI class, the method updateGUI(...) looks like this:

 public void updateGUI(Stats stats, int step){
     this.stats = stats;
     getContentPane().remove(pollutionPanel);
     pollutionPanel = new BarPanel(settings, stats, possibleColors);
     getContentPane().add(pollutionPanel);
     validate();
     repaint();
 }

and my BarPanel class overrides the paintComponent method where I simply use a graphic object to paint a few things. When starting the simulation, the panel is only updated after the last simulation step although I already know that the updateGUI() method is called in every simulation step (I made some debugging outputs).

Does anyone have an idea why this is happening?

2
  • 1
    Welcome here. Please provide a runnable example in form of SSCCE Feb 8, 2017 at 11:10
  • Use either a SwingWorker or a Swing Timer to inject some kind of delay between updates Feb 8, 2017 at 20:30

2 Answers 2

2

So, basic concept, you want to generate some animation, where by the UI is updated over a period of time. Not an uncommon request, with plenty of examples.

Things to keep in mind:

  • Swing is single threaded
  • Don't do anything which might block the Event Dispatching Thread, this will prevent the UI from been update until such time that control is passed back to it
  • Don't update the UI from outside the context of the EDT

Okay, that sounds a little contradictive, but Swing provides a couple of tools to make your life easier

You could...

Use a SwingWorker

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.setSize(400, 400);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface StepContainer {

        public void addStep(int index);
    }

    public class TestPane extends JPanel implements StepContainer {

        private int step = 0;

        public TestPane() {
            setLayout(new GridBagLayout());
            PopulateWorker worker = new PopulateWorker(10, this);
            worker.execute();
        }

        @Override
        public void addStep(int step) {
            JButton btn = new JButton(Integer.toString(step));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(btn, gbc);
            revalidate();
            repaint();
        }

    }

    public class PopulateWorker extends SwingWorker<Void, Integer> {

        private int steps;
        private StepContainer parent;

        public PopulateWorker(int steps, StepContainer parent) {
            this.steps = steps;
            this.parent = parent;
        }

        @Override
        protected Void doInBackground() throws Exception {
            Thread.sleep(1000);
            for (int index = 0; index < steps; index++) {
                publish(index);
                Thread.sleep(1000);
            }
            return null;
        }

        @Override
        protected void process(List<Integer> chunks) {
            for (int step : chunks) {
                parent.addStep(step);
            }
        }

    }

}

Use a Swing Timer

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingWorker;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.setSize(400, 400);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public interface StepContainer {

        public void addStep(int index);
    }

    public class TestPane extends JPanel implements StepContainer {

        private int step = 0;

        public TestPane() {
            setLayout(new GridBagLayout());
            Timer timer = new Timer(1000, new PopulateAction(10, this));
            timer.start();
        }

        @Override
        public void addStep(int step) {
            JButton btn = new JButton(Integer.toString(step));
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(btn, gbc);
            revalidate();
            repaint();
        }

    }

    public class PopulateAction implements ActionListener {

        private int steps;
        private StepContainer parent;
        private int step;

        public PopulateAction(int steps, StepContainer parent) {
            this.steps = steps;
            this.parent = parent;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            parent.addStep(step);
            if (step == steps - 1) {
                ((Timer) e.getSource()).stop();
                step = 0;
            }
            step++;
        }
    }
}

Which you use will depend on the complexity of your problem, SwingWorker uses it's own Thread to call doInBackground, allowing you to process time consuming tasks, but provides the ability to update the UI safely.

Timer triggers it's updates within the context of the EDT, making it save to update the UI from, but not to perform time consuming tasks in

5
  • @KrzysztofCichocki It's hard been wrong - can you argue that my answer is the wrong approach or won't work for the user? Feb 10, 2017 at 8:31
  • You instruct Him to use excavator to plant single flower. And He is obviously confused, and don't know how to solve His problem anyway. Feb 10, 2017 at 8:37
  • @KrzysztofCichocki Both tools of the API are commonly used, neither are overly difficult and both will do what they are trying to do without violating the rules of EDT, if up-lifting someone's skills is a bad thing, that I'm guilty as charged. Both approaches are common solutions to any number of threaded related issues with Swing, which is why I suggested them, nothing wrong with invokeLater, but it's limited and doesn't scale well. Threading is a difficult concept to learn, learning what tools to use when is also a skill we should encourage. Feb 10, 2017 at 8:43
  • change at least one letter, can't vote again without your edit. Feb 13, 2017 at 9:41
  • @KrzysztofCichocki Yep, weird requirement :P Feb 13, 2017 at 10:11
0

If you update GUI very quickly, you don't see the intermediate changes, so add some pause beetween each step in loop like:

new Thread() {
  public void run() {
    for (int step = 0; step < simSteps; step++){
      this.gui.updateGUI(this.stats, step);
      try {
        Thread.currentThread().sleep(1000); // wait 1s before each step
      } catch (InterruptedException e) {
        e.printStackTrace();
      }       
    }
  } 
}.start();   


 public void updateGUI(final Stats stats, final int step){
   // the declaration of stats in this class should be marked as volatile like: 
   // private volatile Stats;
   this.stats = stats;
   EventQueue.invokeLater(new Runnable() {
     @Override
     public void run() {
       getContentPane().remove(pollutionPanel);
       pollutionPanel = new BarPanel(settings, stats, possibleColors);
       getContentPane().add(pollutionPanel);
       validate();
       repaint();
     }
   });
 }

Remeber also, that this loop above should not be run by EventThread, so you should not run this code directly in an ActionListener (eg. after JButton was pressed), but rather in the ActionListener.actionPerformed() create new Thread, that contains the above code in the run() method, then start such thread using yourThread.start(). You can alternatively use other way to run it in separate thread, but it is too broad topic to fit in scope of your question.

8
  • Swing is single threaded, if you block the Event Dispatching Thread, the entire UI will stop updating until such point as you control to the EDT, so based on your example, you will be taking step seconds before the UI is again updated. If you are thinking of updating the UI in a different thread then you will violating the single threaded nature of Swing, as Swing is not thread safe Feb 8, 2017 at 20:29
  • Yes, indeed. I already tried this. So, now, I am going to try out what MadProgrammer suggested. Seems so complicated for me ;-) But thanks for your answer
    – Truehnue
    Feb 9, 2017 at 11:51
  • @MadProgrammer He don't call any function that needs to be invoked directly by the EDT thread. AND programmers obviously can do GUI related tasks from other Threads - there is no violation of anything - maximum that this needs is proper synchroniztion, but swing in many cases just wraps these calls into runnalbe and send them to the EDT queue for execution. Also if you know what you're doing, you can write thread safe code - even for Swing. So kindly please take your downvote back Feb 10, 2017 at 8:16
  • @KrzysztofCichocki If the OP was NOT calling the code on the EDT, the they would violating the single threaded nature of Swing, as I pointed out to you, you also assume that I'm the one who downvoted you and if I was, you're lucky I was kind enough to point out to you why. If trying to help you improve your answer and give correct advice to the asker makes me an asshole, I'd hate think what giving bad advice makes you Feb 10, 2017 at 8:35
  • @KrzysztofCichocki "He don't call any function that needs to be invoked directly by the EDT thread" - Container#remove and Container#add and Container#validate all NOT thread safe, and as you have now correctly done, should be called from within the context of the EDT. As I said, either they risked blocking the EDT or violating the single threaded nature of it, either it "was" wrong Feb 10, 2017 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.