Update JFrame via another Thread

Hello,
I have a JFrame with a JProgressBar, and I need to see the JProgressBar fill as some operation executes. In that JFrame there's a public method that increments the JProgressBar. This serves as a GUI to another class. That other class receives, as an argument, the JFrame, in order to be able to call that public method to increment the JProgressBar.
Something like:
public class Worker{
   public Worker(JFrame jf){
      this.frame = jf;
   public doWork(){
      instruction1;
      frame.updateProgressBar();
      instruction2;
      frame.updateProgressBar();
}This has a major problem: the JFrame's graphics won't be updated (you won't see the progress bar filling during the operation). So I made a class to run the Worker on a Thread, that looks something like:
public class WorkerThread extends Thread{
   public WorkerThread (Worker w){
      this.worker= w;
   public void run(){
      w.doWork();    
}This got the problem solved, the JProgressBar is now correctly updated. But it created a new problem: I need the JFrame to wait for the WorkerThread to finish, and that's what I'm having real trouble with:
public class GUI extends JFrame{
   private worker = new Worker();
   void someButtonPressed(...){
      WorkerThread wt = new WorkerThread(worker);
      wt.start();
      System.out.println("I don't want to see this until the Thread finishes");
}If I leave this as is, I'll see the text before the Thread finishes.
So I added "wait()" between the last two instructions, and a "notify()" as the last instruction of the run() method on WorkerThread. Unfortunately, this gives me two exceptions (java.lang.IllegalMonitorStateException: current thread not owner), one when I call wait() and another when I call notify(). If I make the two methods that call wait() and notify() synchronized, the JFrame's graphics won't update correctly (back to the initial problem).
Any suggestions? Sorry for the long post, and thanx in advance! :)

I don't really understand why you are using two JFrames.
Typically in an application you have a single main JFrame. Whenever you need additional information you would create and display a "modal" JDialog. A modal JDialog prevents the JFrame from receiving any events. So in your example the progress bar should be added the dialog. When the long running task is finished you close the dialog an execution continues back in your main JFrame.

Similar Messages

  • Updating CniNumEdit from another thread

    I get the following Exception,
    First-chance exception in pmdcsimulator.exe (KERNEL32.DLL): 0xE06D7363: Microsoft C++ Exception.
    My call Stack looks as below,
    KERNEL32! 77f1d479()
    MSVCRTD! _CxxThrowException@8 + 57 bytes
    AfxThrowOleDispatchException(unsigned short 0, const char * 0x00433e1c, unsigned int 0) line 1574
    PMDCSIMULATOR! NI::CNiControl::CheckThreadId(void) + 91 bytes
    PMDCSIMULATOR! NI::CNiControl::ValidateControl(void) + 22 bytes
    PMDCSIMULATOR! NI::CNiNumEdit:etValue(double) + 62 bytes
    CPmdcsimulatorDlg::AcquisitionWorkFunction() line 1147
    CPmdcsimulatorDlg::AcqProcessThreadFunction(void * 0x0012f2dc) line 1159
    _AfxThreadEntry(void * 0x0012ec58) line 112 + 13 bytes
    _threadstartex(void * 0x010
    96f80) line 212 + 13 bytes
    KERNEL32! 77f04ede()
    How do I update the control..?

    The UI control classes in Measurement Studio 1.0.1 do not support access from other threads. The next release of Measruement Studio will remedy this problem. Until then, there is an example program that shows how you can use a user message to work around this here: http://zone.ni.com/devzone/devzoneweb.nsf/opendoc?openagent&24C350515009D6A1862569AC0073ACC6&cat=61B119A9F74ADC07862568C50070CE22
    Best Regards,
    Chris Matthews
    Measurement Studio Support Manager

  • Another Thread About 2.0....Updating post as my phone is updated

    At various times today I have hit Check for Updates on iTunes with no success. Just now I clicked it--got nothing. For kicks, I clicked it immediately again. Guess what! Update underway!
    So keep checking back for your update. In the meantime, I'll chronicle mine so you can know what to expect.
    Update: 5 minutes in and I have downloaded quickly (218.2 MB). Now there is a window that says, "Preparing iPhone software for restore..." Been here for a bit.
    Update: "Restoring iPhone software..."
    Update: "Verifying iPhone software..." I'm about 7 minutes into the process, including download time. Just before I updated, I'm at "Restoring iPhone firmware..."
    Update: Couple minutes spent there with the barberpole bar. Next a pop up to say "Your iPhone has been returned to factory setting and is restarting...blah blah blah". Image on phone is for me to connect to itunes. Already am. Now it is syncing and phone says "Waiting for Activation...This may take some time."
    Update: No sooner than I updated, I got another restart pop-up warning for the phone. Aaaaaand we're back. Indeed all settings have been wiped out, including my home screen icons. The apps I already downloaded are present. Oh pop-up, it is restoring my songs and pics. Blah, gotta sift through some contact syncing issues. Back soon...
    Update: That was weird. It wanted to change a few peoples "type" from "empty" to "person." Also it wanted to change the URL for birthdays on iCal. Looks okay though. Correction about the icons, they were just moved around, not removed. Apps are there. OMG FINALLY, the calendar isn't default one color! Love the PhoneSaber app. Ha ha. New contacts icon.
    I heard you can hold the home button and press the top power button to take a screen shot. Sure enough, you can! Adds the picture to Photos. Kind of froze my screen for a second. Scared me...
    Well that's all. Looks like it was succesful. Took about 20 minutes over all. Good luck and have fun!
    Message was edited by: bpeacock22

    Good luck... it took me about an hour to completely update my iPhone this morning, and I started around 7:20AM. While it was trying to activate, it was telling me that I had no signal and that it could not activate without a signal... I guess it resolved itself, because installation (even though it was super slow) finished smoothly, and I haven't had any issues all day.

  • How to refresh a JTable of a class from another thread class?

    there is an application, in server side ,there are four classes, one is a class called face class that create an JInternalFrame and on it screen a JTable, another is a class the a thread ,which accept socket from client, when it accept the client socket, it deal the data and insert into db,then notify the face class to refresh the JTable,but in the thread class I used JTable's revalidate() and updateUI() method, the JTable does not refresh ,how should i do, pls give me help ,thank you very much
    1,first file is a class that create a JInternalFrame,and on it there is a table
    public class OutFace{
    public JInternalFrame createOutFace(){
    JInternalFrame jf = new JInternalFram();
    TableModel tm = new MyTableModel();
    JTable jt = new JTable(tm);
    JScrollPane jsp = new JScrollPane();
    jsp.add(jt);
    jf.getContentPane().add(jsp);
    return jf;
    2,the second file is the main face ,there is a button,when press the button,screen the JInternalFrame. there is also a thread is beggining started .
    public class MainFace extends JFrame implements ActionListener,Runnable{
    JButton jb = new JButton("create JInternalFrame");
    jb.addActionListener(this);
    JFrame fram = new JFrame();
    public void performance(ActionEvent e){
    JInternalFrame jif = new OutFace().createOutFace(); frame.getContentPane().add(JInternalFrame,BorderLayout.CENTER);
    public static void main(String[] args){
    frame.getContentPane().add(jb,BorderLayout.NORTH);
    frame.pack();
    frame.setVisible(true);
    ServerSokct ss = new ServerSocket(10000);
    Socket skt = ss.accept()'
    new ServerThread(skt).start();
    3.the third file is a thread class, there is a serversoket ,and accept the client side data,and want to refresh the JTable of the JInternalFrame
    public class ServerThread extends Thread{
    private skt;
    public ServerThread(Sokcet skt){
    this.skt = skt;
    public void run(){
    OutputObjectStream oos = null;
    InputObjectStream ios = null;
    try{
    Boolean flag = flag;
    //here i want to refresh the JTable,how to write??
    catch(){}
    4.second is the TableModel
    public class MyTableModel{
    public TableModel createTableModel(){
    String[][] data = getData();
    TableModel tm = AbstractTableModel(
    return tm;
    public String[][] getData(){
    }

    Use the "code" formatting tags when posting code.
    Read this article on [url http://www.physci.org/codes/sscce.jsp]Creating a Simple Demo Program before posting any more code.
    Here is an example that updates a table from another thread:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=435487

  • How to use ImageContr​ol on another thread out main

    Hi All,
    I'm looking to use ImageControl (ImageControl.fp) on another thread out main thread 
    In my second thread i try to update image but i have a error (This panel operation can be performed (if a top-level panel) only in the thread in which the panel was created, or (if a child panel) only in the thread in which the top-level parent panel was created.)
    Here my code
    Main thread :
    ImageControl_ConvertFromDecoration (panelHandle, PANEL_IMAGECTRL, 0);
    ImageControl_SetZoomToFit (panelHandle, PANEL_IMAGECTRL, 1);
    ImageControl_SetAttribute (panelHandle, PANEL_IMAGECTRL, ATTR_IMAGECTRL_SHOW_SCROLLBARS, 0);
     hdleThread = CreateThread(NULL, 0,  (LPTHREAD_START_ROUTINE) ThreadTest,  NULL,  0, &idThread);
    Secand thread :
    int ThreadTest (void * data)
    ImageControl_SetZoomToFit (panelHandle, PANEL_IMAGECTRL, 1);
    iIdError  =    ImageControl_SetAttribute (panelHandle, PANEL_IMAGECTRL, ATTR_IMAGECTRL_IMAGE, imageToDisplay);
    // iIdError  = -129
    Could you help me ?
    Thankyou

    many thanks.  I should have thought of the need for using the Target Display Mode. 
    tony

  • My ipod touch 4g doesn't show option for os update in setting-general page. Can i update it via itunes by connecting it to computer?

    My ipod touch 4g doesn't show option for ios update in setting-general page. Can i update it via itunes by connecting it to computer?

    Try:
    - iOS: Not responding or does not turn on
    When it says place the iPod in recovery mode ue one of these programs:
    For PC
    RecBoot: Easy Way to Put iPhone into Recovery Mode
    If necessary:
    Download QTMLClient.dll & iTunesMobileDevice.dll for RecBoot
    For MAC or PC
    The Firmware Umbrella - TinyUmbrella
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try on another computer
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
    Apple Retail Store - Genius Bar       

  • Are you suppose to access UIView from another thread?

    A lot of UI events in my apps take place in another thread. So in my uivewcontroller, it catches a button click for example, it launches a NSThread with some parameter. The reason I decided to use a thread is because if the duration takes long the UI completely locks up. The thread then fetches for some result and access a pointer to a UIView (a UILabel for example) and update it's content.
    Now, is this model correct? I'm running in cases where setting the UILabel.text from the thread sometimes work, sometimes doesnt. I'm not sure how to debug. If I change the thread call to a standard method call (which blocks until results are ready) the text is updated correctly.
    Any hints?

    http://developer.apple.com/documentation/Cocoa/Conceptual/Multithreading/ThreadS afetySummary/chapter950_section2.html

  • Running another thread not to block UI

    I do some heavy operation inside the actionPerformed (load images from File Chooser, resize it for display and populate it in the ScrollPane etc) and I realize that the windows freezes until the whole operation is finished. And it doesn't really help that I do repaint() or validate(). I make some research and some of the books and people from forums say that I actually needed to dispatch another thread to run the heavy operation. So that I won't block the UI interface and can update things accordingly. But the problem is, I don't have any clear example to understand this concept. How to clean up the thread after operation finished. How can a thread notify the progress back and etc. I need to know how much images has been loaded so that I can update the progress bar and so on. Can anyone help me point out a good example? :D

    Think I should show my code snippet to you
    public void actionPerformed(ActionEvent e) {
            if (e.getSource() == BtnBrowse) {
                int returnVal = fcSelectFile.showDialog(this,"Select");
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    file= fcSelectFile.getSelectedFiles();
                    //This is where a real application would open the file.
                    Thread worker=new Thread(){
                            public void run(){
                                int count=0;
                                selectedFile=new JLabel[file.length]; 
                                while(count<file.length)
                                {   final int index=count;
                                    String actualFile=file[count].toString();
                                    String fileName= file[count].getName();
                                    selectedFile[count]=new JLabel(createImageIcon(actualFile,fileName));
                                    SwingUtilities.invokeLater(new Runnable(){
                                    public void run(){
                                    PnlImageHolder.add(selectedFile[index]);
                                    PnlImageHolder.repaint();
                                    PnlImageHolder.validate();
                                    count++;
                    worker.start();
                    ScpImageScroller.getViewport().add(PnlImageHolder);
    }

  • Linksys srw2048 unable to update firmware via xmodem (using hyperterm)

    I have three srw2048 series switches at my new job. One updated fine via the web interface the other two (after I found a windows machine to use the web interface) looked as though they were uploading the new file but after a reboot I was still on the old verison. So I broke out the console cable. What I have done is to Download Software to the switch (option 1) this kicks me over into xmodem. Once I am in xmodem I choose to send a file (the latest rom) using the 1K Xmodem protocol it immediately gives me retries and errors until it reaches a threshold that ends the session. During this whole process zero k is transferred.
    Boot Version 1.0.0.04
    Software Version 1.0.0.49
    Hardware Version 00.03.10
    The only thing I can think is that I must need older files to upgrade to an intermediary version before loading the latest 1.22 rom file.

    You might want to pose this question in the Linksys forums at http://homecommunity.cisco.com/
    Also, try another terminal program like Teraterm Pro.  Maybe it needs "classic" xmodem?

  • Updated Facebook via the Apps store.  Icon is "grayed" and will not open.  It also will not let me delete, to download again.  Anyone have this problem?

    Updated Facebook via the apps store.  Now, icon is "grayed" &amp; will not open, nor will it let me delete it, so I can re-download.  Has anyone had this problem?

    Do you have another disk or Mac connected that has Pages '09 from the Mac App Store installed? If so, the MAS will "see" it & will report it as installed. Unmount any & all drives, including Time Machine backups, that might have Pages '09 on them & then relaunch the MAS & see if you can download it.

  • IPhone - Trying to Update View from Separate Thread

    I am having trouble updating a view. My iPhone project is built from the Utility Application template. Upon startup, the Main View is loaded and some network communications are performed (on a separate thread). In response to the reply from the network, the toggleView method is called to switch to FlipSideView.
    This works (view changes) when I call toggleView from applicationDidFinishLaunching or by pressing the "i" button on the MainView. When I call toggleView after getting a response from the network, toggleView is called (as evidenced by a NSLog called within the toggleView method) but the View does not update.
    Does anyone have any ideas why this would happen?
    Could it have anything to do with the fact that I'm calling toggleView from another thread? If so, why would toggleView be called but not work?
    Thanks in advance,
    Daedalus
    - iPhone SDK Beta 8

    Update... I figured it out.
    To anyone else seeing this, when communicating between threads, you need to use the NSObject method performSelectorOnMainThread.
    Thanks.

  • TS1967 how to update games via itunes 11.01?

    how to update games via itunes 11.01...i cant see the application folder in itunes..and i dont see the option update  application...

    How many ID Apple have you got? more than one?
    If so, in you Itune go to Store->Account
    Log-in using the same email and password you used in your Iphone and click on see account.
    There you will see all your account information... Look for Purchase History and see if the apps your iphone is saying you have to update is on the list. If they are not listed on the Purchase History is probably because you got them using another ID Apple.
    But on the other hand if you see your apps on this list, try to click on "RESET ALL WARNIGS FOR BUYING AND DOWNLOADING ITEMS".
    Log-out and try again to update your apps using your Iphone.
    By all mean if you have to change you ID Apple in your Iphone go to SETTINGS->STORE on the botton you will see your ID Apple (click on it and a pop-up will show asking you to change you ID Apple) change for your new ID Apple and try all again.
    If any path I described here looks different  in you Itune is because mine is in Portuguese

  • Keymapping (follow up from another thread)

    To follow up on another thread, I checked out the keymappings and found most of what I was looking for.
    Only a couple of things I miss:
    1. SHIFT + TAB doesn't pull the text back with it if the text is not selected. I am convised most editors do this and I keep find myself trying to do it in JDev and it doesn't work, and then I go in a huff.
    2. Ctrl+K, Ctrl+L to perform a word match forwards or backwards, based purely on text in the document, ie. not syntax/context sensitive. This was one of my most used/most time saved features in Netbeans.

    Hi,
    don't understand what 1) is supposed to do. Can you explain this further? Winword and TextPad behave differently. I tried NetBeans and shift+tab is doing nothing.
    For 2) Is it the same as
    pressing ctrl+f to enter a search string and then continuing with F3 for forward matches and shift+F3 for backward matches? If you select a string before pressing ctrl+f then this string is added to the search list.
    If yes, then you can change the key mapping in Tools-->Preferences --> Accelerators to the keyboard combination you are most familiar with (look for "find").
    Frank

  • Black Screen on MBP, Can hear chime and can boot from HDD via another MBP!

    Hope someone can help me here, as I'm at my wits end.
    I've got two issues, one with my MacBook Pro 17in, 4GB RAM, 160GB 7200rpm (2008) and another with my iMac 24in. 4GB RAM, 500GB 7200rpm (2009).
    Firstly the MBP, left work on Thursday last week, got home, powered up the MBP and got a black screen!!! Tried resetting PRAM, SMC, booting in safe mode, removing and re-installing RAM, removing battery and mains power and leaving off overnight etc etc, yet nothing happens. Benn all over the forums and have not found any solution to get my beloved MBP working on it's own. I can boot off the HDD using another MBP 15in, re-install Snow Leopard and as far as I can tell the HDD is fine, as I have run disk utility and it tells me the HDD is OK.
    I can't figure this out and it's doing my head in, as I use this laptop for business use and just can't afford to go out and buy another Mac. I should point out that this MBP never had any issues when running on Leopard, but ever since I upgraded to Snow Leopard, I have had nothing, but trouble. I did a clean install, in fact I have done it at least twice, even erasing the HDD securely, both at 7pass and 35pass, yet I have had permissions issues regularly and on the odd occasion, I have also had the problem of the HDD not being recognised.
    The iMac is nearly the same, but the screen is working, although the iMac doesn't see the HDD no matter what way I do, again, reset PRAM, SMC, safe boot etc etc. In truth the iMac has been a lot more unreliable, but with the screen working, if I can get any solutions here, then I'll be working to work on that without the need or hassle of working via another.
    I think that the MBP is only just still under warranty, but the iMac definitely is, but I need at least one working for business use, so really only want to let Apple have one at a time to look at/repair etc.
    Ideally, as the HDD is working in the MBP, if I could get a solution to the black screen issue, then I could do without the iMac for whatever time it takes, so if there is anyone out there that can help, I'd be so grateful.
    One last thing, when I bought the iMac 24in., I also bought an iMac 20in., but I never upgraded the 20in. to Snow Leopard and to this day, it has worked flawlessly, without a single issue ever.
    Perhaps, I'm getting paranoid here, but there seems to me to be a link between the ongoing and regularly occurring problems with both Macs ant the upgrade to Snow Leopard. Why also, or is it just pure unadulterated coincidence that both the MBP and the iMac 24in have failed at pretty much the same time??!!!!
    I'm going mental here, so I hope someone out there has a better fix, then me overdosing on Prozac!!
    PS
    I'm not a mac expert, not good with a soldering iron either, but I'm capable of following good instructions.

    Concerning your imac, have you tried installing the OS on an external drive and running the iMac from that? My friend in Texas had her iMac's hard drive vanish, so we installed the OS on an external FireWire drive I happened to have and then restored her data from a recent backup. So far I haven't had time to install the drive in her iMac, so it's been running off of the external for a long time now. Perhaps you could do something like that so you could at least have the use of the iMac while your MBP is in the shop. Once you get the MBP back, you can send in the iMac.
    Be sure to report both of these to Apple and get case numbers so that you can document that the issues started while you were still under warranty--especially for the MBP that's about to go out of warranty.
    Good luck!

  • How can I pass an exception from one thread to another thread

    If I create a new class, that will extends the class Thread, the methode run() can not be use with the statement Throws Exeption .
    The question now: Is there any possibility to pass an exception from one thread to another thread?
    Thx.

    It really depends on what you want to do with your exception. Is there some sort of global handler that will process the exceptions in some meaningful way? Unless you have that, there's not much point in throwing an exception in a thread, unless you simply want the stack trace generated.
    Presuming that you have a global handler that can catch exceptions, nest your Exception subclass inside a RuntimeException:
    public class NestedRuntimeException extends RuntimeException
        private final m_nestedException;
        public NestedRuntimeException(final Exception originalException)
            super("An exception occurred with message: " + originalException.getMessage());
            m_nestedException;
        public Exception getNestedException()
            return m_nestedException;
    }Your global handler can catch the NestedRuntimeException or be supplied it to process by the thread group.

Maybe you are looking for

  • Table where product category assigned to supplier is stored in SRM

    Hi, We are on SRM 7.0. We have replicated material groups from ECC as product categories in SRM and vendor master also into SRM. Now I log into SRM portal as strategic purchaser and go to the following tab. Strategic Purchasing->Business Partner-> He

  • Pull out my soundblaster card.. now it doesnt work? (pics included)

    my soundblaster card was working fine. i had to change some sata cables in my computer and to get to it, i had to pull out the soundblaster card temporary. now the card doesnt produce any sound when i plug in my 3.5 headphone jack into it. fatality l

  • Display photo of uut in labview

    I'm using TestStand 3.5, but I'm developing the tests in LabVIEW8 (I'm also trying to customize the OI in LabVIEW - but that's an etirely different set of problems).  Anyway, what I'd like to do is when an operator selects a sequence file to open, af

  • Playlist problems on 6126

    I cannot create, edit, or modify playlists directly on the phone, nor using PC suite. In the PC suite Music Manager, I can select tracks (with the check mark in the box next to each one) installed on the memory card on the phone , but when I select '

  • How do I reset my software updates to default back to the apple updates ser

    How do I reset my software updates to default back to the apple updates server. I used ARD to send a unix command to download the software from my test server but now I don't know the exact path to point it back to the apple updates server. Below is