سؤال

I need to wait at the end of my for loop before starting again, but I've searched and none of the methods work for my program. The program moves the image from one side to the other. The for loop looks like this:

int xSize = ((int) tk.getScreenSize().getWidth());  
int ySize = ((int) tk.getScreenSize().getHeight());

for (int finalX = xSize - 128; finalX == 0; finalX-=50) 
{
    for (int i = 0; i < 11; i += 1) 
    {
        int Min = 64;
        int Max = ySize - 200;
        int finalY = Min + (int)(Math.random() * ((Max - Min) + 1));
        g.drawImage(image3, finalX, finalY, imageWidth, imageHeight, this);

        <b>//wait here</b>
    }
}

Yes, I have imported everything. I have tried the try/catch, exceptions, and more but none of them work. How do I do this so that my program will still work and it will wait?

هل كانت مفيدة؟

المحلول

Because of this line:

g.drawImage(image3, finalX, finalY, imageWidth, imageHeight, this);

This looks to be a Swing or AWT GUI since you're drawing with a Graphics object (an important detail regarding your question which you should provide for us), and if so, this has been well discussed here and elsewhere:

  1. Don't use a for loop.
  2. Don't use Thread.sleep(...)
  3. Instead use a Swing Timer for the delay, and in the timer's ActionListener, set class fields that will be used to animate the drawing.
  4. And do the drawing in the paintComponent(Graphics g) override of a JPanel or other class that extends from JComponent.
  5. And remembering to call the super.paintComponent(Graphics g) within the override above.

The details of your implementation will all depend on the details of your problem, something else you might wish to pass on to us. For a general review on how to use Swing Timers, please check out the Swing Timer Tutorial.


Edit
For example...

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class TimerEg extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = PREF_W;
   private static final String ICON_PATH = "https://duke.kenai.com/iconSized/duke4.gif";
   private static final int TIMER_DELAY = 400;

   private BufferedImage imageSprite = null;
   private Random random = new Random();
   private int finalX;
   private int finalY;

   public TimerEg() throws IOException {
      URL imgUrl = new URL(ICON_PATH);
      imageSprite = ImageIO.read(imgUrl);

      int maxX = PREF_W - imageSprite.getWidth();
      int maxY = PREF_H - imageSprite.getHeight();
      new Timer(TIMER_DELAY, new TimerListener(this, maxX, maxY)).start();
   }

   public void setSpriteLocation(int x, int y) {
      finalX = x;
      finalY = y;
      repaint();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      if (imageSprite != null) {
         g.drawImage(imageSprite, finalX, finalY, this);
      }
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   private class TimerListener implements ActionListener {
      private TimerEg timerEg;
      private int maxX;
      private int maxY;

      private TimerListener(TimerEg timerEg, int maxX, int maxY) {
         this.timerEg = timerEg;
         this.maxX = maxX;
         this.maxY = maxY;
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         int currentX = random.nextInt(maxX);
         int currentY = random.nextInt(maxY);
         timerEg.setSpriteLocation(currentX, currentY);
      }
   }

   private static void createAndShowGui() {
      TimerEg mainPanel = null;
      try {
         mainPanel = new TimerEg();
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      JFrame frame = new JFrame("TimerEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Which shows a sprite moving randomly over a GUI and looks like:

enter image description here

نصائح أخرى

This has been answered before: Java Delay/Wait

Thread.sleep(1000); // do nothing for 1000 miliseconds (1 second)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top