2017-06-27 24 views
0

我正在使用Java Swing。最初我想读一个文件(这很大)。因此,在文件完全显示后,帧会显示出来。而我想要首先加载(显示)框架,然后应该读取文件。如何仅在显示JFrame后才读取Java文件?

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

      } 
     }); 
    } 
} 

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

回答

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。

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

+0

为什么第一行代码中有“ - >”? – user5155835

+0

@ user5155835:Java 8的lambda语法的一部分。请阅读[在Java中做什么箭头运算符,' - >'?](https://stackoverflow.com/questions/15146052/what-does-the-arrow-operator-do-in-java) –

+0

请你能告诉Pre Java 8吗? – user5155835