Search code examples
javaswingjpaneljlayer

Jlayer in a Jpanel with circular loading bar


here is my exemple of making a circular loading bar with Jlayer but now the layer start and stop after the execution of the btnLoad.addActionListener() and stop after a while of determinated timer (4000) so my problem that I need it to start when I click the button load and stop after complete the loading of the file !!!

  final WaitLayerUI layerUI = new WaitLayerUI();

       jlayer = new JLayer<JPanel>(this, layerUI);

        final Timer stopper = new Timer(4000,new ActionListener() {
              public void actionPerformed(ActionEvent ae) {
                layerUI.stop();
              }
            });
            stopper.setRepeats(false);
          if (!stopper.isRunning()) {
            stopper.start();
          }
        btnLoad.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              layerUI.start();
              DataManager dataManager = new DataManager();
              try {
        dataManager.loadFromFile("C:/Users/*****PC/Downloads/****.csv");
            } catch (Exception e) {

                e.printStackTrace();
            }
            }
          }
        );

Solution

  • You should load the file on another Thread and not the Event Dispatch Thread. Assuming your loadFromFile method blocks until it loads the file, you can then hide the layer, but you must hide on the Event Dispatch Thread and not the new Thread you started for loading the file.

    Remove your timer and replace your try block with this:

        try {
            new Thread(new Runnable(){
                public void run() {
                    dataManager.loadFromFile("C:/Users/*****PC/Downloads/****.csv");
                    EventQueue.invokeLater(new Runnable(){
                        public void run() {
                            layerUI.stop();
                        }
                    });
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
        }