0

所以,我正在创建一个简单的对话框来获取用户输入,但文本字段显示了两次。这是一个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());
}

在此处输入图像描述

这里的代码有什么问题?

4

2 回答 2

4

这样做是因为您JTextField也在message[].

Object[] message = {"File name", fileName};//sending filename as message

因此,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");
    }
于 2013-03-24T15:19:35.920 回答
2

输入对话框默认包含文本字段,因此您无需添加另一个。试试这种方式

String name = JOptionPane.showInputDialog(null, "File name",
        "Add New", JOptionPane.OK_CANCEL_OPTION);
System.out.println(name);
于 2013-03-24T15:23:44.993 回答