JOptionPane是/否选项确认对话框问题-Java
我创build了一个JOptionPane
,它只有两个buttonYES_NO_OPTION
。
JOptionPane.showConfirmDialog
popup后,我想点击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
进行testing,你正在使用它来设置对话框应该显示的button,而且这个variables永远不会被更新 – 所以dialogButton
永远不会是除了JOptionPane.YES_NO_OPTION
之外的任何东西。
每个用于showConfirmDialog
的Javadoc:
返回:表示用户select的选项的整数
尝试这个,
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"); }