2017-06-27 17 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