Updating JPanel during a loop.

Here's the deal: my first class (first file) which extends a JFrame, creates a JFrame and adds some JPanels to it (with buttons, JTextFields etc), after i press one button it creates an instance of a class Algorithm that is in another file, and calls a function solve() from that class, which counts some things. In that function (the start() one) there are 2 loops, and it returns a stack. The thing is I want a JTextField from that JFrame to be updated with every new loop (so it would show numbers 1,2,3,4,etc while the function was being executed). If they were in a single file than there would be no problem (simply message.setText(loopNumber+"");), but since they are in different files I have no idea how to do it. Should I try making a new thread for the solve() function or what?
It would be something like this, file1 (tho the new Algorithm part isnt in main() but it is executed after a button is pressed):
public class Frame extends JFrame{
         variables
         private JTextField message; // this one is in one of the JPanels attached to the JFrame
main(){
       JFrame frame = new JFrame();
       new algorithm = new Algorithm(passes some variables);
       algorithm.solve();
}Second file:
public class Algorithm{
       some variables,
       constructor etc;
       int numer = 0;
       public void solve(){
                for(int i=0; i < 10; i++){
                          numer += 1;
                          something happens here;
}And I want to change the "message" whenever "number" changes.

Someone told me I should make a new thread for the soultion() in order to "repaint" the JPanel that contains the "message"...Not for setting a text field, you shouldn't. But you're getting dangerously close to mashing up your GUI and "business" logic with inappropriate relationships. You may want to have a look at the Observer pattern, where your algorithm can notify any observers of state changes, and the observers can handle that information as they see fit.
~

Similar Messages

  • I can't update Instuments and Apple Loops

    I don't know what is going on here with the Garageband update "Instruments and Apple Loops".
    Everytime when I try to install I got this error below:
    "The update “GarageBand Instruments and Apple Loops” can’t be installed.
    The update could not be verified. It may have been corrupted or tampered with during downloading. The update will be downloaded and checked again the next time that Software Update runs."
    I tried many times and no sucess.
    I tried to repair the HD and permissions and still nothing.
    This only occurs with this update, the others work fine.
    I search the forum for same problem and I found a lot of treads tell to choose the third option ( install from DVD) but I dont have this option here in my Garageband. When I click in a instrument the garageband show me a window with two options. "Download Now" or "Download Later".
    Any suggestion ??
    Thanks
    Adriano
    Macbook Pro i7 2.2GHz
    Mac OS X 10.7.4
    4Gb Ram
    300+ free HD
    Garabeband 6.0.5

    HI Dahoveed,
    When i bought this macbook the software is OS X Mountain Lion (Early 2011)
    btw i got what you mean.
    Thank You.

  • Timer stops during in loop while continuous operation

    Hi, all
    I have a sequence loop in while loop that is controlled by a "elasped time function".  After several hours of program operation, the timer stops and causes cycle to freeze.  This always happens (about 1-10 hours after run start) despite the length of cycle steps.  I cannot determine the cause of this problem and any insight is appreciated. I use Labview 8.2v and have attached the vi and screen capture of the function loop.
    Attachments:
    RH cycling.vi ‏394 KB
    block.JPG ‏125 KB

    swsyoon wrote: I'm just wondering if all the loop needs a wait statement. Is it more stable for the program?
    Wy wait comment was just generi. Most likely it is not the caouse of your problem. Any while loop should only spin as often as needed. For example, to update a timer, the loop rate should depend on how many decimal digits of the time you need to show. SInce your code runs for a long time, maybe once/second is entirely sufficient.
    Still, this is certainly not the cause of your problems but it is impossible to debug your VI.
    We cannot run your VI, because of missing subVIs.
    Do you know if any of your subVIs contain third party DLLs?
    Your entire code structure is designed inside-out, making very little sense.
    What's the story with the start button? Are you using the "continuous run" button to operate this VI??? Don't!!!
    What's the story with the big case structure tied to the tab structure? Since your code is inside-out, operating the tab during run makes no difference in the code. Large portions of code are inaccessible.
    You have extrememly confusing code the way you wire in and out of frame one at the bottom. Maybe that code at the bottom should all go inside the first frame.
    You error handling is no handling at all. You just display the error indicators. Shouldn't the code depends a little bit on error status?
    Even the UI is confusing. Labeling a stop switch with ON/OFF makes no sense. You turn STOP to OFF to stop the VI.
    Can you check for memory leaks? Run the VI for extended periods and see if the memory use increases over time.
    Check all your subVIs. Who wrote them? All your subVIs deal with instruments and visa resources. Do you properly close all references before creating new ones? Can you attach a few of your subVIs? You constantly open Labjacks (last frame)... do you ever close them??
    All indications point to a serious resource leak somewhere.
    It would really be beneficial to tear down most of the code a rewrite it from scratch using a more reasonable design template. The outermost structure needs to be a while loop. What good is a tab structure if the code in the other tabs cannot run?
    LabVIEW Champion . Do more with less code and in less time .

  • Acrobat XI 11.0.06 update fails during install

    acrobat XI 11.0.06 update fails during install. Any advice or help? Here is the installer log contents:
    Jan 17 00:32:34 fox.local installd[5955]: PackageKit: ----- Begin install -----
    Jan 17 00:33:44 fox.local installd[5955]: PackageKit: Install Failed: Error Domain=PKInstallErrorDomain Code=112 "An error occurred while running scripts from the package “AcrobatUpd11006.pkg”." UserInfo=0x7fb9615c5160 {NSFilePath=./postinstall, NSURL=file://localhost/Volumes/AcrobatUpd11006/AcrobatUpd11006.pkg#payload.pkg, PKInstallPackageIdentifier=com.adobe.acrobat.a11.AcrobatUpd11006, NSLocalizedDescription=An error occurred while running scripts from the package “AcrobatUpd11006.pkg”.} {
            NSFilePath = "./postinstall";
            NSLocalizedDescription = "An error occurred while running scripts from the package \U201cAcrobatUpd11006.pkg\U201d.";
            NSURL = "file://localhost/Volumes/AcrobatUpd11006/AcrobatUpd11006.pkg#payload.pkg";
            PKInstallPackageIdentifier = "com.adobe.acrobat.a11.AcrobatUpd11006";
    Jan 17 00:33:44 fox.local Installer[11306]: Install failed: The Installer encountered an error that caused the installation to fail. Contact the software manufacturer for assistance.
    Jan 17 00:33:44 fox.local Installer[11306]: Displaying 'Install Failed' UI.
    Jan 17 00:33:44 fox.local Installer[11306]: 'Install Failed' UI displayed message:'The Installer encountered an error that caused the installation to fail. Contact the software manufacturer for assistance.'.

    You are right. There are a lot more self-support tools available in Windows
    than in MacOS. All you ever get on a Mac is "That didn't work: -304998173".
    Thanks for your insights.
    Re: acrobat XI 11.0.06 update fails during install
    created by Bill@VT <http://forums.adobe.com/people/Bill%40VT>  in Acrobat
    Installation & Update Issues - View the full discussion
    <http://forums.adobe.com/message/6040206#6040206>
    The upgrade is not the 11.0.06, but that is an update. The upgrade is what
    you can purchase if you had a previous version of Acrobat (at least AA 9).
    The upgrade is substantially less in price than the full product. With the
    upgrade you also have to have the SN of the previous product available for
    the install. That is why I asked about the upgrade. Once you install AA XI,
    then going to 11.0.06 is a free update (updates are changes in the
    sub-version and are done quarterly or when there is a critical security
    issue).  You can often fix installations by running a repair. In Windows
    that is done either from Help>Repair or from the Control Panel. I do not
    know the equivalent of the Control panel in the MAC. In any case I am glad
    you got it fixed.
    Please note that the Adobe Forums do not accept email attachments. If you
    want to embed a screen image in your message please visit the thread in the
    forum to embed the image at http://forums.adobe.com/message/6040206#6040206
    Replies to this message go to everyone subscribed to this thread, not
    directly to the person who posted the message. To post a reply, either reply
    to this email or visit the message page:
    http://forums.adobe.com/message/6040206#6040206 To unsubscribe from this
    thread, please visit the message page at
    http://forums.adobe.com/message/6040206#6040206. In the Actions box on the
    right, click the Stop Email Notifications link.  Start a new discussion in
    Acrobat Installation & Update Issues at Adobe Community
    <http://forums.adobe.com/choose-container!input.jspa?contentType=1&container
    Type=14&container=4714>  For more information about maintaining your forum
    email notifications please go to
    http://forums.adobe.com/thread/416458?tstart=0.

  • How to see the last updates made during Power Nap?

    Hello guys,
    I am using MacBook Pro with Retina Display with Power Nap turned on. I think it's a great feature, but I wouyld like more control — to be able to see the updates it has made while sleeping.
    Is there any way to see the last updates made during Power Nap? Maybe some logs etc.

    You can see updates installed via Software Update by clicking on the Apple > About this Mac > more info > System Report > scroll down to Software > Installations. That is a comprehensive list - you won't find a separate list of the last hour or whatever (that I know of). There might be a terminal command for that - or not - I don't know of one.
    FWIW, I like to know what updates are being installed when, so I do not allow automatic download/installs of anything - I allow automatic checking so I get a notification that an update is available, but then I prefer to choose if/when I will download and install.

  • Redraw a JPanel during runtime

    Hi there,
    Im trying to redraw a whole JPanel during runtime.
    So basically I have this panel:
    public JPanel panel1 = new JPanel() {
         public void paintComponent(Graphics g) {
               super.paintComponent(g);
    }That panel is added to my JFrame during initialisation.
    I added an actionListener to a JButton that creates a whole new JPanel
    Then i try to set the default (panel1) to the new generated JPanel:
    public void actionPerformed(ActionEvent e) {
         if(e.getSource().equals(myButton)) {
         JPanel newPanel = generateNewPanel();
         panel1 = newPanel;
         panel1.validate();
         panel1.repaint();
    }After i done all that, it didn't redraw the jpanel
    Please advise on what I have gotten wrong.
    Thanks
    Edited by: Ruski on Mar 10, 2009 1:35 PM

    To be honest i recommend not using netbeans to code gui for a long term project which relies on code. NetBeans is useful - only for creating gui stubs and for throwaway gui prototypes but not in the long run, which is of my own experience. To be fair i have many years of coding gui's way back in the days when awt only started up.
    i know gui in java is "crap" because of it's repeated code and tedious mechanism to generate ui windows so to do that you might as well hard code it yourself using a proper or better IDE - "ECLIPSE" or any linux based code editors are good also. This way you learn much more about guis.

  • TS3694 ?? I have Iphone 3G , when i update software & during iphone restore software 3.1.2. i got error 1602. how i can solve it

    ?? I have Iphone 3G , when i update software & during iphone restore software 3.1.2. i got error 1602. how i can solve it ?

    http://support.apple.com/kb/TS3694#USB

  • HT1338 Update fails during download of Aperture. I have 10.8.3

    Aperture update fails during download on my MacBook Pro laptop.

    Try setting up another admin user account to see if the same problem continues. If Back-to-My Mac is selected in System Preferences, the Guest account will not work. The intent is to see if it is specific to one account or a system wide problem. This account can be deleted later.
    Isolating an issue by using another user account
    If the problem is still there, try booting into the Safe Mode.  Shut down the computer and then power it back up. Immediately after hearing the startup chime, hold down the shift key and continue to hold it until the gray Apple icon and a progress bar appear. The boot up is significantly slower than normal. This will reset some caches, forces a directory check, and disables all startup and login items, among other things. If the system operates normally, there may be 3rd party applications which are causing a problem. Try deleting/disabling the third party applications after a restart. For each disable/delete, you will need to restart if you don't do them all at once.
    Safe Mode
    Safe Mode - About
    General information.
    Isolating issues in Mac OS X
    Troubleshooting Permission Issues
    Step by Step to Fix Your Mac
    If you still can't get the App Store to work, I'd contact them via the App Store Support link.

  • IOS Update stalled during install...should I reboot?

    Doing a required update to the software on my mac mini (so I could then update the ios on my iphone4s)  seems that the update stalled during the 'installing files' step.  Should I power off and try again?  Help...

    Basic troubleshooting from the User's Guide is reset, restart, restore (first from backup then as new).  Try each of these in order until the issue is resolved.

  • Unable to click on buttons during timed loop .

    Hi !
    I have a timed loop with a cadence set by user . And when the loop is running, I can not push any button of my GUI to stop this....
     I have to wait until error or I stop the run.
    I can't put the diagram it's too big and I think I haven't the right but do you have some ideas ?
    Ask me for more details .
    Thanks
    Solved!
    Go to Solution.

    bejard wrote:  The Timed loop is just in an event structure and I set 10 ms or 100 ms .
    The program is running correctly (with this Timed loop of 10ms/100 ms) as the beginning but I still can't push any button or change tabs during the loop .
    You should not have long processes inside of an event case.  What is supposed to stop your timed loop?
    I think you have the "Lock front panel until event case completes" option turned on.  This will not allow you to press anything until everything in  that event case (including the timed loop) completes.
    In my experience, using a timed loop in a Windows system is a complete waste and often adds more overhead and issues.  Instead, I really think you need to change over to use a State Machine.  When the button is pressed, you just tell your state machine to go into the state the runs some of the code inside of your timed loop.  You can use the state with the event structure to time your loop.  So you can go back and forth from your event structure state to your processing loop.  Just set the timeout on the event structure to whatever loop rate you actually want.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • Getting Key Events during animation loop

    I'm having a problem recieving Key events during my animation loop. Here is my example program
    import java.awt.*;
    import java.awt.image.BufferStrategy;
    import javax.swing.JPanel;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import java.util.ArrayList;
    import java.awt.event.*;
    import java.util.Iterator;
    import GAME.graphics.Animation;
    import GAME.sprites.MainPlayer;
    import GAME.util.MapData;
    import GAME.input.*;
    public class ImageTest extends JFrame {
        private static final long DEMO_TIME = 20000;
        private Animation      anim;
        private MainPlayer     mPlayer;
        private MapData               mapData;
        private InputManager      inputManager;
        private GameAction moveLeft;
        private GameAction moveRight;
        private GameAction exit;
        public ImageTest()
         requestFocus();
         initInput();
         setSize(1024, 768);
         setUndecorated(true);
         setIgnoreRepaint(true);
         setResizable(false);
         loadImages();
         anim = new Animation();
            mPlayer = new MainPlayer(anim);
            setVisible(true);
            createBufferStrategy(2);
            animationLoop();
         // load the player images
         private void loadImages()
              // code that loads images...
         // Initialize input controls
         private void initInput() {
            moveLeft = new GameAction("moveLeft");
            moveRight = new GameAction("moveRight");
            exit = new GameAction("exit",
                GameAction.DETECT_INITAL_PRESS_ONLY);
            inputManager = new InputManager(this);
            inputManager.setCursor(InputManager.INVISIBLE_CURSOR);
            inputManager.mapToKey(moveLeft, KeyEvent.VK_LEFT);
            inputManager.mapToKey(moveRight, KeyEvent.VK_RIGHT);
            inputManager.mapToKey(exit, KeyEvent.VK_ESCAPE);
        // Check player input
        private void checkInput(long elapsedTime) {
            if (exit.isPressed()) {
                System.exit(0);
            if (mPlayer.isAlive()) {
                float velocityX = 0;
                if (moveLeft.isPressed()) {
                    velocityX-=mPlayer.getMaxSpeed();
                if (moveRight.isPressed()) {
                    velocityX+=mPlayer.getMaxSpeed();
                mPlayer.setVelocityX(velocityX);
        // main animation loop
        public void animationLoop() {
            long startTime = System.currentTimeMillis();
            long currTime = startTime;
            while (currTime - startTime < DEMO_TIME) {
                long elapsedTime =
                    System.currentTimeMillis() - currTime;
                currTime += elapsedTime;
                checkInput(elapsedTime);
                mPlayer.update(elapsedTime);
                // draw and update screen
                BufferStrategy strategy = this.getBufferStrategy();
                Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
                if (!(bgImage == null))
                     draw(g);
                     g.dispose();
                     if (!strategy.contentsLost()) {
                         strategy.show();
                // take a nap
                try {
                    Thread.sleep(20);
                catch (InterruptedException ex) { }
        public void draw(Graphics g) {
            // draw background
            if (bgImage != null)
                         // draw image
                 g.drawImage(mPlayer.getImage(), (int)mPlayer.getX(), (int)mPlayer.getY(), null);
    }My InputManager implements KeyListener. When running print statements on my Key events, they are not being called until after the animation demo is done running. Can someone help me with getting the Key events to update during the animation loop? Thank you!

    I've used the post from Abuse on the following thread with success. Maybe it will clue you in to what you might be doing wrong:
    http://forum.java.sun.com/thread.jsp?forum=406&thread=498527

  • A question about how to change a button in a JPanel during runtime

    I am a beginner of GUI. Now I am trying to change a specific component, a button, when the application is running. For example, I have 3 buttons in a JPanel. Each button has its onw icon. If I click one of them, it will change its icon, but the other two don't change. I don't know if there is any method for changing a specific component during runtime. If any one knows please let me know, I will appreciate that very much!!!

    What you're going to have to do is loop inside the actionlistener but still have accessability to click while its looping. I don't know much about it, but I think you're going to need a thread. Try something like this... (it doesn't work yet, but I have to take off)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class buttonxdemo extends JFrame implements ActionListener{
      Buttonx mybutton;
      //set it all up, make it look pretty  =]
      public buttonxdemo()
           mybutton = new Buttonx("default");
           getContentPane().add(mybutton.thebutton);
           mybutton.thebutton.addActionListener(this);
           this.setDefaultCloseOperation(3);
           this.setSize(200,200);
      public void actionPerformed(ActionEvent ae){
        if (ae.getSource() == mybutton.thebutton)
             if (mybutton.keepGoing)
               mybutton.keepGoing = false;
                else if (!mybutton.keepGoing)
                     mybutton.keepGoing = true;     
          mybutton = new Buttonx(/*Icon,*/"My Button");
          //getContentPane().remove(mybutton);
          //getContentPane().add(mybutton.thebutton);
          mybutton.startstop();
      }//actionperformed
      static void main(String args[])
           new buttonxdemo().show();
    } //movingicondemo
    class Buttonx extends Thread{
      public boolean keepGoing;
      //public Icon ICx;            //perhaps an array, so you can loop through?
      public String strbuttonx;
      public JButton thebutton;     //may have to extend JFrame?
      public Buttonx(/*Icon IC,*/ String strbutton){
        //ICx = IC;
        strbuttonx = strbutton;
        thebutton = new JButton(strbuttonx);
      public void startstop()
        int i = 0;
        while (keepGoing)
          thebutton.setLabel(strbuttonx.substring(0,i));
          //if an array of Icons ICx
          //thebutton.setIcon(ICx);
    i++;
    if (i > strbuttonx.length() - 1)
    i = 0;
    try
         Thread.sleep(1000);
    catch (InterruptedException ie)
         System.out.println("sleep caught: " + ie);
    }//startstop()
    }//buttonx
    kev

  • Phtosmart wireless update fails. - uninstall loop ensues.

    HP Install Error - Windows 7: Anyone help with scenario below?
    Unsolicited Photosmart wireless HP109n-z software update fails on install. Report raised then continue. Asks to wait while unsuccessful install is removed. THis fails as existing uninstall still in progress. NO other uninstall visible, so cannot remove. Clear down message boxes and select restart message from installer. Reboot simply takes you back to same loop!
    Solution xml placed on desktop still requires the uninstall process to be completed. I suspect a registry flag and manual uninstall may be solution. What reg settings required? What do remove from file system?
    This message constantly interrupted by continuing update/fail/restart requests!

    Hi there @Adam3of7 , welcome back!
    I read your post about the issue you're having installing your Photosmart Wireless B109n model on your Windows 7 system. I'd like to offer you my suggestion!
    Click this link and try these steps for the installation issue: A 'Fatal Error' (MSI error) Displays on the Computer During HP Software Installation in Windows
    Please let me know what happens in detail. Include screen shots if you'd like too!
    Have an awesome day!
    R a i n b o w 7000I work on behalf of HP
    Click the “Kudos Thumbs Up" at the bottom of this post to say
    “Thanks” for helping!
    Click “Accept as Solution” if you feel my post solved your issue, it will help others find the solution!

  • Software Update not finding missing loops

    I've just updated my MacBook Pro (OS X 10.6.8) from iLife 09 to iLife 11.
    In Garageband most of the loops are missing (greyed out). When I click on one I'm given the option of downloading later or now. When I choose 'now' it opens Software Update which searches for updates and tells me that all my software is up to date. If I click on a missing look again the message says that the software instrument or Apple Loop is currently being installed and that I should open Software Update for additional information.
    How do I install all the missing loops if Software Update is telling me all my programs are up to date?
    Graham

    What do you have in...
    /Library/Receipts folder?
    Getting them Directly is better antway.
    The combo update for PowerPC-based Macs...
    http://www.apple.com/support/downloads/macosx10411comboupdateppc.html
    The combo update for Intel-based Macs...
    http://www.apple.com/support/downloads/macosx10411comboupdateintel.html
    Mac OS X 10.5.4 Update ...
    http://www.apple.com/support/downloads/macosx1054update.html
    Repair Permissions after re-install, then reboot again.

  • How to get updated values from the loops while they are running

    Hello,
            I am having difficulty solving a very basic problem, how to access the updated values from the 'FOR loop' while its running?  Basically, the VI  I am currently working on calls two sub VIs. Each sub VI has a for loop, and both VIs may or may not run for same number of iterations. My goal is to read the values at each terminal inside the loop of both sub VIs, in the Main VI. I tried to achieve it using Global Variables, but in main VI it displays only the last iteration value from both sub VIs. Could anyone please tell me whrere am I going wrong? Is there any other/better way to achieve this.
    I appreciate any input on this issue.  
    Kudos are (always) welcome for the good post. :-)
    Solved!
    Go to Solution.

    Dennis,
                In attached VI, I can see the values changing in the sub VI from the main VI with the numeric indicator whose reference is passed on to the sub VI. Now if I wanted to store or use those values how do I do that? I tried to chnge the indicator to control and read from it (in the attached VI) , but the the indicator updates only once. Tried to create a property node and read the Value from it and it didn't work either.
    Thanks in Advance!
    -Nilesh
    Kudos are (always) welcome for the good post. :-)
    Attachments:
    main-1.vi ‏8 KB
    sub-1.vi ‏9 KB

Maybe you are looking for

  • Lenovo N100 won't boot!

    Almost two weeks ago I shut my computer down one night and the next morning it would not boot. It goes through the motions but before starting windows i get a blue screen for a split second and then it restarts. I got a boot disk for windows vista an

  • Can I add a second login account to my ipad?

    I would like to have 2 passwords and 2 login accounts for my ipad--one for my business content and one for my kids names.  They love to play game with my ipad but I prefer not to give them free rein of my content including my email.  Can I do this so

  • Regarding ABAP report

    Hi Experts, I have to create a report in the following format: Report AA   |Date     |      X     |Y      |     Z    |     XX   |     YY 11:30|05/10/08| 989     |4567 |     B   |     A    |     A      Maria Smith      123  Main St.       Apt.      99

  • How to revive my ipod

    well im on windows. my ipod wont mount, so i cant do anything through itunes.. and the windows refort tool cant reformat it. the ipod has got a file corruption error (folder with excalmation mark) and turn on but wont get past the start-up screen. oh

  • Problem with Activities

    Hello, I'am facing a problem within the CIC. Whenever I ceate a new activity, the actual date is automatically filled with the current date. If I do this the "normal" way (SAP menu -> Activities -> Maintain Activities) the actual date stays empty, ev