1

I read a file and set the text(about 4000KB of size) into a JTextArea. It freezes my application. Following is my code snippet. I appreciate your suggestions....

public void setText(final JTextArea textArea)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            BufferedReader from = null;
            try
            {
                from = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                System.out.println("Started..........");
                textArea.read(from, file.getName());
                System.out.println("Completed..........");
            }
            catch (Exception ex)
            {
                Logger.getLogger(FileTools.class.getName()).log(Level.SEVERE, null, ex);
            }
            finally
            {
                try
                {
                    from.close();
                }
                catch (IOException ex)
                {
                    Logger.getLogger(FileTools.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

        }
    });
}
Anuruddha
  • 1,367
  • 6
  • 19
  • 38
  • 4
    You are reading the text file from your GUI thread. This makes it unable to deal with events from the GUI thus it seems like the program 'froze'. Read the file from another thread and your problem will be solved. – Joel Witteveen May 22 '14 at 05:15
  • 1
    http://stackoverflow.com/questions/19444912/difference-between-swingutilities-invokelater-and-swingworkervoid-object/19444995#19444995 – René Link May 22 '14 at 05:18
  • 2
    You are putting 4MB of data into a GUI which is already a terrible idea from the point of view of usability. Rethink. – user207421 May 22 '14 at 07:15
  • 1
    @JoelWitteveen, I used a seperate thread and it worked. But it takes some time to load the text into JTextArea. – Anuruddha May 22 '14 at 07:20
  • Also, it takes a lot time to display the text in UI after printing "Completed....". Seems JTextArea.read() takes some time to update the UI. – Anuruddha May 22 '14 at 08:23
  • 1
    You can read the file line-by-line (or in chunks) and append it to the text area. This way the visible part of the text area is filled quickly and the rest is done "behind the scene". – user1803551 May 22 '14 at 15:33
  • Also, remember not to create too many strings. Use a `StringBuilder` to hold them, as `String` is immutable. – user1803551 May 22 '14 at 15:37

0 Answers0