![](/img/trans.png)
[英]how do I use a try/catch block on a GUI to test out methods on a Deck Class
[英]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.