因此,我正在创建一个简单的对话框来获取用户输入,但文本字段显示两次。这是 SSCCE。
public static void main(String[] args) {
JTextField fileName = new JTextField();
Object[] message = {"File name", fileName};
String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
System.out.println(fileName.getText());
}
这里的代码有什么问题吗?
最佳答案
这样做是因为您还在 message[]
中添加 JTextField
对象。
Object[] message = {"File name", fileName};//将文件名作为消息发送
因此,显示的第一个 JTextField
是 inputDialog 中固有的一个,另一个是您自己作为消息发送的 JTextField
。
我猜你想将fileName
的内容发送到消息。在这种情况下,您的代码应该是这样的:
public static void main(String[] args) {
JTextField fileName = new JTextField();
Object[] message = {"File name", fileName.getText()};//send text of filename
String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
System.out.println(fileName.getText());
}
更新
如果您只想接受输入,则无需将对象 filename
作为消息发送。您只需按照以下步骤操作即可:
public static void main(String[] args) {
//JTextField fileName = new JTextField();
Object[] message = {"File name"};
String option = JOptionPane.showInputDialog(null, message, "Add New", JOptionPane.OK_CANCEL_OPTION);
if (option == null)
System.out.println("Cancell is clicked..");
else
System.out.println(option+ " is entered by user");
}
关于java - 文本字段在 JOptionPane.showInputDialog 中显示两次。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15600180/