簡體   English   中英

當使用“ try,catch”塊來處理異常時,如何在GUI上輸出錯誤消息?

[英]when using a 'try, catch' block to handle exceptions, how do I output an error message on a GUI?

我正在編寫一個GUI程序,並且正在使用“ try,catch”塊進行異常處理。 我知道您可以在catch塊中使用'System.out.print()'在控制台上輸出錯誤消息,但是如何在GUI上輸出錯誤消息呢?

我使用“ JLabel”創建了一條錯誤消息,並且我試圖通過在catch塊中放置一行代碼來將該標簽添加到JPane中,但是它無法正常工作,所以我有點卡在這里,我只能將錯誤輸出到最終用戶永遠不會看到的控制台。 任何幫助/建議都將不勝感激。

    errorMessage = new JLabel("<html><b>An error has occured. Please remember that you cannot enter alphabetic characters in any of the data fields, "
            + "also you cannot leave any of the fields blank and the probability data must be a decimal number less than '1' and greater than '0'</html>");
    errorMessage.setBounds(10,150,410,180);
    errorMessage.setFont(defaultFont);


    JButton beginSim = new JButton("Begin simulation");
    beginSim.setFont(defaultFont);
    beginSim.setBounds(10, 178, 160, 25);
    inputPane.add(beginSim);
    beginSim.addMouseListener(new MouseAdapter()
    {
        public void mouseClicked(MouseEvent e)
        {
            try
            {
                PlaneSimulator newSimulation = new PlaneSimulator(Integer.parseInt(txtLandingTime.getText()), Integer.parseInt(txtTakeoffTime.getText()), 
                    Double.parseDouble(txtLandingProb.getText()), Double.parseDouble(txtTakeoffProb.getText()), Integer.parseInt(txtTotalTime.getText()),
                        Integer.parseInt(txtCrashTime.getText()));
            }
            catch (NumberFormatException e1)
            {
                inputPane.add(errorMessage);    
            }
        }
    });

這可以通過顯示對話框消息來完成。 查看文檔 ,了解如何顯示dialog

編輯:

由於您不希望出現任何彈出窗口,因此可以在屏幕底部添加一個JTextArea,僅當出現任何錯誤時該JTextArea才可見,並且可以在此處顯示錯誤消息,

標簽已添加到面板中,但是除非以某種方式更改其寬度和高度之類的屬性(例如,調整/最小化/最大化面板所在的窗口),否則您將看不到面板的任何更改。

解決此問題的最簡單方法是在面板上調用revalidate ,這將驗證對面板所做的更改並使它對用戶可見。

catch (NumberFormatException e1)
{
    inputPane.add(errorMessage);
    inputPane.revalidate();
}

在某些情況下,您可能還需要repaint面板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM