![](/img/trans.png)
[英]Why Confirm Dialog Box of JOptionPane is not taking action on clicking Yes/No button?
[英]JOptionPane YES/No Options Confirm Dialog Box Issue
我創建了一個JOptionPane
,它只有兩個按鈕YES_NO_OPTION
。
彈出JOptionPane.showConfirmDialog
后,我想點擊YES BUTTON
繼續打開JFileChooser
,如果我點擊NO BUTTON
它應該取消操作。
這似乎很容易,但我不確定我的錯誤在哪里。
代碼片段:
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) {
}
}
您需要查看對showConfirmDialog
的調用的返回值。 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
}
你正在測試dialogButton
,你用它來設置對話框應該顯示的按鈕,而且這個變量從未更新過 - 所以dialogButton
永遠不會是JOptionPane.YES_NO_OPTION
以外的任何東西。
根據showConfirmDialog
的Javadoc:
返回:一個整數,指示用戶選擇的選項
試試這個,
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.