0

I am making a app that takes data from an API, but it takes some time(like some 1 or 2 seconds), I want to use JProgressBar to show how much of the data is downloaded, here is my code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String snum;
        try
        {
            curfrom=(String)fromList.getSelectedItem();
            curto=(String)toList.getSelectedItem();
            snum=curval.getText();
            address="http://rate-exchange.appspot.com/currency?from="+curfrom+"&to="+curto+"&q="+snum;
            url=new URL(address);
            connect=url.openConnection();
            br=new BufferedReader(new InputStreamReader(connect.getInputStream()));
            output=br.readLine();
            String[] split = output.split("\"");
            res=split[12];
            res=res.replace(" ", "");
            res=res.replace(":", "");
            res=res.replace("}", "");
            result.setText(snum+" "+curfrom+" = "+res+" "+curto);
        }
        catch(Exception e)
        {
            result.setText("Error! Please check the Problem(e.g. Net)");
            JOptionPane.showMessageDialog(null, "An Error has Occured!", "Error!", JOptionPane.ERROR_MESSAGE);
        }
    }

I thought of making a progress bar that will load and show it value using JProgressBar.setStringPainted(true), but when I update it using afor loop like:

for(i=0;i<=100;i+=10)
{
    bar.setValue(i);
    try 
    {
        Thread.sleep(100);
    } 
    catch (InterruptedException ex) 
    {
        Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
    }
 }

But when I run this code, and it starts loading, it appears hung for 100 miliseconds and then loads, I cannot see the animation which I think should have be shown by this code. I want to see the animation happening.

Thanks in advance.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Ved
  • 389
  • 3
  • 7
  • 16
  • 3
    Don't call Thread.sleep. Use a [`SwingWorker`](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) – Paul Samsotha Jan 05 '14 at 08:04
  • 3
    First, take a look at [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/), in particular [Worker Threas and SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) and [this](http://stackoverflow.com/questions/20739488/swingworker-in-multithreaded-jframes/20739571#20739571) for an example – MadProgrammer Jan 05 '14 at 08:05

1 Answers1

1

Throw it away and use a javax.swing.ProgressMonitorInputStream wrapped around the connection input stream.

user207421
  • 305,947
  • 44
  • 307
  • 483