Som*_*ica 1 java swing awt jlabel
我有一个问题是JLabel使用类中的方法设置一个文本,从一个不同的类调用该方法创建GUI.设置的方法JLabel在GUI外部调用,但是当从GUI类内部调用时,它可以工作.getText()从GUI类外部调用后,我在标签上测试了该方法,并显示标签已更新.我知道它可能是Swing的油漆问题或更新问题,但我不知道该怎么做.我已经尝试repaint()并revalidate()在标签上,然后面板,它在内.这是我目前的代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
以及我称之为的背景.设置数据库连接
//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");
}
}
Run Code Online (Sandbox Code Playgroud)
任何有关这方面的帮助都很棒,或者如果你有一些建议的链接,那也很棒!谢谢您的帮助.
这是我的主要内容:
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
Run Code Online (Sandbox Code Playgroud)
您的问题可能是引用之一 - 您的GUI类中的mainwindow变量可能不是指正在显示的MainWindow对象.你new MainWindow();在代码中的其他地方打电话吗?如果是这样,那么你最好将对可视化MainWindow的引用传递给上面的这个类,这样你就可以调用它上面的方法来产生可以看到的东西.
例如,
public class DatabaseConnection {
// MainWindow mainwindow = new MainWindow(); *** don't do this ***
MainWindow mainwindow;
public DatabaseConnection(MainWindow mainwindow) {
this.mainwindow = mainwindow; // pass in the reference in the constructor
}
public void connect() {
Connection conn = null;
// ... etc
// now we can call methods on the actual visualized object
mainwindow.setStatusLabel("Connection");
}
Run Code Online (Sandbox Code Playgroud)