简体   繁体   中英

JProgressBar not working as expected

I am trying to use this JProgressBar with a button. I set the visibility of the ProgressBar to true on click of the button and in the same code I call a webservice. Upon receipt of a response from the web service, I set the visibility of the progress bar to false.

Below is my code.

Please help me fix this. At present the ProgressBar appears only after teh response is received.

 JButton testAPI = new JButton("Test API");
    testAPI.setBounds(OFFSET_X + 80, OFFSET_Y + 140, 120, 30);
    testAPI.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            prg.setVisible(true);
            String apiKey = apiKeyText.getText();
            testAPI(apiKey);
        }
});
 add(testAPI);

protected void testAPI(String apiKey) {

    StringBuilder sb = new StringBuilder(testQuery);
    sb.append("officialdharam@gmail.com");
    RestClient client = new RestClient();
    try {
        prg.setVisible(true);
        Response s = client.invoke(sb.toString(), HttpMethod.POST);
        prg.setVisible(false);
        System.out.println(s);
    }
    catch (URISyntaxException e) {
        e.printStackTrace();
    }
}

Your code is executed on the EDT so the GUI can't repaint itself until the task is finished.

Read the Swing tutorial on How to Use Progress Bars for a working example that uses a SwingWorker.

Also, read the tutorial on Concurrency for more information about the EDT.

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