0

I'm trying to get a JPanel to update repeatedly after a JButton gets clicked. I have a method called updatePanelGrid(), which is activated with a JButton ActionListener, and everything there works perfectly fine. I have another method called updatePanelGridVisual(), which calls updatePanelGrid() many hundreds of times, and is activated with a JButton ActionListener; however, it does not work so well. The goal is for it to update every 0.1 seconds in the same way as updatePanelGrid(), making kinda a little animation. (By the way, I'm new to Java.)

Here is the class method updatePanelGridVisual():

public void updatePanelGridVisual(JPanel panelGrid, ArrayList<Grid> backtrackingGrids) {
    new Thread() {
        @Override
        public void run() {
            for (int i=0; i<backtrackingGrids.size(); i++) {
                updatePanelGrid(panelGrid, backtrackingGrids.get(i));//Not working.
                System.out.println(backtrackingGrids.get(i));//For testing, prints fine.
                try {
                    //Pause for 0.1 seconds
                    Thread.sleep(100);//Time in milliseconds.
                } catch (InterruptedException ex) {
                    Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }.start();
}

Here is the JButton ActionListener, which resides inside the main:

button.addActionListener(
    new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            updatePanelGridVisual(panelGrid);
        }
    }
);

Everything is printing to the console exactly as I would expect it to, but when updatePanelGrid(panelGrid, backtrackingGrids.get(i)) is called, it will either do nothing or update only partially, creating only a portion of the grid that I have on panelGrid.

  • 1
    Thou shalt not access swing components from a thread other than the event dispatch thread. https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html. Use a swing timer. – JB Nizet Dec 19 '16 at 07:03
  • 1
    See also [*How to Use Swing Timers*](http://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html). – trashgod Dec 19 '16 at 10:35
  • I figured it out using some of the methods the answer for http://stackoverflow.com/questions/11058172/java-stopwatch-that-updates-the-gui-every-second – Shawn Elledge Dec 19 '16 at 19:07
  • Thanks both of you, that let me to it. – Shawn Elledge Dec 19 '16 at 19:07

0 Answers0