Results 1 to 8 of 8
  1. #1
    mkj
    mkj is offline Member
    Join Date
    Jan 2012
    Posts
    15
    Rep Power
    0

    Default Timer and for loop

    hi all,
    In the following code: i want to move the car horizontally from a position 1 to a position 2, by using a for loop that display the car at various positon between position 1 and 2.
    To do so i have created a button and i have assigned an actionlistener to this button, where i have placed the for loop. In order to smootly move the car i thought of creating a timer, that seperate (delay) the steps of the for loop by a duration .
    By executing the code below i am having the following problems:
    1-the timer start even when the button is not pressed
    2-the car is directly moved to the final position, as if the timer is not affected by the for loop
    3-the phrase you clicked a button is displayed in the terminal every 1 sec.
    can any one help me in fixing the code below or telling me what other metod should i use to solve my problem

    Java Code:
    ActionListener buttonAction = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    System.out.println("you clicked a button");
    for(int i=0; i<100;i++){
    car.setBounds(2+i,260,50,50);
    }
    }
    };
    Timer timer = new Timer(1000,buttonAction);
    timer.start();
    button1.addActionListener(buttonAction);

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

    Default Re: Timer and for loop

    Suggestions:
    • I think you may be a little confused on how the Timer works -- you would use it in place of the for loop, not with the for loop.
    • You would need two ActionListener objects -- one for the JButton, and one for the Timer since they have two very different Actions.
    • In the JButton's ActionListener you would create and start the Timer, that's it.
    • In the Timer's ActionListener, you would advance the sprite until a maximum value of some type is reached, and then you would stop the Timer.

  3. #3
    mkj
    mkj is offline Member
    Join Date
    Jan 2012
    Posts
    15
    Rep Power
    0

    Default Re: Timer and for loop

    Thanks for your reply although i didn't get all what you have mentioned
    Quote Originally Posted by Fubarable View Post
    Suggestions:
    • You would need two ActionListener objects -- one for the JButton, and one for the Timer since they have two very different Actions.
    • In the JButton's ActionListener you would create and start the Timer, that's it.
      ActionListener buttonAction = new ActionListener(){
      public void actionPerformed(ActionEvent e){

      Timer timer = new Timer(1000,animation);
      timer.start();
      }
      };
    • In the Timer's ActionListener, you would advance the sprite until a maximum value of some type is reached, and then you would stop the Timer.
      i dont understand how to advance the sprite if i dont no a for loop a while or a while do loop
      final ActionListener animation = new ActionListener(){
      public void actionPerformed(ActionEvent e){
      System.out.println("you clicked a button");

      car.setBounds(2+i,260,50,50);

      }};
      thanks in advance

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

    Default Re: Timer and for loop

    Please show your code in [code] [/code] not [quote] [/quote] tags.

    Also if you change your code and have a problem with it, please fill us in with the details of the problem, and if there is anything specific that you don't understand about my recommendations, please let us know.

    Luck!

  5. #5
    mkj
    mkj is offline Member
    Join Date
    Jan 2012
    Posts
    15
    Rep Power
    0

    Default Re: Timer and for loop

    Dear Fubarable, thanks for you patient.
    here is the code, that i have modified according to your recommandation.
    the J button ActionListener.

    Java Code:
    ActionListener buttonAction = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    
    Timer timer = new Timer(1000,animation);
    timer.start();
    }
    };
    for your second recommandation i am not seeing how can the timer replace the for loop. As i have said i want to move the car from x-initial to x-final using a for loop.
    i am thinking of something like:
    Java Code:
    final ActionListener animation = new ActionListener(){    // i have declared animation as a final to be able to access it from the inner class actionbutton
    public void actionPerformed(ActionEvent e){
    for (int j =0; j <100; j++){
    car.setBounds(2+j,260,50,50);
    // here i want to add something that pause or delay the for loop for a certain time before continuing to move the car, but i am not getting what could i use
    };
    }
    button1.addActionListener(buttonAction);
    thanks in advance.

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

    Default Re: Timer and for loop

    Make the int variable that is used to calculate the x-position of the car a class field. In your Swing Timer's ActionListener, increment the value of that variable, and then call repaint().

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

    Default Re: Timer and for loop

    For example:

    Java Code:
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.Stroke;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class SimpleClockAnimation extends JPanel {
       private static final int PREF_W = 300;
       private static final int PREF_H = PREF_W;
       private static final Color CLOCK_FACE_COLOR = new Color(180, 180, 255);
       private static final Color CLOCK_RIM_COLOR = Color.blue;
       private static final Color HOUR_COLOR = Color.red.darker();
       private static final Color MINUTE_COLOR = new Color(255, 0, 255);
       private static final Color SEC_COLOR = Color.black;
       private static final float CLOCK_RIM_WIDTH = 8f;
       private static final double SCALE = PREF_W / 2.0;
       private static final float HOUR_WIDTH = 5f;
       private static final double HOURS_PER_CYCLE = 12;
       private static final int MIN_PER_HOUR = 60;
       private static final double HOUR_R1 = 0.05;
       private static final double HOUR_R2 = 0.5;
       private static final float MINUTE_WIDTH = 3f;
       private static final int SEC_PER_MIN = 60;
       private static final double MIN_R1 = 0.05;
       private static final double MIN_R2 = 0.75;
       private static final float SEC_WIDTH = 2f;
       private static final double SEC_R1 = 0.05;
       private static final double SEC_R2 = 0.83;
       private static final int TIMER_DELAY = 300;
       private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat(
             "hh:mm:ss");
       private BufferedImage clockFaceBufImg;
       private double hourAngle = 0.0;
       private double minuteAngle = 0.0;
       private double secondAngle = 0.0;
    
       public SimpleClockAnimation() {
          clockFaceBufImg = createClockFaceBI();
          new Timer(TIMER_DELAY, new TimerListener()).start();
       }
    
       private class TimerListener implements ActionListener {
          public void actionPerformed(ActionEvent arg0) {
             Date date = new Date();
             String dateString = DATE_FORMAT.format(date);
             String[] tokens = dateString.split(":");
             int hour = Integer.parseInt(tokens[0]);
             int minute = Integer.parseInt(tokens[1]);
             int second = Integer.parseInt(tokens[2]);
             
             hourAngle = hour *2 * Math.PI / HOURS_PER_CYCLE;
             hourAngle += minute * 2 * Math.PI / HOURS_PER_CYCLE / MIN_PER_HOUR;
             
             minuteAngle = minute * 2 * Math.PI / MIN_PER_HOUR;
             minuteAngle += second * 2 * Math.PI / MIN_PER_HOUR / SEC_PER_MIN;
             
             secondAngle = second * 2 * Math.PI / SEC_PER_MIN;
             repaint();
          }
       }
    
       @Override
       protected void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.drawImage(clockFaceBufImg, 0, 0, this);
          Graphics2D g2 = (Graphics2D) g;
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
          drawHourHand(g2);
          drawMinuteHand(g2);
          drawSecondHand(g2);
       }
       
       private BufferedImage createClockFaceBI() {
          BufferedImage bi = new BufferedImage(PREF_W, PREF_H,
                BufferedImage.TYPE_INT_ARGB);
          Graphics2D g2 = bi.createGraphics();
          g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
          g2.setColor(CLOCK_FACE_COLOR);
          g2.fillOval(0, 0, PREF_W, PREF_H);
          g2.setColor(CLOCK_RIM_COLOR);
          Stroke oldStroke = g2.getStroke();
          g2.setStroke(new BasicStroke(CLOCK_RIM_WIDTH));
          g2.drawOval(0, 0, PREF_W, PREF_H);
    
          g2.setColor(Color.black);
          g2.setStroke(new BasicStroke(2f));
          for (int i = 0; i < 12; i++) {
             double angle = 2 * Math.PI * i / 12;
             drawClockLine(g2, angle, 0.88, 0.92);
          }
          g2.setStroke(oldStroke);
          g2.dispose();
          return bi;
       }
    
       private void drawClockLine(Graphics2D g2, double angle, double r1, double r2) {
          angle -= Math.PI / 2.0;
          int x1 = (int) (Math.cos(angle) * r1 * SCALE + SCALE);
          int y1 = (int) (Math.sin(angle) * r1 * SCALE + SCALE);
          int x2 = (int) (Math.cos(angle) * r2 * SCALE + SCALE);
          int y2 = (int) (Math.sin(angle) * r2 * SCALE + SCALE);
          g2.drawLine(x1, y1, x2, y2);
       }
       
       private void drawHand(Graphics2D g2, Color c, float strokeWidth, double angle, double radius1, double radius2) {
          Graphics2D g2b = (Graphics2D) g2.create();
          g2b.setColor(c);
          g2b.setStroke(new BasicStroke(strokeWidth));
          drawClockLine(g2b, angle, radius1, radius2);
          g2b.dispose();
       }
    
       private void drawHourHand(Graphics2D g2) {
          drawHand(g2, HOUR_COLOR, HOUR_WIDTH, hourAngle, HOUR_R1, HOUR_R2);
       }
    
       private void drawMinuteHand(Graphics2D g2) {
          drawHand(g2, MINUTE_COLOR, MINUTE_WIDTH, minuteAngle, MIN_R1, MIN_R2);
       }
    
       private void drawSecondHand(Graphics2D g2) {
          drawHand(g2, SEC_COLOR, SEC_WIDTH, secondAngle, SEC_R1, SEC_R2);
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PREF_W, PREF_H);
       }
    
       private static void createAndShowGui() {
          JFrame frame = new JFrame("Clock Animation");
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.getContentPane().add(new SimpleClockAnimation());
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                createAndShowGui();
             }
          });
       }
    }
    Last edited by Fubarable; 03-06-2012 at 02:38 AM.

  8. #8
    mkj
    mkj is offline Member
    Join Date
    Jan 2012
    Posts
    15
    Rep Power
    0

    Default [SOLVED]: Timer and for loop

    Dear fubarable,
    Thanks for your help i managed to move the car by adding inti i = 1; in the animation actionListener and now my code is:
    [/code]
    final ActionListener animation = new ActionListener(){
    int i = 1; // i only added this
    public void actionPerformed(ActionEvent e){
    {int j= i++;
    car.setBounds(2+j,260,50,50);
    }
    }
    };


    ActionListener buttonAction = new ActionListener(){
    public void actionPerformed(ActionEvent e){

    final Timer timer = new Timer(10,animation);
    timer.start();
    }
    };

    now the car starts to move but i will look for a way to stop it before it exits the panel .



    button1.addActionListener(buttonAction);

Similar Threads

  1. Breaking out a timer loop
    By musico in forum New To Java
    Replies: 6
    Last Post: 06-23-2011, 08:29 PM
  2. Stopping a Timer from Inside the timer
    By krishnan in forum Java Applets
    Replies: 2
    Last Post: 10-04-2010, 11:15 PM
  3. Inside a Timer thread loop,how to refresh a JTable in swing
    By neha_negi in forum Threads and Synchronization
    Replies: 3
    Last Post: 09-04-2009, 01:45 AM
  4. How to use timer to monitor lengthy loop progress
    By JotaPe in forum New To Java
    Replies: 7
    Last Post: 06-26-2009, 06:14 AM
  5. Replies: 0
    Last Post: 04-04-2008, 02:46 PM

Posting Permissions

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