Why do we have to use SwingUtilities.invokeLater() to update UI status?

I just don't understand very well why we have to use SwingUtilities.invokeLater() to update UI status. Why not just new a thread in actionPerformed() method and do time consuming tasks in this thread and update UI status in it? Some tutorials say it is not safe to update UI status not in Event Dispatch Thread, I don't understand, why is it not safe? Can anyone provide a scenario for this? I just write an example, a button and a progressbar, click button, progressbar keeps updating value. I just create a new thread to do this, don't find any issue. Thanks.

[Swing single threaded rule|http://www.lmgtfy.com/?q=swing+single+threaded+rule]
db

Similar Messages

  • Why do we have to call SwingUtilities.invokeLater()??

    Hello,
    i am not understanding the concept of SwingUtilities.invokeLater() i read the documentation but still couln't get why it is needed and when it is needed?do we have to call this function everytime some event is generated and some action is performed on component Ex.mouse click on button etc?? Please give me little details regarding it's concept!
    Thanks in advance :)

    (guys correct me if i'm wrong here)Most of the time that's correct, but for some customizations it is necessary to run custom code after all default code contained in the Swing classes has been executed. For example, to request focus be given to a component that would otherwise not be immediately focused, if you omit to enclose that in a invokeLater, it will get the focus but immediately lose it as still-queued events mandate the transfer of focus elsewhere. Moreover, as the event delivery mechanism is asynchronous, the behavior may be inconsistent.
    In general, any customization that may conflict with the normal flow should be wrapped in invokeLater, whether run from the EDT or another thread. The exceptions here are methods which the API declares to be thread safe.
    what you want to do is run that time consuming process in a thread, and when you need to call back to update the GUI, then use SwingUtilities.invokeLater.Or use SwingWorker, that's what it's for.
    cheers, db

  • Is it safe to use SwingUtilities.invokeLater(), while updating GUI?

    Hi,
    I am updating GUI components in synchronized block which is runinng on main() thread my application hangs, but if I use SwingUtilities.invokeLater(...) then it runs fine.
    My question is:
    Is it safe to use SwingUtilities.invokeLater(...) in synchronized block.
    Edited by: Amol_Parekh on Nov 1, 2007 1:28 AM

    Paul Hyde in his "Java Thread Programming" (great book!!!) says it is.
    With invokeLater() you say to the Thread Scheduler you want that code to run on the Swing thread. In fact, if that is the only thing you do in the synchronized block I think it is unnecessary.
    Greetings,
    astrognom

  • Should I use a SwingWorker or SwingUtilities.invokeLater() to update my UI?

    Are there specific situations where you want to use method above the other? This whole swing concurrency is very new to me, and I don't really know where to begin.

    When executing long running code you don't want the GUI to freeze. Therefore you have two things to be concerned about. First, you want the long running task to execute in a separate Thread. Secondly, when you need to update the GUI from this code you need to make sure the code executes on the Event Dispatch Thread (EDT).
    You can code this manually by creating a separate Thread and then use SwingUtilities.invokeLater() when necessary.
    A SwingWorker tries to simplify this process by having a simple API where you can add code that executes on a separate Thread or where you can add code that executes on the EDT.
    So in the case of managing long running tasks, the end result should be the same.
    Hwever, there are times when I know code is already executing on the EDT, but I sometimes use invokeLater(..) to force my code to the end of the EDT. This is used in special situations when code doesn't execute in the order you want.
    For example, I've tried to add a FocusListener to a JFormattedTextField to "select the text" when it gains focus. The problem is the the UI also adds a FocusListener. Because of the way listeners are handled the last listener added to the component executes first. Therefore, using the invokeLater() forces my listener code to execute last.
    You can try this code to see what I mean:
    KeyboardFocusManager.getCurrentKeyboardFocusManager()
         .addPropertyChangeListener("permanentFocusOwner", new PropertyChangeListener()
         public void propertyChange(final PropertyChangeEvent e)
              if (e.getNewValue() instanceof JTextField)
                   //  invokeLater needed for JFormattedTextField
                   SwingUtilities.invokeLater(new Runnable()
                        public void run()
                             JTextField textField = (JTextField)e.getNewValue();
                             textField.selectAll();
    });Edited by: camickr on Mar 5, 2011 2:36 PM

  • Why do i have to use nextLine() when there is an InputMismatchException

    I dont understand why do i have to use this line of code to avoid an infinite loop here...help appreciated.
    import java.util.Scanner;
    import java.util.InputMismatchException;
    public class InputTest {
         public static void main(String [] args){
         Scanner in = new Scanner(System.in);
         int n = 0;
         while(true){
              try{
                   System.out.println("Input a number:");
                   n = in.nextInt();
                   break;
              }catch(InputMismatchException exc){
                   System.out.println("Error, non-valid input.");
                   //in.nextLine(); <--If i use this line of code it doesn't get into an infinite loop
                             System.out.println("Integer read is: " + n);
    }

    Rix87 wrote:
    When i run the program if i input something that triggers the exception, it infinitely loops through the question and the catch method block outputs, weirdest thing of all is that i can't even input again after the exception is thrown, but with nextLine() it avoids that, but i still dont understand why do i have to use nextLine().Exactly what I said.
    You enter "A". The exception is thrown. The "A" is not consumed. It calls nextInt on "A" again... and again... and again...
    If you do nextLine, the "A" and the newline are consumed.
    Even on good input, I don't think nextInt consumes the EOL.

  • WHy should we have to use to update ipod touch

    WHy should we have to use to update ipod touch

    Your question does not make sense. Please clarify.
    GamingChamp wrote:
    WHy should we have to use to update ipod touch

  • HT201250 Why do i have to use the password for time capsule every time i start my computer

    Why do I have to use thr password for time capsuel every time I start my imac?

    With hindsight, the previous response I got from Apple was just a way of shelving the problem.
    Having just had to reset my password after another 3 months, I contacted Apple again, and it happened that the senior advisor whom the phone agent consulted had had exactly the same problem as me, and had found that iTunes could fix it.  However when I spoke to iTunes they told me I needed to speak to Apple ID account security.  The Apple ID account security representative spoke to a senior adviser, then told me that it would be fixed after I reset my password.  However I am not convinced that anything was actually done, so I may be back here in another 3 months ...
    To modify Roger's advice, the solution I was given is: go to https://expresslane.apple.com ; select 'All Products and Services' in the first column, 'iTunes' in the second column, 'iTunes Store' in the third column, then "Account Management" and "Apple ID account security", then "Talk to Apple support now". A complication is that the "Talk to Apple support now" option only appears when UK English is selected.  So you either need to select UK at the top, or find another way of making phone contact (the email link just went back to the person in iTunes)!

  • I tried updating iphone 6 to 8.1.3 But the phone went dead. I have tried using restore options - both update and erase, but the process stops when it tries to update Iphone firmware.

    I tried updating iphone 6 to 8.1.3 But the phone went dead. I have tried using restore options - both update and erase, but the process stops when it tries to update Iphone firmware.

    Put your phone in DFU mode,
    Hold the Power Button (3 secs)
    Continue holding the power button and also hold the home button (15 secs)
    Release the power button while continuing to hold the home button (10 secs)
    Your device should prompt with the "Connect to iTunes Screen"
    Restore.

  • HT4623 why do i have to pay every time i update from app store?

    why do i have to pay every time i update from app store?

    If you have any questions about your account in particular rather than questions about why something is the way it is, it would be better to contact itunes support at expresslane.apple.com than to talk to us about it. we can't tell you specific information about your account, only how things work in general

  • Why do I have to use SELECT INTO clause in a Stored Proc ?

    Hi,
    I'm new to oracle. I've bought Oracle Database 10g SQL and Oracle Database 10 A beginner's Guide, two books from Oracle press but I can't find any answer for that.
    Why when I'm writing a Stored Procedure with a SELECT statement do I have to use an INTO clause ?? And why when the select returns more than one row do I have to use a cursor ? By the way is this the only way to return more than one row from a stored procedure ?
    Any help will be appreciated.
    Regards.
    S. Nunes

    Sounds like you may have some experience with other databases (SQL Server, maybe?) which allow you to create stored procedures which implicitly return result sets simply by embedding select statements.
    In Oracle, the correct way to do this is using ref cursors.
    See the following link for a good explanation:
    http://osi.oracle.com/~tkyte/ResultSets/index.html

  • When and why do i have to use a Network-Path?

    Hello,
    i'm wondering when i why i have to use a Network-Path in KM.
    I'm able to connect to a File-System Repository, even if i have no Network-Path defined.
    - both run on W2K Server
    - EP runs on host EP (not an Domain-member)
    - Filesystem is provided by host FS (Domain-member)
    - EP is started with the default local-user SAPServiceEP6
    - on the FS host, i have defined also a local-user SAPServiceEP6 (because EP always wants to logon with these credentials, i have checked this in the windows securitylog of host FS)
    - no network-path defined
    So regarding the fact, that everything is working, can anybody tell me when i have to use a Network-Path?
    Thanks in advance
    Frank

    Hi,
    for example if you want to access a share that only access is granted for a given user. The idea is having a superuser with privileges on the other computer to do things like checking ACLS.
    Another example, how can you access windows shares when running the portal in Unix? Using a network path.
    REgards,
    Miguel

  • Why do I have to use silverlight to view Netflix movies?

    I'm wondering why I have to use Silverlight to play Netflix movies. When I opened Netflix and selected a movie to play in my Firefox browser a gray page opened up and the only option was to play the movie using Silverlight. I have a sneaking suspicion that it's a requirement by Netflix as Netflix is partnered up with Silverlight, a Microsoft product and has some sway over what's able to be played with this addon. Why is there no alternative. I really like the new Firefox but still we're wanting for just a little more control of who does what on our machine.
    Respectfully,
    Tom V.

    Netflix determines which program their movies are to use. Firefox has no control over it.

  • Why do I have to use security code for wifi router each time I turn on iPad 3?

    Why do I have to enter wifi security code for my router each time I turn on ipad3?  I have checked all the settings I could but is this a router problem?

    If you're hiding your network SSID and/or using WEP security, I think these can cause this problem.  If you're hiding your SSID, there's really no point in doing that since there are ways people can easily see it if they're looking to do harm anyway.  If you're using WEP security, consider changing to WPA2 which is much more secure than WEP.

  • Why sometimes we have to use two message( ) to display one message ?

    Sometimes one message( ) function is not working properly ? We have to use two message( ) to display one message ? Why ?

    And just to add a little on what dave said:
    You can also detect which button the user has clicked and do some action accordingly.
    DECLARE
    al_id ALERT;
    al_result NUMBER;
    BEGIN
      al_id := Find_Alert('MESSAGE');
      SET_ALERT_PROPERTY(al_id, ALERT_MESSAGE_TEXT, 'your message here');
      al_result := Show_Alert(al_id);
      IF al_result = ALERT_BUTTON1 THEN
         ...  --do some action.
      END IF;
    END;

  • EJB function using  SwingUtilities.invokeLater()  is problm msg publishing

    My problem for JMS using Message publish to group of people , What I did, Server side I am pushing message for each topic , (it could be n number of topic ) I created for Every five topic to as single thread. (Topic will be [ 200 ~2000] ) ,
    Some time this SwingUtilities.invokeLater() function will shown error Message AWT event
    I am using EJB Method for like this.
    new Thread()
    public void run()
         SwingUtilities.invokeLater( new Runnable() {
    public void run() {
         HashMap map=null;
         try
              map=MessagePublish2Group.init(); // to getting connection function .
              InitialContext iniCtx=(InitialContext)map.get("InitialContext");                
                   TopicSession session =(TopicSession) map.get("TopicSession");
                   TextMessage txtmsg = session.createTextMessage();
                   txtmsg.setText(Message);
              for(int i=0;i<userlist.length;i++)
                   try
                   Topic     receiver =(Topic) iniCtx.lookup("topic/"+userlist[i]+"");
              TopicPublisher usertopic = session.createPublisher(receiver);
              usertopic.publish(txtmsg);
              usertopic.close();     
                   catch(Exception gexp)
              close(map); // // to closing connection function .
         catch(Exception exp)
              close(map); // to closing connection function .
    exp.printStackTrace();
    }.start();
    Thanks in advance
    Sasikumar (Sasimsit)

    {color:red}{size:20px}TRIPLE POSTED{size}{color}
    [http://forums.sun.com/thread.jspa?threadID=5333442]
    [http://forums.sun.com/thread.jspa?threadID=5333443]
    [http://forums.sun.com/thread.jspa?threadID=5333445]
    Cross posting is rude.
    db

Maybe you are looking for

  • Question about the smell of new Apple products (in this case an iMac)

    Hi! I wonder what's up with the smell of new Apple products, because they all smell the same in my opinion. I got a new iMac last week and it had a special smell and i know i'm not the only one thinking this. Do Apple add this smell with a perfume to

  • Itunes won't sync music to my iPhone5!!

    I just updated to OSX Mavericks and I have the latest update for iTunes, but when i sync my phone to my macbook pro and try to put my music on it, nothing happens. When it gets to part 4 or 5 (whichever one is the part where the music get's sync'd) i

  • Trex search failed, how to find the problematic property?

    Hello, I've created an index that runs over a repository which contains documents with lots of customised attributes. When I run a search through this index I get: "Error during search occurred - com.sapportals.wcm.WcmException: attribute value is no

  • Release strategy in PR

    Hi, I have some issue in PR release strategy  Whenever a PR is created, it is directly going to our DG. But his release code is 05.when we see our PR, header release stragey showing like this... M1  initiator M2  Core manager 10  MGR PMMD out problem

  • Error opening certain applications

    I keep getting this error when trying to open a game after i have reformated recently. i have play this game prior to the format but now i cant for some odd reason. http://farm3.static.flickr.com/2045/233574904422d8748fc9b.jpg