简体   繁体   English

JOptionPane自定义按钮返回字符串

[英]JOptionPane Custom Buttons to return String

I have a method getDate which returns String value. 我有一个方法getDate返回字符串值。 I'd like to add custom buttons but I can't because Eclipse tells me to change method type to int instead of String. 我想添加自定义按钮,但是不能,因为Eclipse告诉我将方法类型更改为int而不是String。 What can I do here? 我在这里可以做什么?

public String getDate(String info){
          return JOptionPane.showInputDialog(null, info, "Date insertion", JOptionPane.PLAIN_MESSAGE);
    }

This is how this InputDialog looks like: 此InputDialog如下所示:

IMAGE 图片

I want this dialog to have let's say Yes/No/Quit buttons and if I understand correctly, code like this should work: 我希望此对话框具有“是/否/退出”按钮,如果我理解正确,则这样的代码应该可以工作:

public String getDate(String info){
      return JOptionPane.showOptionDialog(null,info,
                "Date insertion", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,null,options,
                null);
}

But it says "cannot convert from int to String" and I need it to return String not int. 但是它说“无法从int转换为String”,我需要它返回String而不是int。

Have the class that invokes JOptionPane.showOptionDialog() get the integer that it returns, and use that to choose the string that you want to return. 让调用JOptionPane.showOptionDialog()的类获取它返回的整数,并使用该整数选择要返回的字符串。 You cannot change the showOptionDialog() method to return a string, but you can decide, based on the int that it returns, what string you want the caller to get. 您不能将showOptionDialog()方法更改为返回字符串,但是可以根据返回的int来确定希望调用者获取的字符串。 There's no need for a custom dialog. 无需自定义对话框。

public String getDate(String info)
{
  int[] optionStrings = { "Yes", "No", "Cancel" };
  int option = JOptionPane.showOptionDialog(null, info, "Date insertion",
                        JOptionPane.YES_NO_CANCEL_OPTION, 
                        JOptionPane.QUESTION_MESSAGE,null,options,
                        null);
  return optionStrings[option];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM