【发布时间】:2016-06-05 20:47:43
【问题描述】:
如果与 MySQL 的连接是 null 或 !null,我有一个 JLabel 必须更改 color 和 text。而且我正在尝试了解如何使其动态化,因此,当连接丢失时JLabel 会将颜色和文本更改为红色“未连接”。
例如:
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。循环.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();
}
【问题讨论】:
-
你可能想要Swing
Timer之类的东西
标签: java mysql while-loop connection