Error messages with Java Swing

后端 未结 3 1401
南笙
南笙 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: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    
    }
    

提交回复
热议问题