Text Area not getting updated with the button action performed event

☆樱花仙子☆ 提交于 2019-12-24 12:43:44

问题


I have a Text Area swing element where I want to display some execution logs. messages should appear after each execution step. e.g. "Fetching has been started". But the problem is that all logs messages appear only once after the button action performed event is completed.Below is the way I used to display some text

getXmlButton = new JButton("Fetch Reports");
    getXmlButton.addActionListener((new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            createDirectory();
            stutusArea.append("Fetching has been started");
            final String password = passwordTextField.getText();
            final String username = loginTextField.getText();

            OperatingSystemDriver os = new OperatingSystemDriver();
            driver = os.getDriver();

            stutusArea.append("getting some url");
            driver.get(URL);



           try {
               LoginPage login = new LoginPage(driver);
               login.loginAs(username, password);
               stutusArea.append("successful login"); 
           } catch (Exception e1) {
               stutusArea.append("login error"); 
            }
    insertToDbButton.setEnabled(true);
        }
    }));

回答1:


You have to use a different thread, otherwise your GUI blocks.

Please note that updating the GUI from an other thread is a bad idea, use SwingUtilities.invokeLater to avoid some strange errors/bugs.

public void actionPerformed(ActionEvent e) {
    new Thread(new Runnable() {
        public void run() {
             SwingUtilities.invokeLater(new Runnable() {
                 public void run() {
                     stutusArea.append("Fetching has been started");
                 }
             })
             final String password = passwordTextField.getText();
             final String username = loginTextField.getText();
             // ...
        }
    }).start();
}



回答2:


That's because you do all your ActionPerformed stuff in the GUI thread, so the GUI freezes, and waits for your ActionPerformed stuff to be done, a way to avoid this is using Threads, there is an example: Thread Example



来源:https://stackoverflow.com/questions/15310862/text-area-not-getting-updated-with-the-button-action-performed-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!