2016-03-22 11 views
0

私は、JOptionPane /ダイアログボックスを使用して連絡先を配列リストに挿入する学校向けのプログラムを作成しています。メソッドの特定のポイントでコードを停止する

私が抱えている問題は、キャンセルボタンと「X」ボタンがあることです。ユーザーが押すと、プログラムがクラッシュします。
私は方法を止めることができました。最初のダイアログボックスでは機能しましたが、情報が入力されて次のダイアログボックスに進むと、リターンを再度使用していてもクラッシュします。

基本的に私がしたいのは、キャンセルまたは "X"を押して現在のメソッドをエスケープし、クラッシュせずに他のプロセスを実行するメインメソッドに戻る場合です。

このコードは、最初のエントリのために働き、プログラムを正常に終了します。

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; 
} 
} 

が、2番目のダイアログボックスdoesntのためのメソッドのコードの次の行:

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

このような何かそれを行う必要があります:

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; 
    } 

} 
+0

おそらく理由を説明できますか? –