我正在为学校制作一个程序,它使用JOptionPane / Dialog框将联系人插入到数组列表中以进行输入/输出。
我遇到的问题是取消和“X”按钮:当用户按下它们时,它们会使程序崩溃。
我想出了使用“返回”我可以停止该方法,并且这适用于第一个对话框,但如果输入信息并且用户进入下一个对话框,即使我再次使用返回,它也会崩溃。
所以基本上我想做的是如果用户按下cancel或“X”来转义当前方法,它将不会崩溃并返回main方法来执行其他进程。
此代码适用于第一个条目并成功退出程序:
while(nameError)
{
surname = JOptionPane.showInputDialog(null, "Enter a Surname");
if(surname == null)
{
return;
}
else
{
if(!(surname.matches(NamesTest)))
{
JOptionPane.showMessageDialog(null,errorMsg);
}
else nameError = false;
temp[0] = surname;
}
}
但是第二个对话框的方法中的下一行代码不是:
while(nameError1)
{
if(forename == null)
{
return;
}
else
{
forename = JOptionPane.showInputDialog(null, "Enter a Forename");
if(!(forename.matches(NamesTest)))
{
JOptionPane.showMessageDialog(null,errorMsg);
}
else nameError1 = false;
temp[1] = forename;
}
}
答案 0 :(得分:0)
这样的事情应该这样做:
import javax.swing.JOptionPane;
public class DialogExample {
public static void main(String[] args) {
new DialogExample().getNames();
}
private void getNames() {
String firstName = null;
String lastName = null;
while (firstName == null || firstName.length() == 0) {
firstName = getFirstName();
}
while (lastName == null || lastName.length() == 0) {
lastName = getLastName();
}
JOptionPane.showMessageDialog(null, "Hello " + firstName + " " + lastName);
}
private String getFirstName() {
String rtn = JOptionPane.showInputDialog(null, "Enter First Name");
if(rtn == null || rtn.length() == 0) {
JOptionPane.showMessageDialog(null, "Name cannot be empty");
}
return rtn;
}
private String getLastName() {
String rtn = JOptionPane.showInputDialog(null, "Enter Last Name");
if(rtn == null || rtn.length() == 0) {
JOptionPane.showMessageDialog(null, "Name cannot be empty");
}
return rtn;
}
}