(java) 循环检查连接

(java) Loop to check connection

我有一个 JLabel 必须更改 colortext 如果与 MySQL 的连接是null!null。我正在尝试了解如何使其动态化,因此,当连接丢失时 JLabel 会将颜色和文本更改为红色 "Not Connected".

例如:

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

您可以实现观察者模式

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

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

有用的链接: