Sob*_*lic 59 java swing jfilechooser
我创建了一个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) {
}
}
Run Code Online (Sandbox Code Playgroud)
zie*_*mer 107
您需要查看调用的返回值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
}
Run Code Online (Sandbox Code Playgroud)
您正在测试dialogButton
,您正在使用它来设置应该由对话框显示的按钮,并且此变量从未更新过 - 所以dialogButton
除了之外永远不会有任何变化JOptionPane.YES_NO_OPTION
.
根据Javadoc showConfirmDialog
:
返回:一个整数,指示用户选择的选项
小智 32
试试这个,
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");
}
Run Code Online (Sandbox Code Playgroud)
小智 6
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");
}
Run Code Online (Sandbox Code Playgroud)