java - 如何在JFrame显示后才读取Java中的文件?

标签 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();                   

            }
        });
    }
}

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

最佳答案

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。

附带问题:避免使用空布局,因为它们会反过来咬你。

关于java - 如何在JFrame显示后才读取Java中的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44785560/

相关文章:

java - com.sun.xml.internal.ws.client 不存在

java - JSP 类属性无效

java - 将整数添加到 ArrayList 时

java - 如何使用多种类型 "|"在JAVA中通过Google Place API搜索地点

java - 我可以将 CSS 应用于 swing 文本组件吗?

java - 使 Java Swing 应用程序持久化

java - 为什么Java的GUI平台命名为 "Swing?"

java - 如何在 Java Swing 应用程序中播放 MP4 视频

java - 如何用始终在最上面的对话框结束 Swing 程序?

java - 使 JDialog 始终位于父级 (JFrame) 之上,但用户仍然可以与父级交互