Results 1 to 16 of 16
  1. #1
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default How do I make a timer run in the background?

    I can get my timer to stop the thread and wait for the timer to finish. This is not what I want to d though. I want have the timer going and still be able to use the other buttons in my program. How can I do this?

    Java Code:
            int delay = 100; //milliseconds
    
            Timer t = new Timer(delay, taskPerformer);
            t.start();
    
            System.out.println( t.isRunning() );
            System.out.println( t.getDelay() );
    
            // wait 10 seconds before going on. 
            try {
            Thread.sleep(10000);
            }
            catch (Exception ea) {}
    
            t.stop();
    
      ActionListener taskPerformer = new ActionListener()
      {
      public void actionPerformed(ActionEvent evt)
      {
      System.out.println( "test" );
     labelHomeNumber[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
              labelHomeName[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
      }
      };
    Please help.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Can you clarify what exactly you're trying to do here?

    I see you start a Timer, but what is the timer's purpose. It is only changing the properties of one component. Then after you start the Timer you put all of Swing to sleep (including the timer), and then you stop the timer. Again, I am very unclear on just what your use-case is here. What are you trying to accomplish?

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    For instance if you just want the timer to continue for 10 seconds then stop, then you can get the system time before starting the timer, and then within the Timer's actionPerformed method, get the system time with each time the actionPerformed method is called, and if the difference is > 10000, stop the timer from within the actionPerformed method. This can be done simply with
    Java Code:
    long startTime = System.currentTimeMillis();
    int delay = 100; //milliseconds
    Timer t = new Timer(delay, taskPerformer);
    t.start();
    in the actionPerformed method
    Java Code:
    long currentTime = System.currentTimeMillis();
    long timeDifference = currentTime - startTime;
    
    if (timeDifference > 10000) {
      ((Timer)evt.getSource()).stop();
    }
    Last edited by Fubarable; 09-02-2009 at 05:11 AM.

  4. #4
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    Okay this is what I want to do is make the background of the labels for one player turn red if they receive a major penalty and then after one minute turn it to either the standard background color, yellow if they are one penalty from being kick out.
    I want to be able to turn it red for a minute and still be able to use the rest of the buttons on the board because the game will go on while they are in the penalty box.
    This is what I have for the button listeners.
    Java Code:
        buttonsHomeMajor[0].addSelectionListener(new SelectionAdapter() 
        {
          public void widgetSelected(SelectionEvent e) 
          {
            String temp = buttonsHomeMajor[0].getText();
            int num = Integer.parseInt(temp);
            num++;
            temp = Integer.toString(num);
            buttonsHomeMajor[0].setText(temp);
            if(num==(MAJORS-1))
            {
              labelHomeNumber[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
             labelHomeName[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
            }
            if(num>=MAJORS)
            {
              labelHomeNumber[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
              labelHomeName[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
              labelHomeNumber[0].setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
              labelHomeName[0].setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
              temp = Integer.toString(MAJORS);
              buttonsHomeMajor[0].setText(temp);
            }
            else
            {
              
              buttonsHomeMajor[0].setText(temp);
            }
            intHome[0]=1;
            labelHomeNumber[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
            labelHomeName[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
            System.out.println("before t.start()");
            int delay = 100; //milliseconds
    
            Timer t = new Timer(delay, taskPerformer);
            t.start();
    
            System.out.println( t.isRunning() );
            System.out.println( t.getDelay() );
    
            // wait 10 seconds before going on. 
            try {
            Thread.sleep(10000);
            }
            catch (Exception ea) {}
    
            t.stop();
          }
        });
      
        buttonsHomeMajor[1].addSelectionListener(new SelectionAdapter() 
        {
          public void widgetSelected(SelectionEvent e) 
          {
              String temp = buttonsHomeMajor[1].getText();
              int num = Integer.parseInt(temp);
              num++;
              temp = Integer.toString(num);
              buttonsHomeMajor[1].setText(temp);
              if(num==(MAJORS-1))
              {
                labelHomeNumber[1].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
               labelHomeName[1].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
              }
              if(num>=MAJORS)
              {
                labelHomeNumber[1].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
                labelHomeName[1].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
                labelHomeNumber[1].setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
                labelHomeName[1].setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
                temp = Integer.toString(MAJORS);
                buttonsHomeMajor[1].setText(temp);
              }
              else
              {
                
                buttonsHomeMajor[1].setText(temp);
              }
          }
        });
        
        buttonsHomeMajor[2].addSelectionListener(new SelectionAdapter() 
        {
          public void widgetSelected(SelectionEvent e) 
          {
            String temp = buttonsHomeMajor[2].getText();
            int num = Integer.parseInt(temp);
            num++;
            temp = Integer.toString(num);
            buttonsHomeMajor[2].setText(temp);
            if(num==(MAJORS-1))
            {
              labelHomeNumber[2].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
             labelHomeName[2].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_YELLOW));
            }
            if(num>=MAJORS)
            {
              labelHomeNumber[2].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
              labelHomeName[2].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_BLACK));
              labelHomeNumber[2].setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
              labelHomeName[2].setForeground(Display.getCurrent().getSystemColor(SWT.COLOR_WHITE));
              temp = Integer.toString(MAJORS);
              buttonsHomeMajor[2].setText(temp);
            }
            else
            {
              
              buttonsHomeMajor[2].setText(temp);
            }
              
          }
        });
         
        shell.open();
        
      } // end void TheGame
    
      ActionListener taskPerformer = new ActionListener()
      {
      public void actionPerformed(ActionEvent evt)
      {
      System.out.println( "test" );
      }
      };

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Okay this is what I want to do is make the background of the labels for one player turn red if they receive a major penalty and then after one minute turn it to either the standard background color, yellow if they are one penalty from being kick out. I want to be able to turn it red for a minute and still be able to use the rest of the buttons on the board because the game will go on while they are in the penalty box.
    You should have stated this in your first post. You do not need to use a background Thread, and you shouldn't be calling Thread.sleep on the EDT (please read the article Concurrency in Swing to find out more about the EDT).

    What you want to do is create a non-repeating Swing Timer, give it a delay time of 1000 ms which equals 1 second. If you look at the Timer API you'll find a method that you should call that will tell the timer not to repeat. To get this to work, simply turn your affected labels to red in your regular code, then start your non-repeating timer which has code to turn the labels back to their normal color.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Also, another suggestion to help us help you: Since your code snippet above is pretty much unintelligible to those not very familiar with the rest of your program it would help us a great deal if when you have a problem such as this, you create another very small program, the smallest bit possible, that demonstrates your problem but has no extraneous code unrelated to the problem and is compilable and runnable by us, an SSCCE (Short, Self Contained, Correct (Compilable), Example). This code would not require any outside resources or other classes.

    While posting this is not a requirement of getting help here, again it would help us a great deal, and by doing so, would greatly increase your chances of getting decent help quickly. Best of luck.

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    For e.g., here's my example of an SSCCE:
    Java Code:
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;
    
    public class FuSwing {
       
       protected static final int INACTIVATE_DELAY = 3000;
       private static int inactiveIndex = -1;
    
       private static void createAndShowUI() {
          final JPanel panel = new JPanel();
          
          // an array of 3 JButtons
          final JButton[] buttons = new JButton[3];
          final Random random = new Random();
          
          // each button simply prints its name when pressed
          ActionListener btnlistner = new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                System.out.println("Button \"" + e.getActionCommand() + "\" pressed");
             }
          };
          // create buttons in array, add to panel, add actionlistener
          for (int i = 0; i < buttons.length; i++) {
             buttons[i] = new JButton("Button " + (i + 1));
             buttons[i].addActionListener(btnlistner);
             panel.add(buttons[i]);
          }
          
          // another button that will choose a random button from the array, and 
          // inactivate that button and itself for 3 seconds, then 
          // reactivate both buttons
          final JButton inactivateBtn = new JButton("Inactivate Random Button");
          panel.add(inactivateBtn);
          inactivateBtn.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                // choose random index in array
                inactiveIndex = random.nextInt(buttons.length);
                
                // inactivate the random array button and the inactivate button
                buttons[inactiveIndex].setEnabled(false);
                inactivateBtn.setEnabled(false);
                
                // create a timer that reactivates both buttons
                Timer timer = new Timer(INACTIVATE_DELAY, new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                      buttons[inactiveIndex].setEnabled(true);
                      inactivateBtn.setEnabled(true);
                   }
                });
                // don't allow repeats
                timer.setRepeats(false);
                // tell timer to start
                timer.start();
             }
          });
    
          JFrame frame = new JFrame("FuSwing");
          frame.getContentPane().add(panel);
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Oh, and in response to this threads title: Timers always work in the background. Or perhaps better to state, they always count in the background, but everything done in the actionPerformed method is done in the EDT.

  9. #9
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    Thank you for the help.

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

  11. #11
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    You're quite welcome. Is your problem solved?
    Yes now I have a working time I understand. However it keeps giving me an error and will not change the label colors from red back to system.
    Java Code:
            Timer timer = new Timer(INACTIVATE_DELAY, new ActionListener() 
            {
               public void actionPerformed(ActionEvent e) 
               {
                // buttonsHomeMajor[0].setEnabled(true);
                 labelHomeNumber[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
                 labelHomeName[0].setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
                 System.out.println(" Timer timer = new Timer(INACTIVATE_DELAY, new ActionListener() ");
               }
            });
    It just gives an error.
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at TheGame$1$1.actionPerformed(TheGame.java:178)

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    The NPE error tells you precisely which line is throwing the error, and then it becomes a matter of simply finding which object you are trying to dereference on that line that is null. You have this information (line numbers et al...) and we don't, so the ball's in your court.

    If this doesn't help, then as noted above, create an SSCCE and post it.

  13. #13
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Another option that is less likely to get you a solution but that sometimes work is to package your source code into a jar file, change the extension to zip and post that file here.

  14. #14
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    So I cut this down to 128 lines from over a 1,000(16 players for each team.)
    I'm sorry its still quit long at 128 lines but could not cut it down anymore.
    I get an error when I try to re-enable the buttons and change the background on the label.
    Java Code:
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.Timer;
    
    import org.eclipse.swt.SWT;
    import org.eclipse.swt.events.SelectionAdapter;
    import org.eclipse.swt.events.SelectionEvent;
    import org.eclipse.swt.graphics.Font;
    import org.eclipse.swt.layout.FillLayout;
    import org.eclipse.swt.layout.FormAttachment;
    import org.eclipse.swt.layout.FormData;
    import org.eclipse.swt.layout.FormLayout;
    import org.eclipse.swt.widgets.Button;
    import org.eclipse.swt.widgets.Composite;
    import org.eclipse.swt.widgets.Display;
    import org.eclipse.swt.widgets.Label;
    import org.eclipse.swt.widgets.Shell;
    
    /**
     * @author caryr
     *
     */
    public class Main
    {
      static Button buttonsHomeMajor;
      static Button buttonsHomeMinor;
      static Label labelHomeName;
      static Shell shell;
      int MAJORS = 2;
      int MINORS = 2;
      int TOTAL =2;
      final static int INACTIVATE_DELAY = 3000;
      private static void TheGame (Shell s)
      {
         shell = new Shell(s, SWT.NO_TRIM|SWT.ON_TOP);
        //` final GroupBox ge = new GroupBox(s, SWT.SHADOW_ETCHED_IN);
         shell.setBounds(shell.getDisplay().getPrimaryMonitor().getBounds());
         shell.setLayout(new FillLayout());
         Composite comp = new Composite(shell, SWT.NONE);
         comp.setLayout(new FormLayout());
         Font font = new Font(shell.getDisplay(), "Times New Roman",24, SWT.BOLD); 
        buttonsHomeMajor = new Button(comp, SWT.PUSH);
        buttonsHomeMinor = new Button(comp, SWT.PUSH);
        labelHomeName  = new Label(comp, SWT.CENTER);
        int top = 14;
        int bottom = 18;
        int left = 25;
        int right = 39;
        FormData data = new FormData();
        data = new FormData();
        data.top = new FormAttachment(top);
        data.left = new FormAttachment(left);
        data.right = new FormAttachment(right);
        data.bottom = new FormAttachment(bottom);
        labelHomeName.setLayoutData(data);
        labelHomeName.setText("The Bruser");
        labelHomeName.moveAbove(null);
        labelHomeName.setFont(font);
        top = 14;
        left = 40;
        right = 45;
        data = new FormData();
        data.top = new FormAttachment(top);
        data.left = new FormAttachment(left);
        data.right = new FormAttachment(right);
        data.bottom = new FormAttachment(bottom);
        buttonsHomeMinor.setLayoutData(data);
        buttonsHomeMinor.setText("0");
        buttonsHomeMinor.moveAbove(null);
        buttonsHomeMinor.setFont(font);
        left = 47;
        right = 53;
        data = new FormData();
        data.top = new FormAttachment(top);
        data.left = new FormAttachment(left);
        data.right = new FormAttachment(right);
        data.bottom = new FormAttachment(bottom);
        buttonsHomeMajor.setLayoutData(data);
        buttonsHomeMajor.setText("0");
        buttonsHomeMajor.moveAbove(null);
        buttonsHomeMajor.setFont(font);
        buttonsHomeMajor.addSelectionListener(new SelectionAdapter() 
        {
          public void widgetSelected(SelectionEvent e) 
          {
    
            buttonsHomeMajor.setEnabled(false);
            buttonsHomeMinor.setEnabled(false);
            labelHomeName.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_RED));
            // create a timer that reactivates both buttons
            Timer timer = new Timer(INACTIVATE_DELAY, new ActionListener() 
            {
               public void actionPerformed(ActionEvent e) 
               {
                 //This is giving me errors.
                 buttonsHomeMajor.setEnabled(true);
                 buttonsHomeMinor.setEnabled(true);
                 labelHomeName.setBackground(Display.getCurrent().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND));
                 System.out.println(" Timer timer = new Timer(INACTIVATE_DELAY, new ActionListener() ");
               }
            });
            // don't allow repeats
            timer.setRepeats(false);
            // tell timer to start
            timer.start();
            String temp = buttonsHomeMajor.getText();
            int num = Integer.parseInt(temp);
            num++;
            temp = Integer.toString(num);
            buttonsHomeMajor.setText(temp);     
          }
        });    
        shell.open();
      } // end void TheGame
      public static void main(String[] args)
      {
        Display display = new Display();
        Shell shell = new Shell(display);
        TheGame(shell);
        while (!shell.isDisposed ()) 
        {
          if (!display.readAndDispatch ()) display.sleep ();
        }  // end while
        display.dispose();
      } // end main
    }  // end class Main

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    You appear to be mixing Swing and SWT together in one program -- very curious. This may also make it difficult for others to be able to debug. I'm curious why you're doing it this way.

  16. #16
    caryr is offline Member
    Join Date
    Nov 2008
    Location
    Colorado
    Posts
    18
    Rep Power
    0

    Default

    I do not know why I did that I would like to keep it all in SWT if at all possible.

Similar Threads

  1. How to Run a .exe in background???
    By jazz2k8 in forum New To Java
    Replies: 9
    Last Post: 01-21-2011, 12:27 PM
  2. Image as background
    By Java.child in forum AWT / Swing
    Replies: 2
    Last Post: 10-03-2008, 12:37 AM
  3. Replies: 0
    Last Post: 04-04-2008, 03:46 PM
  4. How to make the JTextArea background invisible
    By bradder in forum AWT / Swing
    Replies: 1
    Last Post: 12-05-2007, 07:30 PM
  5. Set the background in Java
    By barney in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 08:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •