如果与MySQL的连接是JLabel
或null
,我的!null
必须更改颜色和文字。并且我试图了解如何使其动态化,因此,当连接丢失时,JLabel
会将颜色和文字更改为红色&#34;未连接&#34; 。< / p>
例如:
1.Connect.java
public class Connect {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/";
String dbName = "db_name";
String username = "user_name";
String password = "password";
Connection conn = null;
public Connection check(){
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, username, password);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
/////////////////////////////////
2。 Panel.java
public class Panel extends JPanel{
public Panel(){
//....lots of components and settings
JLabel label = new JLabel(); //the component we need...
}
Loop loop = new Loop(label);
}
/////////////////////////////////
3。 Loop.java
public class Loop{
Connect connect = new Connect();
JLabel label;
int x = 0;
public Loop(JLabel j){
label = j;
}
////////////////////////////////
while(x < 1){ //this is what i'm trying to do
if(connect.check() != null){
label.setText("Connected");
label.setForeground(Color.GREEN);
}else{
label.setText("Not Connected");
label.setForeground(Color.RED);
}
}
////////////////////////////////
}
4。主
public static void main(String[] args){
Panel panel = new Panel();
}
答案 0 :(得分:1)
您可以实施观察者模式。
Connect.java
asInstanceOf
Loop.java
public class Connect extends Observable {
Connection conn;
public Connect(Observer o) {
addObserver(o);
}
public void getConnection() {
// TODO getConnection
hasChanged();
notifyObservers();
}
public void closeConnection() {
// TODO closeConnection
hasChanged();
notifyObservers();
}
}
有用的链接: