0

I wanted to create a "Please wait" animation while, my algorithm is running, that's what I did

            public void mouseClicked(MouseEvent arg0) {
                res.add(image);
                res.setVisible(true);

                String input = txtFind.getText();
                Engine engine = new Engine(input);
                engine.generate();
                List<String> s = engine.getList();

                res.remove(image);

                s.forEach(x -> {
                    JLabel txt = new JLabel(x);
                    res.add(txt);
                });

            }

The idea behind is to display my gif animation when I click on a button, then call my heavy function "generate", once done, I remove my animation and display the results,

However, Im getting another behavior : res becomes visible but without the animation, and then after some seconds (while generate is running) it displays the results.. I noticed that if I remove all my "res.add(txt)" and remove also "res.remove(image)" I still don't get the right behavior as it displays animation only after generate() finishes running and not at the same time.. It feels like the function is not runned sequentially

  • You don't appear to be running the long-running code, the `engine.generate();`, in a background thread. By not doing this, you're running this code on the Swing event thread, blocking this thread and freezing your GUI. Best to fix this. Have a look at [Concurrency in Swing](https://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html) for details on how to use a SwingWorker to help you do this correctly and for the details on Swing threading rules. – Hovercraft Full Of Eels Apr 27 '20 at 12:49
  • Side note: never use a MouseListener on a JButton in this way, but instead use an ActionListener. Otherwise if you later decide to disable the button, the listener will not be disabled automatically in parallel. – Hovercraft Full Of Eels Apr 27 '20 at 12:50
  • @HovercraftFullOfEels oh okay thank you I'm pretty new at creating graphics in Java ahah – Mehdi Zayene Apr 27 '20 at 12:51
  • @MehdiZayene You can look at this [example](https://stackoverflow.com/questions/52079885/java-loading-gif-freeze-while-processing-data "example") too for publishing some sort of progress. – George Z. Apr 27 '20 at 12:55

0 Answers0