下面的裁剪代码。
我在Java和NetBeans工作。我已将两个String变量 dbName 和 successfulConnected 声明为字段。
成功连接打印 dbName 。
行 JOptionPane.showMessageDialog(null, successfulConnected ); 打印“成功连接到null”而不是“成功连接到数据库”。
将文本直接放在参数 JOptionPane.showMessageDialog(null,“成功连接到”+ dbName ); 中,打印所需的文本。
我的问题是,为什么使用字段存储字符串不起作用?当我使用 successfulConnected 打印时,为什么 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();
}
}
答案 0 :(得分:0)
因为您在用户输入之前初始化了successfullyConnected
文字,当时dbName
为null
。在用户输入后初始化
dbName = JOptionPane.showInputDialog(requestDBName);
successfullyConnected = "Successfully connected to " + dbName;
答案 1 :(得分: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);
答案 2 :(得分:0)
初始化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");
}