JOptionPane输入问题

时间:2013-12-14 02:22:31

标签: joptionpane

好的,所以我理解如果您想测试用户在JOptionPane中点击的内容,您可以执行以下操作:

final int option = JOptionPane.showConfirmDialog(null, "That file name does not exist.", "File Name", JOptionPane.OK_CANCEL_OPTION);

                if(option == JOptionPane.CANCEL_OPTION)
                {
                    g++;
                }

但是,如果我想将String =设置为这样的JOptionPane怎么办?

String fileName = JOptionPane.showInputDialog("File Name") + ".txt";

我应该如何比较用户点击的内容?

2 个答案:

答案 0 :(得分:0)

当您使用showInputDialog()时,您希望从文本字段中获取用户输入,而不是取决于用户点击的内容。

您可以使用带有输入字段的JOptionPane

String s = JOptionPane.showInputDialog(null, "Enter a message:); 

或者您可以使用组合框样式的JOptionPane

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                null,
                "Complete the sentence:\n"
                + "\"Green eggs and...\"",
                "Customized Dialog",
                JOptionPane.PLAIN_MESSAGE,
                null,
                possibilities,
                "ham");

编辑:

String s = JOptionPane.showInputDialog(null, "Enter a message:); 
if (s != null){     // OK is pressed with a value in the field
    // do something with s
}

答案 1 :(得分:0)

你可以像你提到的那样使用

String fileName = JOptionPane.showInputDialog("File Name");

默认输入对话框有OK按钮和取消按钮。因此,如果您按取消按钮 你的字符串值将为null 否则,它是您在文本字段中输入的值

所以你可以if(fileName == null) 检查用户是否单击了取消或确定按钮

String fileName = JOptionPane.showInputDialog("Enter file name");
if (fileName == null) {
      System.out.println("User pressed cancel");
      //your logic
}else{
      System.out.println(fileName);
      //your logic
}
相关问题