dharam
dharam

Reputation: 8096

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("[email protected]");
    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();
    }
}

Upvotes: 0

Views: 412

Answers (1)

camickr
camickr

Reputation: 324078

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.

Upvotes: 4

Related Questions