Error messages with Java Swing

后端 未结 3 1349
南笙
南笙 2021-01-20 17:42

I have a query on handling error conditions with Java Swing.

I am using Netbeans to develop a simple Java Swing app. It is to load in a text file, then run calculati

相关标签:
3条回答
  • 2021-01-20 18:06

    You just catch the exception and put condition in the catch block. If the file contains other content that your application is intended to handle then you could call your method which will re-handle another file.

    The main handling of your new process of the new file manipulation will start from your catch block. So in this way you are using java thrown exception to restart your application in a brand new way other than relaunching your app from the zero level.

    0 讨论(0)
  • 2021-01-20 18:15

    yeah the problem is with your IO reading concept the while loop is reading to the end of the file and so on.. to prevent that u can use a buffered reader and use this code

    String line = null
    while((line = reader.readLine())!= null) {
    // do stuf
    }
    

    if you are having this problem with processing the read line all you need is to create a exception class of your own by extending Exception class and throw that exception in your catch block after setting the message to your custom exception class you can set that message in to

     JOptionPane.showMessageDialog(null,"message here"); //showMessageDialog is a static method
    

    ok

    0 讨论(0)
  • 2021-01-20 18:26

    when you catch the exception, run:

    JOptionPane.showMessageDialog("File is corrupted. Please select a new file.");
    

    Then display the file dialog again.

    It's probably best to do this as a loop that continues while the the file is not valid. If there is a corruption, then rather than throwing an exception, set a boolean flag and loop as long as the flag is set. That way, when a good file is found, the while loop will terminate.

    Example:

    public static void main(String[] args){
        boolean goodFile = false;
    
        while (!goodFile){
            JFileChooser chooser = new JFileChooser();
            chooser.showOpenDialog();
    
            goodFile = processFile(chooser.getSelectedFile());
        }
    }
    
    private boolean processFile(File file){
        //do you stuff with the file
    
        //return true if the processing works properly, and false otherwise    
    }
    
    0 讨论(0)
提交回复
热议问题