简体   繁体   English

JProgressBar无法按预期工作

[英]JProgressBar not working as expected

I am trying to use this JProgressBar with a button. 我正在尝试通过按钮使用此JProgressBar。 I set the visibility of the ProgressBar to true on click of the button and in the same code I call a webservice. 单击按钮后,我将ProgressBar的可见性设置为true,并且在同一代码中,我将其称为Web服务。 Upon receipt of a response from the web service, I set the visibility of the progress bar to false. 收到来自Web服务的响应后,我将进度条的可见性设置为false。

Below is my code. 下面是我的代码。

Please help me fix this. 请帮我解决这个问题。 At present the ProgressBar appears only after teh response is received. 目前,ProgressBar仅在收到响应后出现。

 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. 您的代码在EDT上执行,因此GUI在任务完成之前无法重新绘制自身。

Read the Swing tutorial on How to Use Progress Bars for a working example that uses a SwingWorker. 阅读有关如何使用进度条的Swing教程, 获取使用SwingWorker的工作示例。

Also, read the tutorial on Concurrency for more information about the EDT. 另外,请阅读有关并发性的教程,以获取有关EDT的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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