我想知道inputdialog如何返回值,尤其是当还有ok和cancel按钮时。 有人可以解释它如何设法返回价值?
更新:
让我这样说吧。 我想创建一个包含6个按钮的对话框,每个按钮返回不同的值。 我希望它得到这样的价值: String value = MyDialog.getValue(); //喜欢showInputDialog
问题是我如何在按下按钮时返回值?
答案 0 :(得分:2)
Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
frame,
"Complete the sentence:\n"
+ "\"Green eggs and...\"",
"Customized Dialog",
JOptionPane.PLAIN_MESSAGE,
icon,
possibilities,
"ham");
//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
setLabel("Green eggs and... " + s + "!");
return;
}
您可能希望熟悉“从对话框中获取用户输入”部分
您还应该熟悉同一主题的Java Docs
答案 1 :(得分:2)
现在我已经更清楚地了解了你的目标,我认为不是试图模仿JOptionPane,而是给每个按钮一个不同的actionCommand更容易:
private JDialog dialog;
private String inputValue;
String showPromptDialog(Frame parent) {
dialog = new JDialog(parent, true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// [add components to dialog here]
firstButton.setAction(new ButtonAction("Button 1", "first"));
secondButton.setAction(new ButtonAction("Button 2", "second"));
thirdButton.setAction(new ButtonAction("Button 3", "third"));
fourthButton.setAction(new ButtonAction("Button 4", "fourth"));
fifthButton.setAction(new ButtonAction("Button 5", "fifth"));
sixthButton.setAction(new ButtonAction("Button 6", "sixth"));
dialog.pack();
dialog.setLocationRelativeTo(parent);
inputValue = null;
dialog.setVisible(true);
return inputValue;
}
private class ButtonAction
extends AbstractAction {
private static final long serialVersionUID = 1;
ButtonAction(String text,
String actionCommand) {
super(text);
putValue(ACTION_COMMAND_KEY, actionCommand);
}
public void actionPerformed(ActionEvent event) {
inputValue = event.getActionCommand();
dialog.dispose();
}
}