如何在显示JFrame后用Java读取文件?

时间:2017-06-27 16:35:01

标签: java swing jframe

我正在使用Java Swing。最初我想读一个文件(这个文件非常大)。因此,文件完全显示后会显示帧。我希望首先加载(显示)框架,然后读取文件。

class Passwd {

    JFrame jfrm; 
    // other elements

    Passwd() {
        start();

        // Display frame.
        jfrm.setVisible(true);
    }

    public void start() {

        // Create a new JFrame container.
        jfrm = new JFrame("Password Predictability & Strength Measure");

        // Specify FlowLayout for the layout manager.
        //jfrm.setLayout(new FlowLayout());
        jfrm.setLayout(null);

        // Give the frame an initial size.
        jfrm.setSize(450, 300);

        // align window to center of screen
        jfrm.setLocationRelativeTo(null);  
        // Terminate the program when the user closes the application.
        jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // some elements

        File file = new File("file.txt");
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = br.readLine()) != null) {
                // operation
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 

    }

    public static void main(String args[]) {

        // Create the frame on the event dispatching thread.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new Passwd();                   

            }
        });
    }
}

如何在显示框架后读取文件?

1 个答案:

答案 0 :(得分:3)

JFrame应立即显示,这不是问题所在。问题是你正在读取Swing事件线程中的文件,这会阻止它显示JFrame的能力。解决方案是不执行此操作,而是在后台线程中读取文件,例如通过SwingWorker。通过这种方式,JFrame可以无阻碍地显示,并且文件读取不会干扰Swing功能。

因此,如果文件读取不会改变Swing组件的状态,请使用简单的后台线程:

new Thread(() -> {
    File file = new File("file.txt");
    try (BufferedReader br = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = br.readLine()) != null) {
            // operation
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

如果在读取时读入将改变GUI的状态,请再次使用SwingWorker。

方面问题:避免使用空布局,因为他们会回来咬你。