简体   繁体   中英

Using JProgressBar in Java

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 a for 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.

丢弃它,并使用围绕连接输入流包装的javax.swing.ProgressMonitorInputStream

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM