Written on May 27th, 2009 at 3:30 am by

26 Comments

How to Update/Refresh JTextArea Dynamically ?

Some times we want to update the JTextarea dynamically.We want them to display text a log file as and when it is generated from the source .The source can be any thing a class,event generator or a function in a infinite loop returning data continuously (Eg: Voice Recognition Engine continuously listening and returning interpreted voice signal as a text) which we want to display in the JtextArea.

What is the problem we face with JtextArea Updation?

They are updated in one shot.That is they display the initially returned text and then display others only after final text is returned.The text returned in between will not be seen in the JtextArea visually even if you use Jtextarea.append() function or use JComponent refresh !

Finally i found solution for this problem..

What is the solution to update/refresh JtextArea dynamically ?

The key is to use SwingWorker class that is used to updated Swing Components dynamically in background .

How to use it?

-First Instantiate SwingWorker.

-doInBackground() this inbuilt function in SwingWorker.

-done() this methods automatically gets executed in the EDT(Event Dispatch Thread)

-Call Worker.execute()

Example Code:


SwingWorker worker = new SwingWorker() {

//This method automatically gets executed in a background thread
      	   public String doInBackground() {

      		   try {

//Your class which is returning the text continuously you can pass your 

//Jtextarea and can update in that class or can update in the same 

//class  where Jtextarea is residing
Sourceobject(JTextArea textarea);
//passed and updated in source
//class

JTextArea.SetText=Sourceobject();//Updated Locally

				}
catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			    }

      		   return null;

      	   }

  //This methods automatically gets executed in the EDT
      	   public void done() {

                                    }
      	};  



Now call worker.execute where ever need.

Example Code:

Jtextarea Update Dynamically Example Code Download

ScreenShot:

jtextarea update dynamically

Hope this information was useful..Do express how it was useful to you:)

Get Free Newsletter
jtextarea can't refresh text, JTextArea Dynamic Refresh, JTextArea Dynamic update, jtextarea not updating -solution, jtextarea refresh, JtextArea update, jtextarea updating

26 Responses to “How to Update/Refresh JTextArea Dynamically ?”


  1. thegands

    2 years ago

    can you explain more details about the case? I still don’t get why JTextArea does not display your text.

    thegands’s last blog post..6 SHAPED BUBBLES CSS TOOLTIPS

    Reply

    • admin

      2 years ago

      Try doing this in java..Run a infinite loop ,at end of each cycle let it return some text say one,two…like tat..Now if you try setting de return text in Jtextarea..U cannot visually see change.. Initially you can see one thats it no more change in JtextArea thats the problem i want point out…

      Reply

      • thegands

        2 years ago

        Now i get it. So in your example, you add stringworker inside a JTextArea.

        I mean, your extends the JTextArea class to make your custom TextArea thats work for that case. Am I right or wrong?

        thegands’s last blog post..SEMANTIC PURE CSS TOOLTIPS

        Reply

        • admin

          2 years ago

          Its enough for our class to extend swing worker and place the text source function/object call within doInBackground() i think now you are clear..


        • thegands

          2 years ago

          I get it clearly. :)

          thegands’s last blog post..SEMANTIC PURE CSS TOOLTIPS


  2. blinkky

    2 years ago

    That’s something new for me.

    blinkky’s last blog post..Top 5 Free File Hosting

    Reply

  3. kordian

    2 years ago

    Hi, I can’t figure out what is Sourceobject() method…

    More code of working example would be very appreciate.

    Thanks in advance.
    Kordian

    Reply

    • admin

      2 years ago

      Sourceobject() here refers to the function which is going to return data to the Jtextarea ..

      Reply

      • kordian

        2 years ago

        In my case, I need to write a text (as log file) in case of succesful or failed operation (information to the user or catching exception). Currently I use:

        jTextArea.append();

        So there is no function returning text, just calling directly method of jTextArea. Here is an example:

        public boolean connectToSQLite() {
        try {
        // Establish the connection.
        Class.forName(“org.sqlite.JDBC”);
        connSQLite = DriverManager.getConnection(“jdbc:sqlite:eai.sqlite”);
        jTextArea.append(“Connected successfuly”);
        return true;
        // Handle any errors that may have occurred.
        } catch (Exception ex) {
        jTextArea.append(“Connection failed”);
        return false;
        }
        }

        How Can I use above code to meet my needs?

        Thanks in advance!
        Kordian

        Reply

      • kordian

        2 years ago

        I also tried sth like this:

        public void printMessage(String s)
        {
        final String m = s;
        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
        jTextArea1.setText(m);
        }
        });
        }
        Changed also SwingUtilities for java.awt.EventQueue.

        But I didn’t see any difference.

        Reply

        • admin

          2 years ago

          I understand your problem..jTextArea.append() will not work because it will get updated in one shot i faced this same problem..Now try calling printMessage function from within doInBackground().

          SwingWorker worker = new SwingWorker() {

          public String doInBackground() {

          try {

          public void printMessage(String s)
          {
          final String m = s;

          jTextArea1.setText(m);

          }
          catch (Exception e) {

          e.printStackTrace();
          }

          return null;

          }

          public void done() {

          }
          };


        • kordian

          2 years ago

          Thanks for code, but I thing, we can not put metod printMessage() into doInBackground(). I have errors when i do that. When I remove whole block:

          public void printMessage(String s)
          {
          final String m = s;
          jTextArea1.setText(m);
          }
          catch (Exception e) {
          e.printStackTrace();
          }

          everything backs to normal…


        • admin

          2 years ago

          Thats right i forgot..Ok.You cannot define function inside doInBackground()..Define function outside doInBackground() and call printMessage inside doInBackground()it will work fine surely..

          What i did was i passed the Jtextarea variable to function in your case it is printMessage and updated the Jtextarea inside printMessage function…


        • admin

          2 years ago

          OR just call jTextArea.append inside doInBackground() it will solve your problem…You should also execute the worker ..I tried this in Netbean it will be useful for you try it..

          Example Code to Update Jtextarea Dynamically..

          http://sites.google.com/site/shamgsite/file/UpdateJtextarea_technobuz.zip?attredirects=0

          Screen shot:

          http://img38.imageshack.us/img38/4154/updatejtextareadynamica.jpg


        • kordian

          2 years ago

          I really appreciate your help. Thanks for an example, but what You do is just define worker and execute appending text function 10 times and finish. I don’t know how I can append text to jTextArea on demand, I mean each time I want.

          I did sth like this:

          In constructor I fired up swing worker thread:
          SwingWorker worker = new SwingWorker() {
          public String doInBackground() {
          try {
          ???
          } catch (Exception e) {
          e.printStackTrace();
          }
          return null;
          }

          public void printMessage(String s) {
          final String m = s;
          jTextArea1.setText(m);
          }

          public void done() {}
          };
          worker.execute();

          I defined method printMessage:
          public void printMessage(String s)
          {
          final String m = s;
          java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
          jTextArea1.append(m);
          }
          });
          }

          and I want to printMessage(“mess”) on demand in various method/functions.

          And I am too dumb to figure out what am I to do next…What should I put into doInBackground() to access jTextArea independently from main Swing thread, anytime I want to put a message during long time tasks?


        • kordian

          2 years ago

          Wait…Should I create seperate StringWorker thread each time I want to write sth to jTextArea during time consuming operation?

          If so, how can I pass argument to StrinWorker?


    • admin

      2 years ago

      Try this make variable ‘m’ a global variable so that you can access it from any where.It should fix the problem…

      SwingWorker worker = new SwingWorker() {
      public String doInBackground() {
      try {
      jTextArea.append(m);
      } catch (Exception e) {
      e.printStackTrace();
      }
      return null;
      }

      public void printMessage(String s) {
      m = s;
      jTextArea1.setText(m);
      }

      public void done() {}
      };
      worker.execute();

      Reply

      • kordian

        2 years ago

        Thanks for a tip!
        OK, so I did this:

        1. defined global variable:
        String textMessage = “”;

        2. defined method showText()
        private void showText() {
        SwingWorker worker = new SwingWorker() {
        @Override
        public String doInBackground() {

        jTextArea1.append(textMessage);

        return null;
        }
        @Override
        public void done() {}
        };
        worker.execute();
        }

        3. and everytime I want to append text to jTextArea before calling time consuming method, I do this:
        textMessage = “some text I want to display”;
        showText();

        and, imagin, it doesn’t change anything. Still, text appears after calling time consuming method. WTF???

        Reply

        • admin

          2 years ago

          I cannot figure out why its still not working…

          ok try this define swing worker outside separately not inside showtext method

          SwingWorker worker = new SwingWorker() {

          public String doInBackground() {

          jTextArea1.append(textMessage);

          return null;
          }
          @Override
          public void done() {}
          };

          private void showText() {

          worker.execute();
          }


        • kordian

          2 years ago

          Still the same. Have no clue what can cause this problem… Strange thing is that SwingWorker doesn’t do its job…


        • kordian

          2 years ago

          hey, check this out. When i put this loop

          for (long x=0; x< 1000000000; x++) {

          }

          after worker.execute() from your example text is also deleyed…


        • admin

          2 years ago

          I dont know wats causing this pro:(


        • kordian

          2 years ago

          So what we do now? Maybe we should sent mail to sun? :)

          OK, I try to digg a little thru sun forum


        • admin

          2 years ago

          For Sure they will not respond:) Ok ..Try this thread

          http://forums.sun.com/thread.jspa?threadID=5364511&tstart=0

          it was useful to me while i was working on my project ..Currently its not loading ,you give it a try..


  4. name

    2 years ago

    Best,

    Reply

Leave a Reply



Previous Post:

Next Post: