Event Dispatching Thread

Hello
I'm a beginning student of java and I have trouble understanding how to manage the event Dispatching Thread.

I have read many things on the internet; but I have not found anything that it be written in Italian (my language), so I'm afraid I did not understand what I read.

Of course, I have not yet understood where to put the run() methos and how to call it.

I need to set the text in a JLABEL after clicking on a JButton; where should I put the statement JLabel.setText ("bla bla") run() method? in the my JButton actionPerformed() method?

After many attempts I still didn't get it. :(

Thanks for your help.

Published by: piratolo on 18-Dec-2012 0.54

piratolo wrote:
Should I do something like that?

Not really, it's a very bad example. When would you like to add 100000 JLabels anywhere ever.

He spoke as a situation

public void actionPerformed(ActionEvent e) {
    loadDataFromDatabase();    // Loads a lot of data, while loading the GUI will be frozen since you're on the event thread
}

In this case, you must create another thread to load the data, instead of load on the EDT. The EDT is necessary if you make changes to the GUI.

Tags: Java

Similar Questions

  • Event dispatcher listener giving a ClassCast Exception in C++ 3.6.1

    Hello
    I enclose a NamedCache underlying event listener and when I update the cache entry I did not all alerts. But when I checked the
    Journal of consistency than exception available now, I found. But I don't do any kind of Casting as mentioned below.

    2012-01-17 11:12:55.793/0.320 Oracle Coherence for C++ RTC 3.6.1.0 < Info > (thread = hand): Socket connected to 169.52.37.237/169.52.37.237:9099
    2012-01-17 11:13:04.859/9.386 Oracle Coherence for C++ RTC 3.6.1.0 < error > (thread = ExtendTcpCacheService:coherence:component:util:TcpInitiator:coherence:component:util:Service:EventDispatcher): an exception has occurred when sending the following event:
    {[Coherence::Component:util:RunnableCacheEvent: coherence::util::MapListenerSupport::FilterEvent{coherence::component::net::extend::RemoteNamedCache::BinaryCache[source=coherence::component::net::extend::RemoteNamedCache::BinaryCache@0x69f090c4] update: key = Binary(length=19), old value = Binary (length = 713), value = Binary(length=713) new filters = [NULL]}
    2012-01-17 11:13:04.860/9.387 Oracle Coherence for C++ RTC 3.6.1.0 < error > (thread = ExtendTcpCacheService:coherence:component:util:TcpInitiator:coherence:component:util:Service:EventDispatcher): the following exception has been captured by the event dispatcher:
    2012-01-17 11:13:04.860/9.387 Oracle Coherence for C++ RTC 3.6.1.0 < error > (thread = ExtendTcpCacheService:coherence:component:util:TcpInitiator:coherence:component:util:Service:EventDispatcher): NULL
    coherence::lang:ClassCastException: try to cast from a 'gce::coherence:CoherenceEventHandler' to 'coherence::util:MapListener' sub coherence::lang:coh_throw_class_cast(const_std::type_info&,_const_std::type_info&) (ClassCastException.cpp:27)
    at coherence::lang:coh_throw_class_cast(std::type_info_const&,_std::type_info_const&)
    to coherence::lang:cast coherence::lang:TypedHandle < coherence::util:MapListener > < coherence::lang:TypedHandle < coherence::util:MapListener >, coherence::lang:Object > (coherence::lang:TypedHandle < coherence::lang:Object > const &, Boolean)
    to coherence::lang:cast coherence::lang:TypedHandle < coherence::util:MapListener > < coherence::lang:TypedHandle < coherence::util:MapListener >, coherence::lang:Object > (coherence::lang:TypedHolder < coherence::lang:Object > const &, Boolean)
    to coherence::lang:cast coherence::lang:TypedHandle < coherence::util:MapListener > < coherence::lang:TypedHandle < coherence::util:MapListener >, coherence::lang:Object > (coherence::lang:MemberHolder < coherence::lang:Object > const &, Boolean)


    When I wrote a sample application, it works without any problem. Only the difference of the program come above exception is this library c ++ is responsible for true NYI and relevant event listener is added during a JNI method call. Please explain to me why this exception is coming. I am attaching the relevant code as well.

    -----------------------------------------------------------

    CoherenceEventListener.hpp


    /*
    * File: CoherenceEventHandler.hpp
    * Author: srathna1
    *
    * Created January 5, 2012, 10:15
    */

    #ifndef COHERENCEEVENTHANDLER_HPP
    #define COHERENCEEVENTHANDLER_HPP

    #include "coherence/util/MapEvent.hpp".
    #include "coherence/util/MapListener.hpp".
    #include < iostream >
    #include < map >
    #include ' coherence/lang.ns.
    #include "mihelper.hpp".
    #include "MiCoherence.hpp".
    #include < String >
    #include "MICoherenceDataObject.hpp".

    using coherence::util:MapEvent;
    using coherence::util:MapListener;
    using namespace coherence::lang;
    /**
    * Implementation of MapListener which prints each event as it receives
    * them.
    */

    gce {} namespace
    namespace consistency {}

    class CoherenceEventHandler
    : public class_spec < CoherenceEventHandler,.
    extends < object >,
    implements < MapListener > > {}
    friend class factory < CoherenceEventHandler >;

    public:

    CoherenceEventHandler(CMiCoherence * miCoh): mi (miCoh), msgSeqNo (1) {}
    }

    virtual void entryInserted (MapEvent::View vEvent) {}

    Vcle Object::View = vEvent-> getKey();
    Key String::View = cast < String::View > (Vcle);
    Object::view vValue = vEvent-> getNewValue();
    subject of tank [100];
    strcpy (topic, key-> getCString());
    Managed < gce::coherence:MICoherenceDataObject >: discovers pos = cast < < gce::coherence:MICoherenceDataObject > Managed: View > (vValue);
    std::cout < < key < < '=' < < pos < < std::endl;

    }

    virtual void entryUpdated (MapEvent::View vEvent) {}

    Vcle Object::View = vEvent-> getKey();
    Key String::View = cast < String::View > (Vcle);
    Object::view vValue = vEvent-> getNewValue();
    subject of tank [100];
    strcpy (topic, key-> getCString());
    Managed < gce::coherence:MICoherenceDataObject >: discovers pos = cast < < gce::coherence:MICoherenceDataObject > Managed: View > (vValue);
    std::cout < < key < < '=' < < pos < < std::endl;
    GCE::coherence:MICoherenceDataObject msg = * pos;
    }

    virtual void entryDeleted (MapEvent::View vEvent) {}
    }

    private:
    CMiCoherence * mi;
    int msgSeqNo;

    };
    }
    }
    #endif / * COHERENCEEVENTHANDLER_HPP * /.


    ---------------------------------------------------------------

    Code for event registration

    NamedCache::Handle miCoherenceCache = NULL;

    try {}
    String::view cacheName = szConnect;
    miCoherenceCache = CacheFactory::getCache (cacheName);
    } catch (const std::exception & e) {}
    LOGERR ("error in cache for middleware consistency during initialization: %s", e.what ());
    Return MI_ERR_BADSTATE;
    }

    nConnectState = miCoherenceCache - > getCacheService()-> isRunning() == true? 1: 0;
    miCoherenceCache-> addFilterListener(gce::coherence::CoherenceEventHandler::create(this));)


    -------------------------------------------

    Please give me an idea why few internal event dispatcher giving exceptional...

    Thank you and best regards,
    Sura

    Hi Sura,

    That exception would seem to indicate that libcoherence.so was loaded several times. Specifically the exception indicates that a course was recorded twice with our infrastructure of class loader, and this loading occurs as part of the static initialization of the library, which in turn is part of the loading of the library. While I'm not sure that the library has been charged twice to 100%, so it seems quite likely. On a danger noted, the changes above with 3.7.1 and we reporter class registration is delayed until the first time you try to use the library. So with 3.7.1 you will see a different behavior, even if the loading of the library several times always seems to be fatal.

    Mark
    The Oracle coherence

  • Exception occurred during the event dispatching: java.lang.NoSuchMethodError

    Hello

    We have upgraded to the latest Oracle Application Server version 10.1.2.3.0 and webutil version 1.0.6.

    But we are facing the following error while accessing the web link. Message captured from the Java Console.
    Please suggest if you have a solution/idea about this error. Thank you!

    Oracle JInitiator: Version 1.3.1.22
    Using JRE version 1.3.1.22- internal Java hotspot Client VM
    Maximum size: 50 MB
    Compression level: 0 -.
    c: clear console window
    f: finalize objects on the finalization queue
    g: garbage collection
    h: display this help message
    l: dump classloader list
    m: print memory usage
    q: Hide console
    S: dump system properties
    t: dump thread list
    x: delete the cache of class loaders
    0-5: set the level of trace to < n >
    ----------------------------------------------------
    Download http://si02938.in.irt.com:7778/forms/java/frmall_jinit.jar to JAR cacheDownloading http://si02938.in.irt.com:7778/forms/java/frmwebutil.jar to JAR cacheDownloading http://si02938.in.irt.com:7778/forms/java/jacob.jar to JAR cacheDownloading http://si02938.in.irt.com:7778/forms/java/FileInformation.jar to JAR cacheDownloading cacheproxyHost = nullproxyPort = 0connectMode = HTTP, native.
    Version forms cmdlet is: 10.1.2.3
    Exception occurred during the event dispatching: java.lang.NoSuchMethodError at oracle.forms.webutil.common.VBeanCommon.init(VBeanCommon.java:281) at oracle.forms.handler.UICommon.instantiate (Unknown Source) at oracle.forms.handler.UICommon.onCreate (Unknown Source) at oracle.forms.handler.JavaContainer.onCreate (Unknown Source) at oracle.forms.engine.Runform.onCreateHandler (Unknown Source) at oracle.forms.engine.Runform.processMessage(Unknown Source) at oracle.forms.engine.Runform.processSet(Unknown Source) at oracle.forms.engine.Runform.onMessageReal(Unknown Source) at oracle.forms.engine.Runform.onMessage(Unknown Source) at oracle.forms.engine.Runform.processEventEnd(Unknown Source) at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source) at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source) at java.awt.Component.dispatchEventImpl (unknown Source) at java.awt.Container.dispatchEventImpl (unknown Source) at java.awt.Component.dispatchEvent (unknown Source) at the java.awt.EventQueue.dispatchEvent (Unknown Source) at java.awt.EventDispatchThread.pumpOneEventForHierarchy (unknown Source) at the java.awt.EventDispatchThread.pumpEventsForHierarchy (Unknown Source) at java.awt.EventDispatchThread.pumpEvents (unknown Source) at java.awt.EventDispatchThread.run (Unknown Source)

    Published by: user12233243 on November 16, 2009 22:28

    Published by: user12233243 on November 16, 2009 22:29

    Hello

    Your welcome, but you need to mark it as correct or relatively useful because other users will be able to solve their problems.

    Sarah

  • java.lang.RuntimeException called by the event no thread

    Hi all

    Please help me.

    I download my application Suiloidi OTA. When I have my application rum, it throws an error "untrapped Exception: java.lang.RuntimeException called by the event no thread", please let me know if anyone with no work around for this problem.

    I'm really in trouble.

    Ashutosh

    Thank you

    I got a d solution.

    Your steps were correct.

  • Supersimple event dispatcher does not

    I have this simple event using an external .as file Dispatcher and does not trigger my event listener in the root timeline for some reason any. This code is almost identical to a code that I use and which works very well. Can you see the problem? First the code in the .as file. Then, the code on the root timeline.

    Thank you! Who got it. Very logical too I might add. Now, I just need to understand why everything has worked elsewhere in my old program. Very perplexed, but this will help me a lot.

  • Flex Event Dispatcher Questions...

    Hi guys...

    I'm sending a custom of my Player.as and here YouTubeEvent my Main.as would listen to and create the video player... Apparently my eventHandler can't catch the event to create the videoplayer... My flex debug mode is so screw I can even use... My code is as follows... I appreciate really no response or help...

    My custom event...

    package com.youtube.events {}

    import flash.events.Event;

    /public class YouTubeEvent extends Event {}

    Public static const PLAYER_READY:String = "PLAYER_READY";

      

    public void YouTubeEvent(type:String) {}

    super (type);

    }

    }

    }

    My Main.as

    SerializableAttribute public class SearchYoutube extends Sprite

    {

    private var videoPlayer:Player;

    public void SearchYoutube()

    {

    loadPlayer();

    }

    private function loadPlayer (): void

    {

    videoPlayer = new Player();

    videoPlayer.addEventListener (YouTubeEvent.PLAYER_READY, playerReady);

    playReady will never be executed...

    }

    private void playerReady(event:YouTubeEvent):void

    {

    videoPlayer.createPlayer ();   This Manager was never going to be executed...

    addChild (videoPlayer);       This Manager was never going to be executed...

    }

    }

    Player.As

    display only part of the codes here

    public void Player() {}

    }

    public function createPlayer (): void

    {

    _loader = new Loader();

    _loader.contentLoaderInfo.addEventListener (Event.INIT, onLoaderInit);

    }

    private void onLoaderInit(event:Event):void

    {

    _loader. Content.addEventListener ("onReady", onPlayerReady);

    }

    private void onPlayerReady(event:Event):void {}

    dispatchEvent (new YouTubeEvent (YouTubeEvent.PLAYER_READY));

    }

    The is the top-level application. all events will be propagated to the application. So if you save events to the level of the aplcation, you need not worry about losing events.  Application.application will give you the reference application slot and you catch and listen to events at this level based on what I posted in my previous post.

  • Event dispatcher question...

    Hi guys... I have a question about sending the event. I am trying to write code for youtube player and find the following link...

    http://www.codingcolor.com/AS3/AS3-YouTube-chromless-API/

    There many dispatchEvent call similar to this:

     dispatchEvent(new YouTubeEvent(YouTubeEvent.ON_IOERROR,event));

    To my understanding, event custom shipping usually as below:


     dispatchEvent(new Event(YouTubeEvent.ON_IOERROR));

    I don't know why it can add ,event after On_IOERROR . I appreciate if someone could help me with this. Thank you.

    Hello

    Have you downloaded the source? If you did, then please go to com\YouTube\YouTubeEvent.as

    It has the following code:

    /****************************
    * Manuel González *.
    [email protected] *.
    * www.stheory.com *.
    * www.codingcolor.com *.
    *****************************/
    com of the packaging. {From YouTube
    import flash.events.Event;

    SerializableAttribute public class YouTubeEvent extends Event {}
    public var data: *;

    public static const = "ON_IOERROR" ON_IOERROR:String
    public static const = "ON_CHANGE" ON_CHANGE:String
    public static const = "ON_ERROR ON_ERROR:String."
    public static const = "ON_READY" ON_READY:String
    public static const = "ON_QUALITY_CHANGED" ON_QUALITY_CHANGED:String

    public void YouTubeEvent (type: String, data: *) {}
    This.Data = data;
    Super (type);
    }
    }
    }

    You see it is a custom event and the second parameter passed to the constructor of the event is a non typed data. This means that this event holds differnet type of data in data while the distribution of different event types as photographed at static vars.

    Now in flex, we used event metadata for access that of its parent.

    If you are using as a component, you should not write the atg of metadata. Instead add the instance using code and add the event like this listener:

    var myInstance:SomeInstance = new SomeInstance();

    myInstance.addEventListener (MyEvent.TYPE, myEventHandler);

    private void myEventHandler (event: MyEvent): void

    {

    var obj: * = event.data;//data is the public var in the custom event class

    }

    Best regards

    Etienne Das

    http://deepanjandas.WordPress.com/

  • Operation not allowed on the shipment blocking event thread

    Dear friends,

    I'm sorry to put this problem, but I'm posting it after much searching this forum. Although the number of threads, the solution is available, but it does not work on me. On a thread, that the person wrote that he solved the problem, but haven't posted the solution how he had done this. The problem is:

    SerializableAttribute public class SmsDemo extends net.rim.device.api.ui.UiApplication {}
    Private SmsDemoMainScreen SmsDemoMScreen;
    Public Shared Sub main (String [] args)
    {

    SmsDemo SmsDemoApp = new SmsDemo();
    SmsDemoApp.enterEventDispatcher ();
    }
    public SmsDemo()
    {
    _Thread BackGroundThread = new BackGroundThread();
    _Thread.start ();

    SmsDemoMScreen = new SmsDemoMainScreen();
    pushScreen (SmsDemoMScreen);
    }

    class BackGroundThread extends Thread {}
    public BackGroundThread() {}
    / * initialize the constructor parameters * /.
    }

    public void run() {}
        
    net.rim.device.api.ui.UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
       
    public void run() {}
                   
    try {}
    javax.wireless.messaging.MessageConnection msgConn = (javax.wireless.messaging.MessageConnection)javax.microedition.io.Connector.open("sms://:0");
    javax.wireless.messaging.Message msg = msgConn.newMessage (javax.wireless.messaging.MessageConnection.TEXT_MESSAGE);
    javax.wireless.messaging.TextMessage = (javax.wireless.messaging.TextMessage) msg txtMsg.
    txtMsg.setAddress("sms://+91123456789");
    txtMsg.setPayloadText ("Test Message");
    msgConn.send (txtMsg);
                       
    System.out.println ("sending SMS success!");
    } catch (Exception e) {}
    System.out.println (e.getMessage ());
    e.printStackTrace ();
    }
    }
    });
          
    }
    }

    The code above gives error "Blocking Operation not allowed on the event dispatch thread" to msgConn.send (txtMsg); line.

    Please guide me how to solve the problem for example. If possible, please guide me how to continuously listen to the incoming message also. The SmsDemo example with JDE is autonomous work fine but in error when incorporated in my solution.

    Thanking you in anticipation.

    I don't think you need to do invokeLater (new Runnable()... the inner thread.) Try to remove it, I think that this can cause this problem.

  • Thread.Join () does not work

    I did a media player, and I use a database to store data, after playing a song for a while, I store the current position in the Pb, so I can continue to play the next time. I use a thread to update the db, so that he can play the next song at the same time what the db update.

    The problem is when I close the application, I want the event dispatch thread to wait until the thread of db update is finished, the code is:

    If (needWait == true) {}
    logThread.join ();
    }

    but it seems don't work and make the application non-response, where will not?

    A big loop on the thread of events blocks before the end of the loop.  But the OS won't know that the UI Thread is really busy.

    However, thread. Join blocks just the thread of events...

    So why don't; t it becomes sensitive?  There are all sorts of reasons.  Maybe the other Thread is not complete.  There may be something in this Thread that requires access to the event Thread, as synchronize the lock of the event or of nullity.  There may be something in this Thread that locks.  Or maybe the BlackBerry OS throws your Thread.join because it blocks the event Thread?

    I do not know, and to be honest, I'm not sure that this is not important.  The important think is here to get your code to work and to do so, in my opinion, you need to move your join off the thread of events.

    If you ignore this advice, it's good, I don't mind.  Your call - this is your code.  I've been wrong before, and I'll be wrong again.  But you have the best advice that I can give you.

    And I must admit that I never use thread.join, even in Background Threads.  I always use wait/notify.  But that's just me.

  • Update of the main screen to a background thread

    Hi guys im trying to update the main screen from a background thread. in this case I'm using a 2 static pictures. Once I click on a butotn on the popupScreen when the application is loaded, it will update the image on the main screen.

    I wrote a small excerpt for it and can you please give me some help with this. because when I've debugged and one of the developers helped me thereby to discover that the screen im trying to update is not the active screen.  Please have alook please.ive extract have 3 classes here

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    SerializableAttribute public class MyApp extends UiApplication
    {

    Public Shared Sub main (String [] args)
    {
    Create a new instance of the application and make the currently
    who runs the thread of the application of the event dispatch thread.
    MyApp PAP = new MyApp();
    theApp.enterEventDispatcher ();
    }
        
    /**
    * Creates a new object MyApp
    */
    public MyApp()
    {
    Push a screen onto the stack in the user interface for rendering.
    pushScreen (new MyScreen());
    final Pinpopup pp = new Pinpopup();

    UiApplication.getUiApplication () .invokeLater (new Runnable()
    {
    public void run()
    {
    UiApplication.getUiApplication () .pushModalScreen (pp);
    }
    });
    }
    }
    ////////////////////////////////////////////////////////////////////////////////////////

    / public final class screen extends MyScreen
    {
    /**
    * Creates a new object of MyScreen
    */
    public Bitmap bmp image;
    public BitmapField bmpField;
    public ButtonField btnDisplay;
    public ImageThread imgThread;
            
    public MyScreen()
    {
            
    Set the displayed title of the screen
    setTitle ("MyTitle");
    BMP = Bitmap.getBitmapResource ("image.png");
    btnDisplay = new ButtonField ("Display");
    bmpField = new BitmapField (bmp);

    btnDisplay.setChangeListener (new FieldChangeListener() {}
                
    ' Public Sub fieldChanged (field field, int context) {}
    TODO self-generating method stub
                    
    if(Field == btnDisplay)
    {
    BMP = Bitmap.getBitmapResource ("image1.png");
    bmpField.setBitmap (bmp);
    signInButtonClicked ("07760926037", "1234");
    LaunchImageThread();
                        
    }
    }
    });
            
    Add (bmpField);
    Add (btnDisplay);
            
    }
        
        
    Public Sub LaunchImageThread()
    {
    imgThread = new ImageThread (this);
    System.out.println ("THIS screen:" + this.getScreen ()); I realized that the im screen update is not active but its strange I don't create any other refrence so
    New Thread (imgThread) m:System.NET.HttpListener.start ();
    }
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// POPUPSCREEN CLASS
    class Pinpopup extends PopupScreen //implements FieldChangeListener
    {
    private ButtonField btnOk;
        
    Pinpopup()
    {
            
    Super (new HorizontalFieldManager());

    btnOk = new ButtonField ("Sign In");

    btnOk.setChangeListener (new FieldChangeListener() {}

    ' Public Sub fieldChanged (field field, int context)
    {
    TODO self-generating method stub
    Try
    {
    if(Field == btnOK)
    {
    Close();
    MyScreen ms = new MyScreen();
    Mrs. LaunchImageThread();
    }
    } catch (IllegalArgumentException e) {}
    TODO: handle exception
    System.out.println ("Exception Popup all in signingIn" + e.getMessage ());
    }
    }
    });
            
    Manager fieldManagerContext = new Manager (USE_ALL_WIDTH)
    {
    ' public void sublayout (int width, int height) {}

    int xPos = 10;
    int ypos = 40;

    Field = getField (0);
    layoutChild (field, 280, 50);
    setPositionChild (field, xpos ypos + 100 + 165);

    setPosition (300, 300);
    setExtent (350, 225);
    }
    };
            
    fieldManagerContext.add (btnOk);
    Add (fieldManagerContext);
    }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    / public class ImageThread implements Runnable
    {
    private MyScreen parent;
        
    public ImageThread (MyScreen myScreen)
    {
    parent = myScreen;
    }

    public void run()
    {
    Try
    {
    UiApplication.getUiApplication () .invokeLater (new Runnable() {}
                    
    public void run() {}
    TODO self-generating method stub
    System.out.println ("active screen:" + UiApplication.getUiApplication () .getActiveScreen ());
    System.out.println ("active screen:" + parent.getScreen ());
    parent.bmp = Bitmap.getBitmapResource ("image1.png");
    parent.bmpField.setBitmap (parent.bmp);
                        
    }
    });
    }
    catch (Exception ex)
    {
    System.out.println ("Exception in Thread:" + ex.getMessage ());
    }
    }
    }

    was soon thanks

    I suspect that this is your problem:

    MyScreen ms = new MyScreen();
    Mrs. LaunchImageThread();

    I suspect that if you did as I suggested on the other Thread and put a breakpoint in the constructor of MyScreen, you'd have foiund, this creates a second instance.

    I hope that you can take it from here.

  • In another thread - another method and then run Sub...

    I wrote a method to extract a string from a webpage using StreamConnection and it works perfectly... except that it runs on the main thread.  I wonder if there is a simple way to have a method that returns an object (String in this case) something to run on a thread and return it to the first thread.

    Everything I try the only thing I can get to work on the second thread is what's on the run method void, but that returns nothing... because it sucks...

    Until now what I thought is to pass the variables I need in the constructor, then set the connection stream real term where I want retruned is written in a class variable and another method that returns the class variable that has been filled with the run method... but that doesn't seem to just... thought he worked in a simple test I ran...

    A slightly different way (but completely equivalent) to work in a another thread is to create a class that implements Runnable and feed a thread. If, for any reason, you do not want to expand Thread (because your worker class extends already something else and it would be difficult to refactor), then this variant is a lifeline. You do something like this:

    class WorkerClass extends AnotherClass implements Runnable {    // ...    public void run() {       // do time-consuming work here    }}
    
    // later...WorkerClass worker = new WorkerClass();// initialize worker object. Then: new Thread(worker).start();
    

    As it is easy to turn a class in an executable (you simply add "implements Runnable" and a run() method), it's an easy way to avoid the subclassing Thread.

    Regardless of how you use to perform work in a separate thread, there is always the question of how to get the results. With the help of the observer is a common way to handle this, but in general, this means that the results are returned in the worker thread, not the thread from the main event. If you want to update the user interface, this can be a problem. Another approach is to structure your code something like the following:

    /** * Process the results of some time-consuming operation. */public void acceptResults(ResultType result) {  // ...}
    
    /** * Start a thread to carry out time-consuming work in a * separate thread and deliver the results back in the * event dispatching thread. */public void launchWork() {  new Thread() {        public void run() {           final ResultType res = computeResults();          Runnable r = new Runnable() {                public void run() {                   acceptResults(res);               }         }         Application.getApplication().invokeLater(r);      }
    
           /**        * Do time-consuming work in this method       */       private ResultType computeResults() {         // connect to server, interpret reply, etc.       } }.start();}
    

    You have the right idea that is running in a thread separate is how to manage a time consuming task. The point of all, however, is that you (the event dispatching thread) don't want to wait for the task at hand. Both the observer model and the code here offer a solution for a worker thread to do the work without blocking the thread of the event. The invokeLater() method was kindly provided by BlackBerry people to give the worker threads neatly transfer control on the event dispatching thread when needed.

  • JTextField.setText blocks Java in thread EDT

    Hello

    When I try to setText in a particular context, the application blockes (hangs forever).

    I've used EDT thread like this:

              if(!javax.swing.SwingUtilities.isEventDispatchThread())  {
                    System.err.println("NOT EDT THREAD");
                    Runnable doThread = new Runnable() {
                        @Override
                        public void run() {
                              temp.setText(VAL);
                        }
                    };          
                    SwingUtilities.invokeLater(doThread);
                } else {
                    System.err.println("IS EDT THREAD");
                    temp.setText(VAL);
                    System.err.println("AFTER IS EDT THREAD");
                }
    
    
    

    So my request prints "IS the EDT THREAD" but does not print 'AFTER IS EDT THREAD".

    The frame is like this:

    1. a new thread is started from EDT

    2. this new thread creates a new JPanel with a few swings and sets values in these swings

    3. some of these fluctuations were associated events DocumentListener and they begin to run the text for some JTextFields setting

    The hanging appears when these events are executed.

    These events are not started from EDT, but they are considered by Java as EDT. Is this ok?

    Is there something I can do to fix this?

    Thank you.

    Wrong with setText in EDT? I've probably missed something essential.

    Yes - it is wrong to do almost anything on the EDT.

    The EDT has ONE PURPOSE and one purpose: "ship events". It's the "crier" that allows others to know when important things happen.

    A factor must deliver MAIL on their road. You want the factor to stop and chat with all the way from your neighbor? Or even stop in a cup of tea? What is the delay in the delivery of the mail.

    Can you please explain how should I setText when in EDT?
    

    Of course - don't DO THIS!

    You already know what is happening. Any code that you run in the SOW must be as fast and as short as possible.

    You have been informed of an event. So make a note of the details or notify other processes (for example to add a message to a queue) and out of this EDT as fast and clean as possible.

    See the Java tutorials

    https://docs.Oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

    Tasks on the event dispatch thread must end quickly; If they are not, of events does not support save and user interface stops responding.

    See this last clause? 'save events? does not? Sound familiar.

    When you call Java code as "setText" you call Java code and you have NO CONTROL over what does this code or how it does it.

  • force the update chart actionPerformed thread

    I have the code that illustrates my question. My research on the internet, this is a common question, but common responses have not solved the problem. Java compresses the graphic events into one. When the code is executed at the beginning of the executable test class will work correctly. When it is executed in response to the button click event, it compresses the graphic events and only the second color is shown in the background of the JPanel object. I want to have a button to click because of the event the background to change between two different colors with a fixed interval between color changes. I have studied intensively and tried many a different recommended bugs and several of my own scenarios using son and others... all of this without success.
    Miss me something important... Just can't put your finger on it. Thanks in advance for your help.
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    
    
    public class TestClass implements ActionListener {
      JFrame frame;
      JPanel panel;
      ColorChanger test;
      Runnable BlueBackground;
      Runnable YellowBackground;
      
      public TestClass() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(100,100));
        panel.setMinimumSize(new Dimension(100,100));
        panel.setVisible(true);
        frame.add(panel);
        frame.setPreferredSize(new Dimension(100,100));
        frame.setMinimumSize(new Dimension(100,100));
        frame.setVisible(true);
        JButton button = new JButton();
        button.addActionListener(this);
        panel.add(button);
        test = new ColorChanger();
        BlueBackground = new Runnable(){public void run(){panel.setBackground(Color.blue); panel.repaint();}};
        YellowBackground = new Runnable(){public void run(){panel.setBackground(Color.yellow); panel.repaint();}};
        test.run();
      }
    
      /*
       * When run on the EDT this works.  When run on the actionPerformed thread it compressed the graphics events into one.
       * Initial threads - Their most essential job is to create a Runnable object that initializes the GUI and schedule that 
       *   object for execution on the event dispatch thread.
       * EDT event dispatch thread - Once the GUI is created, the program is primarily driven by GUI events, each of which causes 
       *   the execution of a short task on the event dispatch thread. 
       * Worker thread - Application code can schedule additional tasks on the event dispatch thread (if they complete quickly, so 
       *   as not to interfere with event processing) or a worker thread (for long-running tasks).
       */
      public final class ColorChanger implements Runnable {
        public void run(){
          try {
            Thread.sleep(700);
            SwingUtilities.invokeLater(BlueBackground);
            Thread.sleep(700);
            SwingUtilities.invokeLater(YellowBackground);
            Thread.sleep(700);
          } catch (InterruptedException ex) {
            
          }
        }
      }
    
      @Override
      public void actionPerformed(ActionEvent arg0) {
        test.run();
      }
    }
    
    public class Main {
      private static TestClass square;
        /**
         *<p> Initials - Version - Date     - Reason        <br>
         *      JPH    - 0.00    - 01/20/13 - Java Release
         *<p>  
         * main() method is the method used to launch the application.  It also
         * contains the application state data.<br>
         *  
         * @param args - String array of potential run parameters.  Not used.
         * @return nothing
         */
        public static void main(String[] args)  {
          square = new TestClass();
        }
    }

    On click of a button, copy the following code

    Thread.sleep(700);
    SwingUtilities.invokeLater(BlueBackground);
    Thread.sleep(700);
    SwingUtilities.invokeLater(YellowBackground);
    Thread.sleep(700);
    

    runs on the Event Dispatch Thread (EDT). Specifically, actionPerformed() is called on the EDT and you then call run(). It is the same thread that manages these invokelater as well as the table itself. He cannot do this kind of things, though, until it ends all that actionPerformed() sleep and get out. I hope you can see why it is a problem.

    The above code should be run on a separate thread.

    @Override
    public void actionPerformed(ActionEvent arg0) {
      new Thread(test).start();
    }
    
  • Is replicated cache single thread?

    Hello

    Replicated cache scheme do has no thread < count > configuration option.
    1 can. the replicated system cause a survey of worker threads?
    2. what thread is used to get replicated, calling cache operations or a cache service event dispatch thread?
    3. where are executed the aggregation of entry (local or remote, calling node or event dispatch thread)?

    Thank you
    Alexey

    Alexey salvation,

    1. replicated cache is not currently using worker threads
    2, 3. 'Read' all operations are performed on the thread of the appellant

    Kind regards
    Gene

  • Implementing custom listener for ListField

    I'm trying to implement a listener for a custom field I created that would launch a new screen when you click on the field. However, nothing happens when I click on the custom field. I use BlackBerry Java plug-in for Eclipse, JDK 1.3 and JRE 6.0. All my code is attached. MyScreen.java contains the code where I'm trying to implement a function fieldChanged.

    //MyApp.Java
    
    package mypackage;
    
    import net.rim.device.api.system.CodeModuleManager;
    import net.rim.device.api.ui.UiApplication;
    
    /**
     * This class extends the UiApplication class, providing a
     * graphical user interface.
     */
    public class MyApp extends UiApplication
    {
        /**
         * Entry point for application
         * @param args Command line arguments (not used)
         */
        public static void main(String[] args)
        {
            CodeModuleManager.promptForResetIfRequired();
    
            // Create a new instance of the application and make the currently
            // running thread the application's event dispatch thread.
            MyApp theApp = new MyApp();
            theApp.enterEventDispatcher();
        }
    
        /**
         * Creates a new MyApp object
         */
        public MyApp()
        {
            // Push a screen onto the UI stack for rendering.
            pushScreen(new MyScreen());
        }
    }
    
    //MyScreen.java
    
    package mypackage;
    
    import net.rim.device.api.ui.container.*; //for vertical manager
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.FieldChangeListener;
    import net.rim.device.api.ui.Manager;
    //import net.rim.device.api.ui.Screen;
    import net.rim.device.api.ui.component.*;
    import net.rim.device.api.ui.Color;
    import net.rim.device.api.ui.decor.BackgroundFactory;
    
    /**
     * A class extending the MainScreen class, which provides default standard
     * behavior for BlackBerry GUI applications.
     */
    public final class MyScreen extends MainScreen
    {
        /**
         * Creates a new MyScreen object
         */
        private CustomField cField;
    
        public MyScreen()
        {
            // Set the displayed title of the screen
            setTitle("My New App");
    
            cField = new CustomField("4.PNG","This is my 4th custom field!!");
            ButtonClickListener listener = new ButtonClickListener();
            cField.setChangeListener(listener);
            add(cField);
    
        }//MyScreen function
    
        class ButtonClickListener implements FieldChangeListener
        {
            public void fieldChanged(Field field, int context)
             {
                  //we need to determine which button was clicked
    
                  if(field == cField)
                      new SpeedBumpScreen();
    
             }
    
        }//ButtonClickListener
    
    }
    
    //CustomField.java
    
    package mypackage;
    
    import java.util.Vector;
    
    import net.rim.device.api.system.Bitmap;
    import net.rim.device.api.ui.*;
    import net.rim.device.api.ui.component.*;
    
    class CustomField extends ListField implements ListFieldCallback {
        private Vector rows;
    
        public CustomField(String customImg, String customLabel) {
            super(0, ListField.MULTI_SELECT);
            setRowHeight(80);
            setEmptyString("Hooray, no items here!", DrawStyle.HCENTER);
            //setCallback(this);
    
            Bitmap p1 = Bitmap.getBitmapResource(customImg); 
    
            rows = new Vector();
    
            TableRowManager row = new TableRowManager();
    
            row.add(new BitmapField(p1));
    
            // SET THE item NAME LABELFIELD
            // if overdue, bold/underline
            LabelField item = new LabelField("item #" + customLabel,
                DrawStyle.ELLIPSIS);
    
            // overdue
            item.setFont(Font.getDefault().derive(
                Font.BOLD | Font.UNDERLINED));
            System.out.println("OVERDUE");
    
            row.add(item);
    
            // SET THE LIST NAME
            row.add(new LabelField("List Name #" + String.valueOf(1),
                DrawStyle.ELLIPSIS) {
                protected void paint(Graphics graphics) {
                    graphics.setColor(0x00878999);
                    super.paint(graphics);
                }
            });
    
            // SET THE DUE DATE/TIME
            row.add(new LabelField("Due Date #" + String.valueOf(1),
                    DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH
                    | DrawStyle.RIGHT) {
                protected void paint(Graphics graphics) {
                    graphics.setColor(0x00878787);
                    super.paint(graphics);
                }
            });
    
            rows.addElement(row);
    
            setSize(rows.size());
    
        } //end public CustomField()
    
        // ListFieldCallback Implementation
        public void drawListRow(ListField listField, Graphics g, int index, int y,
                int width) {
            CustomField list = (CustomField) listField;
            TableRowManager rowManager = (TableRowManager) list.rows
                .elementAt(index);
            rowManager.drawRow(g, 0, y, width, list.getRowHeight());
        } //end drawListRow()
    
        private class TableRowManager extends Manager {
    
            public TableRowManager() {
                super(0);
            } //end pulic TableRowManager
    
            // Causes the fields within this row manager to be layed out then
            // painted.
            public void drawRow(Graphics g, int x, int y, int width, int height) {
                // Arrange the cell fields within this row manager.
                layout(width, height);
    
                // Place this row manager within its enclosing list.
                setPosition(x, y);
    
                // Apply a translating/clipping transformation to the graphics
                // context so that this row paints in the right area.
                g.pushRegion(getExtent());
    
                // Paint this manager's controlled fields.
                subpaint(g);
    
                g.setColor(0x00CACACA);
                g.drawLine(0, 0, getPreferredWidth(), 0);
    
                // Restore the graphics context.
                g.popContext();
            }//end drawRow()
    
            // Arranges this manager's controlled fields from left to right within
            // the enclosing table's columns.
            protected void sublayout(int width, int height) {
                // set the size and position of each field.
                int fontHeight = Font.getDefault().getHeight();
                int preferredWidth = getPreferredWidth();
    
                // start with the Bitmap Field of the priority icon
                Field field = getField(0);
                layoutChild(field, 32, 32);
                setPositionChild(field, 0, 0);
    
                // set the item name label field
                field = getField(1);
                layoutChild(field, preferredWidth - 16, fontHeight + 1);
                setPositionChild(field, 34, 3);
    
                // set the list name label field
                field = getField(2);
                layoutChild(field, 150, fontHeight + 1);
                setPositionChild(field, 34, fontHeight + 6);
    
                // set the due time name label field
                field = getField(3);
                layoutChild(field, 150, fontHeight + 1);
                setPositionChild(field, preferredWidth - 152, fontHeight + 6);
    
                setExtent(preferredWidth, getPreferredHeight());
            }//end sublayout()
    
            // The preferred width of a row is defined by the list renderer.
            public int getPreferredWidth() {
                return Graphics.BLACK;
            }
    
            // The preferred height of a row is the "row height" as defined in the
            // enclosing list.
            public int getPreferredHeight() {
                return getRowHeight();
            }
    
        }// private class TableRowManager extends Manager 
    
        public Object get(ListField listField, int index) {
            // TODO Auto-generated method stub
            return null;
        }
    
        public int getPreferredWidth(ListField listField) {
            // TODO Auto-generated method stub
            return 0;
        }
    
        public int indexOfList(ListField listField, String prefix, int start) {
            // TODO Auto-generated method stub
            return 0;
        }
    
    } //end class CustomField extends ListField implements ListFieldCallback
    
    //SpeedBumpScreen.java
    
    package mypackage;
    
    import net.rim.device.api.ui.Field;
    import net.rim.device.api.ui.component.RichTextField;
    import net.rim.device.api.ui.container.MainScreen;
    
    public final class SpeedBumpScreen extends MainScreen
    {
        /**
         * Creates a new HelloWorldScreen object
         */
        SpeedBumpScreen()
        {
            // Set the displayed title of the screen
            setTitle("Speed bump screen");
    
            // Add a read only text field (RichTextField) to the screen.  The
            // RichTextField is focusable by default. Here we provide a style
            // parameter to make the field non-focusable.
            add(new RichTextField("This is the speed bump screen!", Field.NON_FOCUSABLE));
        }
    
    }
    

    In addition, there is nothing in the ListField that will actually generate an event.

    Here is a simple extension to the ListField which will make "clickable".  In your FieldChangeListener you can use getSelectedindex to determine which line has the focus.

    Please ask if this isn't clear:

    public class ClickableListField extends ListField {
    
        public ClickableListField(int numberOfRows) {
            super(numberOfRows);
        }
    
        protected boolean navigationClick(int status, int time) {
            this.fieldChangeNotify(2);
            return true;
        }
    
        protected boolean touchEvent(TouchEvent message) {
            int x = message.getX( 1 );
            int y = message.getY( 1 );
            if( x < 0 || y < 0 || x > getExtent().width || y > getExtent().height ) {
                    // Outside the field
                    return false;
            }
            // If click, process Field changed
            if ( message.getEvent() == TouchEvent.CLICK ) {
                this.fieldChangeNotify(2);
                return true;
            }
            return super.touchEvent(message);
        }
    
    }
    

Maybe you are looking for

  • Web site will appear as a jumble of characters. What gives?

    When I try to open a Web site, it displays a full page of what looks like Hindu, Chinese and wingbat characters.

  • "You don't have a hard drive capable of burning files to CD or DVD.

    Acer Extensa 4420 laptop.  Always worked great for the past years of 1-1/2 each time that I burned pictures ofPhotos.  Now, I get this error message. But Windows Media Player seems to work on the copy of the data asa video and eject disk drive E. But

  • Upgrade of windows code 7-10 and got the error 0 x 20000...

    I tried to upgrade to windows 7 to 10 and got the error code 0 x 20000... What is - this and can I fix it?

  • Inaccessible links

    There are various links posted by support staff in the 'Ask The Experts' discussion that I can't access. Here are some examples: http://www.Cisco.com/en/us/partner/docs/security/IPS/7.0/Configuration/Guide/IME/ime_getting_started.html#wp1233087 http:

  • Specific Date of the user data recovery

    My 16 year old son has a user account on my Windows 7 (Ultimate - SP1) desktop computer he uses when he stays with me. I am trying to retrieve specific date data (related to its use) to validate when he was with me / on this computer. I use CCleaner