0

I have a JFrame class with this function inside:

o=1;
private String performTest(int i,File file) throws IOException, InterruptedException {
        //CRAPPY CODE  
               while(o<=20) {
               Thread.sleep(1000); 
               progressBar.setValue((o/20)*100);              
               o++;
               }
        //CRAPPY CODE
    }

So, the progress bar is supposed to be updated every second with a bigger value, but all I get is a just 1 final update (to 100), when function finishes it's work; Maybe there are some methods to fix this problem? Thank you anticipately. Full code.

   btnTesteaz.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int i = choice.getSelectedIndex();
            File file = fc.getSelectedFile();


            StringBuilder builder = new StringBuilder();        
            Thread t = new Thread(new Runnable() {
                @Override
                public void run() {

                        String name = Problems[i];
                        int o = 1;
                        try {

                        String pathToPas = file.getPath();
                        String pathToExe = pathToPas.replace(".pas", ".exe");
                        Process process = Runtime.getRuntime().exec("ppc386  "+pathToPas);
                        Thread.sleep(1000);
                        process.destroy();

                        while (new File("Res\\"+Problems[i]+"\\"+"Input"+o+".txt").exists()) { 
                            //FILES WITH INPUTS FROM RES
                            File in = new File("Res\\"+Problems[i]+"\\"+"Input"+o+".txt");
                            //FILES FOR .PAS
                            File inputtxt = new File(file.getParent()+"\\Input.txt");



                            BufferedReader bf = new BufferedReader(new FileReader(in));
                            PrintWriter w = new PrintWriter(new FileWriter(inputtxt));     
                            String s = null;
                            while ((s = bf.readLine())!=null)    {
                                w.println(s);
                            }
                            w.close();        
                            bf.close();
                            Process process1 = Runtime.getRuntime().exec(pathToExe,null, new File(file.getParent()));
                            Thread.sleep(1000);
                            process1.destroy();

                            File outputtxt = new File(file.getParent()+"\\Output.txt");
                            File out = new File("Res\\"+Problems[i]+"\\"+"Output"+o+".txt");
                            BufferedReader r1 = new BufferedReader(new FileReader(out)); 
                            BufferedReader r2 = new BufferedReader(new FileReader(outputtxt));                
                            StringBuilder ansRes = new StringBuilder();
                            StringBuilder ansPas = new StringBuilder();     
                                while ( (s=r1.readLine())!=null) ansRes.append(s);
                                while ( (s=r2.readLine())!=null) ansPas.append(s);

                            if (ansRes.toString().trim().equals(ansPas.toString().trim()))  {
                                builder.append("<p font color=green>"+(o)+". Test succesful </p> ") ;
                            }
                            else builder.append("<p font color=red>"+(o)+". Test failed </p>");
                            r1.close();
                            r2.close();

                               inputtxt.delete();
                               outputtxt.delete();

                               final int temp = o;
                               SwingUtilities.invokeLater(new Runnable() {
                                   public void run() {
                                       model.setValue((int) (((float) temp / 20.0f) * 100));
                                   }
                               });                               
                               o++;
                        }
                        File f = new File(pathToExe);
                        f.delete();
                        File fa = new File(file.getAbsolutePath().replace(".pas",".o"));
                        fa.delete();
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                }
            });
            t.run();
        Result.setText(builder.toString());
        }
    });
Cœur
  • 37,241
  • 25
  • 195
  • 267
Denis Rozimovschii
  • 428
  • 1
  • 6
  • 19

3 Answers3

2

This is a classic problem when in Swing. Swing makes all the graphic updates from its main thread, so you should not do long operations from there (you won't let it repaint!)

Try taking your long operation to another thread like in this tutorial:

https://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html

This will teach you how to make long time-consuming tasks in the background, while updating your UI in real time without messing with Swing architecture

Jorge_B
  • 9,712
  • 2
  • 17
  • 22
0

Adding to the Swing UI freeze problem, you are also deviding two integers which always rounds down to the nearest integer, so you're setting the progress bar to 0*100 every time except the last time when o == 20, so additionally to using a thread, typecasting o to float and deviding by 20.0f should do the trick:

private String performTest(...) {
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            int o = 1;
            while (o <= 20) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //Notice typecasts
                progressBar.setValue((int) (((float) o / 20.0f) * 100));

                o++;
            }
        }
    });
    t.run();
}
Marv
  • 3,517
  • 2
  • 22
  • 47
-1

Try to change int to double

double o=1;
final double max = 100.00;
final double per = 20.00
private String performTest(int i,File file) throws IOException, InterruptedException {
        //HAPPY CODE  
        while(o<=20) {
            Thread.sleep(1000); 
            progressBar.setValue( (int)((o/per)*max) );              
            o++;
        }
        //HAPPY CODE
 }
neferpitou
  • 1,642
  • 2
  • 20
  • 26