在;JOptionPane.showInputDialog";如果用户按escape或X按钮(Java Swing),则显示错误
我是java新手,我只想显示一条错误消息,如果用户在键盘上按escape键,或单击showInputDialog的X按钮,或按cancel,程序将正常关闭 就像现在,如果我关闭或取消inputDialog,它会出现以下错误 我还尝试抛出异常JVM,但它没有像我预期的那样工作,下面是我的代码:在;JOptionPane.showInputDialog";如果用户按escape或X按钮(Java Swing),则显示错误,java,swing,joptionpane,swingx,Java,Swing,Joptionpane,Swingx,我是java新手,我只想显示一条错误消息,如果用户在键盘上按escape键,或单击showInputDialog的X按钮,或按cancel,程序将正常关闭 就像现在,如果我关闭或取消inputDialog,它会出现以下错误 我还尝试抛出异常JVM,但它没有像我预期的那样工作,下面是我的代码: String userInput; BankAccount myAccount = new BankAccount(); while (true){ userInput = JOptionPane.
String userInput;
BankAccount myAccount = new BankAccount();
while (true){
userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
switch (userInput){
case "1":
myAccount.withdraw(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")),Double.parseDouble(JOptionPane.showInputDialog("Please Enter Amount to Withdraw: ")));
break;
case "2":
myAccount.deposit(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")),Double.parseDouble(JOptionPane.showInputDialog("Please enter Amount to Deposit: ")));
break;
case "3":
myAccount.viewBalance(Integer.parseInt(JOptionPane.showInputDialog("Please Enter ID: ")));
break;
case "4":
myAccount.exit();
System.exit(0);
default:
JOptionPane.showMessageDialog(null,"Invalid Input\nPlease Try Again");
break;
}
}
我只想在用户单击X或取消提示时显示一条错误消息,我如何捕获此消息?因此,我将在那里实现我的逻辑。如果用户单击“x”或“取消”按钮,showInputDialog将返回null而不是字符串。因此,不是:
while (true){
userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
switch (userInput){
case "1": ...
您可能希望执行以下操作:
while (true){
userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
if (userInput == null) {
JOptionPane.showMessageDialog(null, "Invalid Input\nPlease Try Again", "Cannot Cancel", JOptionPane.ERROR_MESSAGE);
continue;
}
switch (userInput){
case "1": ...
这将捕获cancel/'x'情况,continue将使其跳到while循环的下一个迭代,而不是在尝试使用带有null的switch语句时抛出错误。第11行可能存在重复的问题。我们不知道哪条语句是第11行。在代码中找到第11行,并确定该行中的哪个变量为null,然后修复该问题。我只想显示一条错误消息,如果用户单击X或取消提示,我如何捕获该消息?所以我将在这里实现我的逻辑
while (true){
userInput = JOptionPane.showInputDialog("1. Withdraw\n2. Deposit\n3. View Balance\n4. Exit");
if (userInput == null) {
JOptionPane.showMessageDialog(null, "Invalid Input\nPlease Try Again", "Cannot Cancel", JOptionPane.ERROR_MESSAGE);
continue;
}
switch (userInput){
case "1": ...