下面的裁剪代码。
我正在使用Java和NetBeans。我已经声明了两个字符串变量,dbName 和 成功连接,作为字段。
已成功连接打印 数据库名称。
该行 JOptionPane.showMessageDialog(null, 成功连接);打印"已成功连接到 null"而不是"已成功连接到数据库"。
将文本直接放入参数中,JOptionPane.showMessageDialog(null,"已成功连接到" + 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();
}
}
dbName
初始化时总是空的 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");
}
因为 您在用户输入之前初始化successfullyConnected
文本,此时dbName
null
. 在用户输入后初始化它
dbName = JOptionPane.showInputDialog(requestDBName);
successfullyConnected = "Successfully connected to " + dbName;
初始化后,除非修改,否则这些值不会更改。它们不是动态变量,并且没有用于检测更改的值的绑定。
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);