Java Swing的错误消息 [英] Error messages with Java Swing

查看:176
本文介绍了Java Swing的错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于使用Java Swing处理错误条件的查询。

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

我正在使用Netbeans开发一个简单的Java Swing应用程序。它是加载一个文本文件,然后根据文本文件中找到的数字运行计算。主Swing类包含JFrame和JPanel。

I am using Netbeans to develop a simple Java Swing app. It is to load in a text file, then run calculation based on the numbers found in the text file. The main Swing class holds the JFrames and JPanels.

我将文件加载代码作为单独的类文件。它将读取的行数和一个数字列表返回给主Swing应用程序。

I have the file loading code as a separate class file. It returns the number of lines read and a List of numbers back to the main Swing app.

我意识到如果文件读取失败(即try - > catch(Exception ex)),整个应用程序将崩溃。处理上述场景导致的错误的最佳方法是什么?也就是说,文件加载代码崩溃,我不希望整个程序崩溃。我希望程序说文件已损坏并等待用户加载新文件。

I realised that if the file reading fails (i.e. try -> catch (Exception ex)), the entire app will crash. What's the best way to handle errors resulting from my scenario above? That is to say, the file loading code crashes and I don't want the entire program to crash. I want the program to say the file is corrupted and wait for user to load new file.

有什么想法吗?

Yakult

推荐答案

当你发现异常时,运行:

when you catch the exception, run:

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

然后再次显示文件对话框。

Then display the file dialog again.

最好这样做是为了在文件无效时继续循环。如果存在损坏,那么只要设置了标志,就设置一个布尔标志并循环,而不是抛出异常。这样,当找到一个好文件时,while循环将终止。

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.

示例:

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    
}

这篇关于Java Swing的错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆