问题
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