0

裁剪代码如下。

我正在使用 Java 和 NetBeans。我已将两个字符串变量dbNamesucceededConnected声明为字段。

成功连接打印dbName

行,JOptionPane.showMessageDialog(null, successfullyConnected ); 打印“成功连接到空”而不是“成功连接到数据库”。

将文本直接放入参数中,JOptionPane.showMessageDialog(null, "Successfully connected to " + dbName ); , 打印所需的文本。

我的问题是,为什么使用字段存储字符串不起作用?为什么当我使用成功连接打印时dbName会恢复为 null ,但直接放在方法调用中时不会?

public class ABMain extends JFrame implements ActionListener {
    //Field
    ...
    private static String dbName;
    private static String successfullyConnected = "Successfully connected to " +dbName;


    //Constructor
    public ABMain() {
        ...
    }

    //Listener
    public void actionPerformed (ActionEvent e) {
        if (e.getSource() == item1) {
            dbName = JOptionPane.showInputDialog(requestDBName);
            try {
                stmt = ABDerbyConnection.createCon(dbName);
                JOptionPane.showMessageDialog(null, successfullyConnected); //echo for debugging
            } catch (SQLException ex) {
                ...
            }
            ...
        }  
    }

public static void main(String[] args) {
        new ABMain();
    }
}
4

3 回答 3

0

因为您successfullyConnected在用户输入之前初始化您的文本,当时dbNamenull. 在用户输入后初始化它

dbName = JOptionPane.showInputDialog(requestDBName);
successfullyConnected = "Successfully connected to " + dbName;
于 2013-11-11T13:09:17.857 回答
0

一旦初始化,这些值不会改变,除非你被修改。它们不是动态变量,并且没有绑定来检测更改的值。

 private static String dbName;
 private static String successfullyConnected = "Successfully connected to " +dbName;

你需要这样做。

private static String dbName;
private static String successfullyConnected = "Successfully connected to ";

stmt = ABDerbyConnection.createCon(dbName);
successfullyConnected = successfullyConnected +dbName; // See this line is added 
JOptionPane.showMessageDialog(null, successfullyConnected);
于 2013-11-11T13:09:33.590 回答
0

dbName初始化时始终为null successfullyConnected

private static String dbName;
private static String successfullyConnected = "Successfully connected to " +dbName;

我认为您不需要静态字段。

private String dbName;
private String successfullyConnected = "Successfully connected to ";

如果 dbName 已初始化,您可以将 dbName 添加到消息中:

    dbName = JOptionPane.showInputDialog(requestDBName);
    if(dbName!=null){
      OptionPane.showMessageDialog(null, successfullyConnected + dbName);
    } else {
      OptionPane.showMessageDialog(null, "Please choise one database");
    }
于 2013-11-11T13:10:13.787 回答