JTextField 变量在动作侦听器之外返回 null?
我正在制作一个添加和格式化文件的程序。我实际上有很多课程,但出于这个问题的目的,我们假设我有两个课程,guidialog 和 guimain。
在 guidialog 中,我有一个 JTextField 和一个动作侦听器。这是动作监听器:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain();
blockAddWrite.addNewBlockFile();
}
});
public String blockName;
现在在 guimain 中,我有一个格式化程序,它根据文本字段中给出的名称写入文件:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
try {
newBlock = new Formatter("Block" + blockName.blockName + ".java");
System.out.println("Created File: Block" + blockName.blockName);
} catch (Exception e) {
System.out.println("ERROR: Could Not Output Block File");
}
}
我确实编辑并关闭了该文件,但这不是必需的。但是当我尝试这个时,guimain 中引用 blockName 的所有内容都输出为“null”。我想不通。
I'm making a program that adds and formats files. I actually have many classes, but for the purpose of this question let's say I have two, guidialog and guimain.
In guidialog I have a JTextField and an actionlistener for it. Here is the actionlistner:
public void actionPerformed(ActionEvent event) {
blockName=textFieldBlockName.getText();
System.out.println("Made new block: "+blockName);
canClose=true;
guimain blockAddWrite = new guimain();
blockAddWrite.addNewBlockFile();
}
});
public String blockName;
Now in guimain I have a formatter which writes a file based on the name given in the text field:
public void addNewBlockFile() {
blockdialog blockName = new blockdialog();
try {
newBlock = new Formatter("Block" + blockName.blockName + ".java");
System.out.println("Created File: Block" + blockName.blockName);
} catch (Exception e) {
System.out.println("ERROR: Could Not Output Block File");
}
}
I do edit and close the file, but it wasn't necessary. But when I try this, all of the stuff in guimain that refers to blockName outputs as "null". I can't figure it out.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为在 guimain 中,您没有使用用户输入内容的对话框的 blockName 字段:您正在使用另一个新建对话框的 blockName 字段:
您应该将 blockName 从对话框传递到 guimain:
旁注:
That's because in guimain, you're not using the blockName field of the dialog where the user entered something: you're using the blockName field of another, newly constructed dialog:
You should pass the blockName from the dialog to the guimain:
Side notes: