[英]JOptionPane YES/No Options Confirm Dialog Box Issue
I've created a JOptionPane
and it only has two buttons YES_NO_OPTION
. 我创建了一个
JOptionPane
,它只有两个按钮YES_NO_OPTION
。
After JOptionPane.showConfirmDialog
pops out , I want to click YES BUTTON
to continue opening the JFileChooser
and if I clicked NO BUTTON
it should cancel the operation. 弹出
JOptionPane.showConfirmDialog
后,我想点击YES BUTTON
继续打开JFileChooser
,如果我点击NO BUTTON
它应该取消操作。
It seems pretty easy but I'm not sure where is my mistake. 这似乎很容易,但我不确定我的错误在哪里。
Code Snippet: 代码片段:
if (textArea.getLineCount() >= 1) { //The condition to show the dialog if there is text inside the textArea
int dialogButton = JOptionPane.YES_NO_OPTION;
JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if (dialogButton == JOptionPane.YES_OPTION) { //The ISSUE is here
JFileChooser saveFile = new JFileChooser();
int saveOption = saveFile.showSaveDialog(frame);
if(saveOption == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(saveFile.getSelectedFile().getPath()));
fileWriter.write(textArea.getText());
fileWriter.close();
} catch(Exception ex) {
}
}
You need to look at the return value of the call to showConfirmDialog
. 您需要查看对
showConfirmDialog
的调用的返回值。 IE: IE:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
// Saving code here
}
You were testing against dialogButton
, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton
would never have been anything other than JOptionPane.YES_NO_OPTION
. 你正在测试
dialogButton
,你用它来设置对话框应该显示的按钮,而且这个变量从未更新过 - 所以dialogButton
永远不会是JOptionPane.YES_NO_OPTION
以外的任何东西。
Per the Javadoc for showConfirmDialog
: 根据
showConfirmDialog
的Javadoc:
Returns: an integer indicating the option selected by the user
返回:一个整数,指示用户选择的选项
Try this, 试试这个,
int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
System.out.println("Yes option");
} else {
System.out.println("No Option");
}
int opcion = JOptionPane.showConfirmDialog(null, "Realmente deseas salir?", "Aviso", JOptionPane.YES_NO_OPTION);
if (opcion == 0) { //The ISSUE is here
System.out.print("si");
} else {
System.out.print("no");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.