【问题标题】:(java) Loop to check connection(java) 循环检查连接
【发布时间】:2016-06-05 20:47:43
【问题描述】:

如果与 MySQL 的连接是 null!null,我有一个 JLabel 必须更改 colortext。而且我正在尝试了解如何使其动态化,因此,当连接丢失时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();
}

【问题讨论】:

标签: java mysql while-loop connection


【解决方案1】:

您可以实现观察者模式

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

有用的链接:

【讨论】:

  • 好点,先生!非常感谢你。这正是我想要的:)
猜你喜欢
  • 2014-02-27
  • 2021-12-14
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多