Good practice to update Swing i SwingUtilities.invokeLater() method?

Is it a good practice to allways make the updates/changes of Swing components in the SwingUtilities.invokeLater() method in a multithreaded application. Or are there any situations when it´s not?

There are a number of methods that are thread safe, but they generally say so in the API
If they aren't then you shouldn't be updating them on the EDT.
[http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html|http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html]

Similar Messages

  • Best Practice for Updating Infotype HRP1001 via Class / Methods

    I want to update an existing (custom) relationship between two positions.
    For example I want
    Position 1 S  = '50007200'
    Position 2 S =  '50007202'
    Relationship = 'AZCR'
    effective today through 99991231
    Is there a best practice or generally accepted way for doing this using classes/methods rather than RH_INSERT_INFTY ?
    If so, please supply an example.
    Thanks...
    ....Mike

    Hi Scott
    You can use a BAPI to do that.
    Check the following thread:
    BAPI to update characteristics in Material master?
    BR
    Caetano

  • How careful do you need to be with SwingUtilities.invokeLater()

    Is it safe to call an SwingUtilities.invokeLater() from within a method that was invoked with SwingUtilites.invokeLater() ?
    I'll give a quick example below.
        public void setWindowLocation(final Point p) {
            //Throw this on to the ETD with a recursive method call.
            if(!SwingUtilities.isEventDispatchThread()){
                SwingUtilities.invokeLater(new Runnable(){
                    public void run() {
                        setWindowLocation(p);
                //don't execute recursive call twice.
                return;
            }// end - EDT section.
            assert EventQueue.isDispatchThread():"Not Event Dispatch Thread";
            frame.setLocation(p);
            someOtherMethodThatCallsInvokeLater();
    public void someOtherMethodThatCallsInvokeLater(){
          //be lazy don't bother to check if already on event dispatch thread.
           Runnable update = new Runnable(){
                public void run(){
                    remoteModeWindow.setTransparency(50);
            SwingUtilities.invokeLater(update);
    }What would happen would when the second method is called that didn't bother to see if it was already on the Event Dispatch thread, and just called invokeLater() anyway. Is that harmless, or can it lead to deadlock, or some other inefficiency?
    The reason I ask, is I've seen some code in one class check and some in a different class that previously was only called from a non-dispatch thread never bothered to check. It is now possible that the "don't bother to check" method could be called in either situation (i.e. from a dispatch thread, or non-dispatch thread).
    Comments appreciated. What is a general guideline for this situation? Too many of the Swing books I've seen only lightly cover a few pages on this topic.
    Edited by: asnyder on Jul 2, 2009 7:14 PM

    Calling invokeLater(...) in this manner is absolutely safe with regards to deadlocks. What happens is that your runnable is enqueued at the end of the event queue. There is a possibility that another runnable has been dispatched in the mean time, so there is no guarantee that your code will be executed immediately:
    1. EDT enters someOtherMethodThatCallsInvokeLater()
    2. Another event (from another thread) triggers a repaint for a component or some other UI operation, which is enqueued
    3. Your runnable is enqueued on the EDT
    So highly theoretically there may be a delay which could be avoided if you immediately executed the runnable:
    public void someOtherMethodThatCallsInvokeLater(){
           Runnable update = new Runnable(){
                public void run(){
                    remoteModeWindow.setTransparency(50);
            if (SwingUtilities.isEventDispatchThread())
                update.run();
            else
                SwingUtilities.invokeLater(update);
    }In my experience though this kind of 'optimization' has no practical implications whatsoever.

  • 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

  • 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

  • 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

  • Javax.swing.SwingUtilities.invokeLater make my program slow

    i am writing a program in which i am implementing documentlistener
    to communicating between two frames
    if i write my code with javax.swing.SwingUtilities.invokeLater it makes my program slow
    and if i write without this thread safe quality then this is fast but giving me runtime exception
    what i do to make my program better
    kindly suggest
    public void insertUpdate(DocumentEvent e) {
                updateLog(e, "inserted into");
            public void removeUpdate(DocumentEvent e) {
                updateLog(e, "removed from");
            public void changedUpdate(DocumentEvent e) {
                //Plain text components don't fire these events.
            public void updateLog(DocumentEvent e, String action) {
                Document doc = (Document)e.getDocument();
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
    tf4.setText(lbl.getText());
    }

    If your program is becoming too slow or unresponsive, it means that the operation "tf4.setText(lbl.getText());" is taking too long to execute and is therefore blocking the Swing-thread.
    There is little you can do to make that operation faster, but perhaps you can change how or how often you update the frames.
    Setting the whole text via setText() everytime a change happens seems very wasteful. Imagine you have a text with a million characters, and every time the user adds or changes just one character, you are getting and seting over one million characters. That is not the right approach.
    I'm not familiar with text-operations or class DocumentEvent, but I guess that there should be some kind of delta in DocumentEvent containing only the changes that were made. You could apply only these changes on tf4 instead of setting the whole text. Finding out how to do this would be the best solution. This will also make your program more scalable, as with setText() the performance of your application will continuously decrease as the text length increases.
    Usually when working with documents you have a "viewer" and a "model". If your viewer was a JTextBox and your model was, say a StringBuilder, you could make quick changes to the contents of JTextBox using the StringBuilder.append() or delete() methods without having to modify the whole text. You need to find out how this is done with whatever UI system you're using.
    If you can't find out how to do the above, a workaround would be to reduce how often you call "updateLog()". For example, is it truly necessary to call "updateLog" every time a new update happens? Perhaps it would be better to use a timer and only call "updateLog()" every few seconds.
    But as I said, this should only be a temporary workaround. You really should find out how to perform more efficient updates without using setText(). I recommend you search for tutorials and guides on how to work with text and documents on the internet.

  • 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

  • Help Update Swing

    Hi,
    I'm having some trouble with a swing application, let me explain it to you.
    I have a function (provided by a library, so it wont be easy to modify it), that retrieves files from a server; An object must be handed over to this function so the programmer can execute some code when a file is retrieved. What I'm trying to do is to update (append some text) on a JTextArea whenever a file is retrieved so the user has some idea of whats going on during the (usually) lengthy process.
    Problem here is that the JTextArea, does not get updated on the screen until during the retriving process, so it goes from an empty JTextArea (at the beginning and during the file transmission process), to a JTextArea with all the information of the process after the last file has been retrieved.
    The function which updates the JTextArea looked like this:
    public void sendReceivedObjectIndication(final String dicomFileName, final String transferSyntax, final String callingAETitle) throws DicomNetworkException, DicomException, IOException {
            if (dicomFileName != null) {
                         area.append("\nReceived: " + dicomFileName + " from " + callingAETitle);
             } else {
                //Notify failure
        }I also tried this
    public void sendReceivedObjectIndication(final String dicomFileName, final String transferSyntax, final String callingAETitle) throws DicomNetworkException, DicomException, IOException {
            if (dicomFileName != null) {
                //System.out.println("Received: " + dicomFileName + " from " + callingAETitle + " in " + transferSyntax);
                Runnable r=new Runnable() {
                    public void run() {
                       area.append("\nReceived: " + dicomFileName + " from " + callingAETitle);
                SwingUtilities.invokeLater(r);           
            } else {
               //Notify failure
        }But none of them works as expected.
    Anybody knows what to do here?
    Thanks in advance
    Jc

    You need to perform your lengthy task off of the EDT. Use a javax.swing.SwingWorker, as it facilitates periodically updating a GUI (on the EDT) while doing the lengthy task off of the EDT.
    Also, read this for a general tutorial and background on the subject: [Concurrency in Swing|http://java.sun.com/docs/books/tutorial/uiswing/concurrency/initial.html] .

  • JTable: RFC on good practice (SQL queries from cell editor)

    I usually add/remove/edit JTable data from an external panel. But in this scenario, my client would like to be able to click on the first column of an empty row and enter a product number. Within the cell editor, I must make an SQL query to the database in order to determine if the product number is valid and if so, use part of the SQL data to populate other cells of the current row (like product description).
    My problem is that this just doesn't seem right! Isn't the cell editor executed on the only Swing thread? Also, if the product number is not valid, I correctly implement the stopCellEditing() method but for some reason, you can still navigate the table (click on any other cell or press the TAB key, etc)... weird!!
    Does anyone have a good practice on how to perform the SQL query in a better place and force a cell to be selected until you enter a valid number or press the CANCEL key?
    I was looking at implementing the TableModelListener's tableChanged(...) method but I'm not sure if that would be a better place either.
    I personally would edit outside of the table, but good practice seems hard when the requirement is to edit from a cell editor!!
    Any suggestion would be greatly appreciated!
    Thanks!

    maybe you could write an input verifier for the column that does the query and rejects invalid entries.
    maybe you could send the query off in a worker thread.
    as far as making the table so you can't select any cells, hmm. not sure.
    you could disable
    .setEnabled(false);the table until the query comes back, something like that.

  • Question on SwingUtilities.invokeLater

    The program I have included is attempting to "simulate" opening and loading a file into memory.
    Run the program, select File and then select Open. You will notice that the File menu does not disappear for 3 seconds (i.e. until the file has been completely read).
    I was hoping it was possible to close the File menu while the file is being read. While reading through various documentation on the invokeLater() method I found the following:
    "Both invokeLater() and invokeAndWait() wait until all pending AWT events finish before they execute"
    Therefore by adding an invokeLater() method I was hoping to accomplish the following series of events:
    1) click on Open menuItem
    2) invoke OpenAction
    3) do the "repaint" (which would cause the file menu to disappear)
    4) finish the OpenAction
    5) do the long running task
    Hopefully you understand what I am trying to accomplish and can provide some guidance. Here is the sample program:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TestInvokeLater extends JFrame
         JFrame frame;
         JMenuBar menuBar;
         JMenu menu;
         JMenuItem menuItem;
         public TestInvokeLater()
              frame = this;
              setDefaultCloseOperation( EXIT_ON_CLOSE );
              menuBar = new JMenuBar();
              menu = new JMenu("File");
              menuBar.add(menu);
              menuItem = new JMenuItem( new OpenAction() );
              menu.add(menuItem);
              setJMenuBar( menuBar );
              JPanel panel = new JPanel();
              panel.setPreferredSize( new Dimension( 100, 100 ) );
              setContentPane( panel );
         class OpenAction extends AbstractAction
              public OpenAction()
                   putValue( Action.NAME, "Open" );
              public void actionPerformed(ActionEvent e)
              repaint();
         SwingUtilities.invokeLater(new Runnable()
         public void run()
              try
                   Thread.sleep(3000); // simulate log running task
              catch (Exception e) {}
         public static void main(String[] args)
              JFrame frame = new TestInvokeLater();
              frame.pack();
              frame.show();
    }

    Thanks for the input, but I still have some confusion -
    "invokeLater() simply appends the thread to the end of the dispatch queue, this happens before the event code to hide the file menu gets queued"
    This is the part that confuses me. If I understand event driven programming correctly then the code for the MenuItemClicked must complete execution before the next event in the queue can be executed.
    If we assume the code for MenuItemClicked is something like:
    1) fireActionEvent
    2) fireCloseMenuEvent
    When MenuItemClicked is finished executing the next event in the queue is the ActionEvent which invokes my ActionPerformed code:
    1) I use the Swing invokeLater() method (which means it should be queued "after" the fireCloseMenuEvent
    Does this make any sense?

  • Updating Swing components from a different class

    I would like to use the JTextArea component in a JFrame to display fast updating text from my application. My application is very simple. When the app launches the GUI is created then my application engine would start processing and displaying text data into the GUI. After reading about Thread safety when using Swing components I concluded it would not be a good idea for my app engine class to update the JTextArea class directly using methods such as .append(String).
    I would be grateful for any suggestions on how I should approach updating Swing components from different classes.
    Many Thanks in advance Sean

    Hi
    Why don't you just implement a basic callback method?
    To do this the right way you should probably define a simple Interface that has a public method like updateProcessText(String s). Your swing class then implements this interface, basically forcing it to provide the public method you defined (this is no different than implementing ActionListener, which forces you to define actionPerformed). Secondly modify your processing class, so that it take's a class that implements the interface you just created, as one of the arguments in it's constructor. Lastly assign the argument from your construnctor to a private var - this will enable your processing class to have a handle to your swing class and update it as it pleases.
    This might sound very complex, but it's really simple once you've done it once.

  • Applet+servlet+good practice

    Hi there,
    I'd like to know what is of "good taste" when it comes to transfer data between servlet and applet : using vector to carry the data or by some way transfer the resultset itself ?
    Or better : some sort of xml that would allow the end user to work disconnected from the servlet, do its changes when traveling (hope it's not by plane these times...) and then back to the office by some usual conciliation mechanism update the database ....?
    Currently i'm using the firs method, but, not sure it's the best way
    Any good practical (already improved) idea ?
    thanks and welcome to all

    I think the better way is to transfer XML data, because this way you are free to implement a client in a different language, not only java. XML is a standard for the interexchange of data between different platforms and different languages. I think it's the best option. But it has disadvantages too. You transfer more data than strictly necessary by the web and transfer times are higher, so if you are looking for efficiency, you should think in propietary formats of information (compressed...).
    I hope this helps you, and sorry about my English.

  • Apex version control: what are "good practices"?

    I have made my first Apex application that is been tested right now. Once this version is released, I should want to have a stable and robust versioning system for this application. I don't have any experience with this. So any info about this issue would be very welcome. Are there some good practice rules I should follow? What are things to watch out for? Etc... Some things I'd like to be able to do:
    1. Have version numbers assigned to the application
    2. Have update scripts to go from one version to the next. (If possible have update scripts to go to the latest version, whatever the current version is.)
    3. Rollback to a previous version of the application
    4. See te differences between different versions of the appliction
    I also would like the same for the database schema.
    Any help would be very welcome...

    Here how I do it:
    Each Apex application has a unique version number in the format Major Release Number / Minor Release Number / Patch Release Number e.g.
    Version 1.3.2
    Each object and build script are separate files, with their own version number and stored in a Configuration Management Database (CMDB) e.g. Subversion. The version number, author, description, date, change history are commented into the header of each script.
    Each Release on CD is also given a unique sequential number so that different releases of the same version can be tracked through test. Each CD Release will usually consist of an application export, object scripts and a build script. The CD image is also checked into the CMDB.
    If an application is going to distributed as a packaged application or installed on multiple environments then each release is a full build. For single instances, the builds are incremental.
    Cheers
    Shunt

  • Best Practice for Updating children UIComponents in a Container?

    What is the best practice for updating children UIComponents in response to a Container being changed?  For instance, when a Canvas is resized, I would like to update all the children UIComponents height and width so the content scales properly.
    Right now I am trying to loop over the children calling InvalidateProperties, InvalidateSize, and InvalidateDisplayList on each.  I know some of the Containers such as VBox and HBox have layout managers, is there a way to leverage something like that?
    Thanks.

    you would only do that if it makes your job easier.  generally speaking, it would not.
    when trying to sync sound and animation i think most authors find it easiest to use graphic symbols because you can see their animation when scrubbing the main timeline.  with movieclips you only see their animation when testing.
    however, if you're going to use actionscript to control some of your symbols, those symbols should be movieclips.

Maybe you are looking for

  • Help! InDesign CS6 tools not working

    Hello, I recently upgraded to CS6 on my PC and have run into some issues with InDesign. None of the tool buttons in the top ribbon or on my side menu function properly. For example, if I make a text box and wish to change the font, I can't select the

  • What is the max number of records in table

    Hello Friends, am using oracle 11g . How many records we can store in a table or what is the maximum size of the table . On what factors it depends. If the number of records are ever growing , what is the best possible solutiion ? thanks/kumar

  • Can u help me please

    WRITE A SELECT STATEMENT TO PRINT THE NUMBER OF DAYS IN THE SYSDATE MONTH

  • Air Application URL Path Issue

    I am trying to invoke a  content of the file which is in shared folder from Air application. Version : Flash builder 4.5,Flex3.6 sdk and Air 2.7. for this am using the below code.. var request:URLRequest = new URLRequest(); //request.url = ('file:///

  • Errors when Modifying a Weblogic EJB example to make it connect to mySQL

    Hello, I am learning the example codes shipped with weblogic server, which is under ...samples\examples\ejb20\basic\beanManaged. The original connection pool was on cloudscape. I was trying to modify it and make it connect to mySQL. In ejb-jar.xml an