简体   繁体   中英

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

I'm writing a GUI program and I'm using a 'try, catch' block to do exception handling. I know that you can use a 'System.out.print()' inside the catch block to output an error message on the console, but how do you output an error message on the GUI?

I used 'JLabel' to create an error message, and I'm trying to add that label to my JPane by putting a line of code inside of the catch block but it's not working so I'm kind of stuck here, I can only output errors to the console which the end user would never see. Any help/advice is very greatly appreciated.

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

This can by done by showing a dialog message. Take a look at the documentation to see how you can display a dialog .

EDIT:

Since you don't want any pop-ups, you could add a JTextArea at the bottom of the screen which only becomes visible when there are any errors, and you could show the error message there,

The label is being added to the panel, but you won't see any changes to the panel unless you alter its attributes like its width and height somehow (resizing/minimizing/maximizing the window that the panel is in, for example).

The easiest way to solve the issue is to call revalidate on the panel, which will validate the change made to the panel and make it visible to the user.

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

In some cases you may need to repaint the panel as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM