I have a TextArea Object, and I have SQL query running, I have the GUI unusable until the SQL query is finished, I would like to get the GUI refreshed meanwhile.

- 168,117
- 40
- 217
- 433

- 52
- 1
- 10
-
Please provide your [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve), So that we can help you on where to resolve your problem. – Praveen Aug 11 '18 at 23:30
-
Possible duplicate [Populating jTable using database data](https://stackoverflow.com/questions/15124904/populating-jtable-using-database-data/15125161#15125161) - I know, you have a `JTextArea`, the answer has a `JTable`, but the mechanism used to populate the `JTable` is what you should be using to keep the UI responsive – MadProgrammer Aug 11 '18 at 23:51
2 Answers
Your SQL query is running on the Event Dispatch Thread (EDT)
which is preventing the GUI from updating itself until the long running task is finished.
You need to run the query on a separate Thread
.
An easy way to do this is to use a Swing Worker
.
Read the section from the Swing tutorial on Concurrency for more information on the EDT
and for examples of using a SwingWorker
.

- 321,443
- 19
- 166
- 288
private String printCommandCalled(String argument) throws SQLException { String finalResult = ""; url = url.substring(0, 15 + port.length() + adress.length()).concat(currentDatabaseName + "?useSSL=false"); try { connection = (Connection) DriverManager.getConnection(url, userName, password); statement = (Statement) connection.createStatement(); resultSet = (ResultSet) statement.executeQuery("SELECT * FROM " + argument + ";"); } catch (SQLException e) { } int i = resultSet.getMetaData().getColumnCount();
//this is the try block that takes too long resulting the unresponsiveness of the gui
try {
while (resultSet.next()) {
for (int j = 1; j <= i; j++)
finalResult += resultSet.getObject(j) + " ";
finalResult += '\n';
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int k = 1; k <= i; k++)
finalResult += resultSet.getMetaData().getColumnName(k) + " ("
+ resultSet.getMetaData().getColumnTypeName(k) + ") ";
finalResult += '\n';
//this output is a string that will be shown in the JTextArea object
return finalResult;
}

- 52
- 1
- 10