2016-05-14 113 views
-1

我正在研究一個簡單的Java應用程序。我有拋出異常的問題。線程中拋出錯誤(異常)

實際上,應該在線程中拋出異常。所以有這些例外的線程:

public void setVyplata(Otec otec) { 

    try { 
     otec.setVyplata(Integer.parseInt(textField1.getText())); 

    } catch (NumberFormatException e) { 
     JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE); 
     otec.setVyplata(0); 
     textField1.setText("0"); 
    } 

} 

public void setVyplata(Mama mama) { 

    try { 
     mama.setVyplata(Integer.parseInt(textField2.getText())); 

    } catch (NumberFormatException e) { 

     JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE); 
     mama.setVyplata(0); 
     textField2.setText("0"); 
    } 
} 

這是可能的,兩個例外將同時拋出。

而且當它,這就是我得到:

empty error message.... and my application stop working. i must close it trough task manager.

我有線程運行的每個方法。我的問題是爲什麼程序會停止在這裏工作。因爲,當我分開啓動這些線程之一。它完美地工作。當我開始這兩個線程應該有2個錯誤窗口,但你可以看到空白的錯誤窗口和程序無法正常工作。

+3

你的問題是什麼? – Vijay

+0

是不是你有一個針對每種方法運行的線程,並且你需要在某個地方得到這個異常,或者你只需​​要知道你是否有兩個對話?或者進一步說,當兩個線程都在運行時,你實際上是想在同一個對話中捕獲這兩個錯誤? –

+0

你爲了不中斷程序的執行而捕獲異常,所以當你捕捉到異常時你只會中斷那個方法的執行,你有兩種不同的方法,所以你會捕獲兩個不同的異常 –

回答

1

我可以明確告訴你,根據你以前的評論,你有一個問題,沒有線程安全擺動組件的特點。您應該閱讀The Event Dispatch Thread文檔。您需要使用調用方法來確保您的更改任務放置在事件派發線程上,否則,您的應用程序會崩潰。

爲您的代碼示例:

public void setVyplata(Otec otec) { 

    try { 
     otec.setVyplata(Integer.parseInt(textField1.getText())); 

    } catch (NumberFormatException e) { 

     SwingUtilities.invokeLater(() -> { 
      JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE); 
      otec.setVyplata(0); 
      textField1.setText("0"); 
     }); 

    } 

} 

public void setVyplata(Mama mama) { 

    try { 
     mama.setVyplata(Integer.parseInt(textField2.getText())); 

    } catch (NumberFormatException e) { 

     SwingUtilities.invokeLater(() -> { 
      JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE); 
      mama.setVyplata(0); 
      textField2.setText("0"); 
     }); 
    } 
} 

如果SwingUtilities類的文檔中查找你有什麼invokeLater一個很好的解釋其實就是做:

導致doRun.run()來在調度線程的AWT事件 上異步執行。在處理了所有待處理的AWT事件 之後,會發生這種情況。應用程序線程 需要更新GUI時應使用此方法。在以下示例中,invokeLater調用 會將事件調度 線程中的Runnable對象doHelloWorld排隊,然後打印消息。

+2

非常感謝:)這節省了我的一天:) –