I am creating a Java program emulating Windows 95, including its various components.
In Windows 95 in "My Computer", clicking the "Removable Disk" icon would cause a dialog box containing an error message to appear, and clicking "Retry" button will cause it to continuously reappear, until the user hits "Cancel" button or X.
I would like to achieve the effect as depicted in the following image, in which clicking "Retry" would make the dialog box continuously appear, until the user clicks "Cancel" or X to close it.
But the following code snippet I have written just would not work as expected. Specifically the while loop with break is not working as intended. The whole program would just freeze unexpectedly. There is no error in syntax found by Eclipse IDE. On a side note, removableDiskA is a JLabel ImageIcon object representing the icon of Removable Disk (A:); I used !=JOptionPane.YES_OPTION because I do not know the code for X for closing the dialog box, but I have to include both "Cancel" and X.
removableDiskA.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.getClickCount() == 2) {
UIManager.put("OptionPane.yesButtonText", "Retry");
UIManager.put("OptionPane.noButtonText", "Cancel");
int responseRemovableDiskA = JOptionPane.showConfirmDialog(null, "A: \\ is not accessible. \n\nThis device is not ready.",
"Removable Disk (A:)", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
while (responseRemovableDiskA == JOptionPane.YES_OPTION) {
if (responseRemovableDiskA != JOptionPane.YES_OPTION) break;
}
JOptionPane.showConfirmDialog(null, "A: \\ is not accessible. \n\nThis device is not ready.",
"Removable Disk (A:)", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE);
}
}
CodePudding user response:
Your while
loop condition and your break
condition are both exclusive.
This creates an infinite loop, hanging the application.
To achieve what you want, call back the showConfirmDialog
if the selected option is not what you expect.
int responseRemovableDiskA = JOptionPane.YES_OPTION;
do {
responseRemovableDiskA = JOptionPane.showConfirmDialog(null,
"A: \\ is not accessible. \n\nThis device is not ready.",
"Removable Disk (A:)",
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE);
} while (responseRemovableDiskA == JOptionPane.YES_OPTION);