Good day, I am having an issue trying to get the Text on a label to say ‘connecting …’ before the connection attempt starts and something else after it is connected. When the code below runs, the settext only displays once everything is complete. How can I get the first settext to display before the connection attempt?
private void buttonConnectActionPerformed(java.awt.event.ActionEvent evt) {
try {
String url = "jdbc:mysql://domain.com:3306/tablename";
String user = "username";
String password = "userpassword";
jLabel.setText("Connecting ...");
con = DriverManager.getConnection(url, user, password);
jLabel.setText(con.getCatalog());
} catch (SQLException ex) {
Logger.getLogger(connection.class.getName()).log(Level.SEVERE, null, ex);
}
}
The problem is that you are trying to connect to the database in your EventDispatcherThread which is basically the thread in charge of all the GUI items you have. The thread is taking it’s time to connect to the database and once it completes (ie. it connects to the database) it updates your GUI.
You can use something like this to get it to work:
I am assuming that
conis some global variable. In this case, for it to be accessible within therun()method, it needs to be declared asfinal.