我创建了JOptionPane
类型showInputDialog
。当它打开时,它会显示两个按钮:确定和取消。当我按取消按钮时,我想处理动作,但我不知道如何触及它。我怎么能得到它?
答案 0 :(得分:24)
例如:
int n = JOptionPane.showConfirmDialog(
frame, "Would you like green eggs and ham?",
"An Inane Question",
JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
或者使用showOptionDialog
:
Object[] options = {"Yes, please", "No way!"};
int n = JOptionPane.showOptionDialog(frame,
"Would you like green eggs and ham?",
"A Silly Question",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]);
if (n == JOptionPane.YES_OPTION) {
} else if (n == JOptionPane.NO_OPTION) {
} else {
}
有关详细信息,请参阅How to Make Dialogs。
编辑:showInputDialog
String response = JOptionPane.showInputDialog(owner, "Input:", "");
if ((response != null) && (response.length() > 0)) {
}
答案 1 :(得分:6)
showMessageDialog不应显示两个按钮,因此您的代码或对其的解释会出现问题。无论如何,如果你想给用户一个选择并想要检测那个选择,不要使用showMessageDialog而是使用showConfirmDialog,并返回int并测试它以查看它是否为JOptoinPane.OK_OPTION。
答案 2 :(得分:2)
这是一个老问题,我是一个Java新手,所以可能有更好的解决方案,但我想知道相同的,也许它可以帮助其他人,我做的是检查响应是否为空。< / p>
这对我有用:
//inputdialog
JOptionPane inpOption = new JOptionPane();
//Shows a inputdialog
String strDialogResponse = inpOption.showInputDialog("Enter a number: ");
//if OK is pushed then (if not strDialogResponse is null)
if (strDialogResponse != null){
(Code to do something if the user push OK)
}
//If cancel button is pressed
else{
(Code to do something if the user push Cancel)
}
答案 3 :(得分:0)
package Joptionpane;
import javax.swing.JOptionPane;
public class Cancle_on_JOptionPane {
public static void main(String[] args) {
String s;
int i;
for (i=0;i<100;i++){
s = JOptionPane.showInputDialog(null,"What is your favorite fruit ?");
try {
if (s.equals("")) {
JOptionPane.showMessageDialog(null," Enter your answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=2;
} else {
JOptionPane.showMessageDialog(null," s = "+s," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Cancle answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
}
}
答案 4 :(得分:0)
你可以这样做:
>>> 1,2,3,4,5,6,7,8,9
>>> 10,11,12,13,14,15,16,17,18,19
>>> 20,21,23,24,25,26,27,28,29
答案 5 :(得分:-1)
这可能是你的答案:
package Joptionpane;
import javax.swing.JOptionPane;
public class Cancle_on_JOptionPane {
public static void main(String[] args) {
String s;
int i;
for(i=0;i<100;i++){
s = JOptionPane.showInputDialog(null,"What is your favorite fruit ?");
try{
if(s.equals("")) {
JOptionPane.showMessageDialog(null," Enter your answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=2;
}
else {
JOptionPane.showMessageDialog(null," s = "+s," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Cancle answer !!!"," ^-^ Information^-^ ",JOptionPane.INFORMATION_MESSAGE);
i=100;
}
}
}
}