Search code examples
javaswinginvokelaterswingutilities

GUI JButton Not Updating On Time


I'm working with code that is essentially a file mover program. What I'm attempting to do is after the user clicks the submit button which calls the file mover, the text of the button would change to 'Working'. I have a basic understanding of why it didn't work when I just set it, but I tried to use SwingUtilities to call it in the background. However, it still waits until after the method call ft.FindSpot has completed before displaying any changes.

            public void actionPerformed(ActionEvent arg0) {
            if(!textField.getText().equals(""))
            {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        btnSubmit.setText("Working...");
                    }
                });
                //btnSubmit.setText("Working...");
                ft.FindSpot(textField.getText(), comboBox.getSelectedItem().toString(), progressBar);

                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        btnSubmit.setText("Submit");
                    }
                });
            }
            else
            {
                ft.warningMessage("The ISCII textbox cannot be blank.");
            }
        }
    });

Solution

  • I managed to fix the issue by putting the ft.FindSpot in the invokeLater Swing Utilities function so that it was called from a different thread.

            btnSubmit.setFont(new Font("Verdana", Font.PLAIN, 12));
        btnSubmit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                if(!textField.getText().equals(""))
                {
                 btnSubmit.setText("Working...");
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            ft.FindSpot(textField.getText(), comboBox.getSelectedItem().toString(), progressBar);
                        }
                    });
    
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            btnSubmit.setText("Submit");
                        }
                    });
                }
                else
                {
                    ft.warningMessage("The ISCII textbox cannot be blank.");
                }
            }
        });