gpt4 book ai didi

java - (java) 循环检查连接

转载 作者:行者123 更新时间:2023-11-29 11:42:13 25 4
gpt4 key购买 nike

如果与 MySQL 的连接为 null 或,我有一个 JLabel 必须更改颜色文本 !null。我正在尝试了解如何使其动态化,以便在连接丢失时 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.面板.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();
}

最佳答案

您可以实现观察者模式

连接.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();
}
}

循环.java

public class Loop implements Observer {

Connect connect;

public Loop() {
connect = new Connect(this);
}

// Called when notifyObservers() is fired
@Override
public void update(Observable o, Object arg) {
Connect connect = (Connect) o;
try {
if(connect.conn.isClosed()) {
// --------
} else {
// --------
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

有用的链接:

关于java - (java) 循环检查连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com