I have an issue setting a JLabel‘s text using a method in the class creating the GUI from a different class calling that method. The method to set the JLabel is called outside the GUI but when called from inside the GUI class it works. I have tested the getText() method on the label after it is called from outside the GUI class and it shows that the label has been updated. I get that it is probably a paint issue or update issue with Swing but I’m at a loss of what to do. I have tried repaint() and revalidate() on the label and then panel that it is within. Here is my current code:
public void setStatusLabel(String statusEntered) {
//Shows the variable statusEntered has been received
System.out.println(statusEntered);
//Not working
status_label.setText(statusEntered);
//Used this to check if the label receives the data. It does.
String status = status_label.getText();
System.out.println(status);
}
And the context in which I am calling it. Setups a database connection
//GUI Class reference
MainWindow mainwindow = new MainWindow();
public void connect(){
Connection conn = null;
try {
String userName = "root";
String password = "";
String url = "jdbc:mysql://localhost:3306";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, password);
//This works
System.out.println("Connection Established");
//The issue is with this guy
mainwindow.setStatusLabel("Connection");
}
catch(Exception e) {
System.err.println("Failed to connect to database");
mainwindow.setStatusLabel("No connection");
}
}
Any help with this would be awesome or if you have some links to suggestions, that would be awesome too! Thanks for the help.
Here is my main:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
Your problem is possibly one of reference — your mainwindow variable in your GUI class may not be referring to the MainWindow object that is being displayed. Do you call
new MainWindow();anywhere else in your code? If so, then you’d best pass a reference to the visualized MainWindow into this class above so that you can call methods on it that will result in something that can be seen.For e.g.,