Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java for循环的问题_Java_Animation_For Loop - Fatal编程技术网

Java for循环的问题

Java for循环的问题,java,animation,for-loop,Java,Animation,For Loop,我有一个for循环,它在actionPerformed方法中迭代。基本上,我有一个汽车游戏。我有一个面板,汽车图像在JPanel中从一边传到另一边。我试着让赛车停在终点线(当图像达到某个x值时,我会睡觉),显示比赛结果,离开屏幕,再次比赛。我需要做四次,直到我们有一个赢家 private class RaceDisplay extends JPanel implements ActionListener{ private Image img1,img2; private int v

我有一个for循环,它在actionPerformed方法中迭代。基本上,我有一个汽车游戏。我有一个面板,汽车图像在JPanel中从一边传到另一边。我试着让赛车停在终点线(当图像达到某个x值时,我会睡觉),显示比赛结果,离开屏幕,再次比赛。我需要做四次,直到我们有一个赢家

private class RaceDisplay extends JPanel implements ActionListener{

   private Image img1,img2;
   private int velX1,velX2;
   private int x1,x2;
   private Timer tm;
   private JTextArea text1 = new JTextArea();


public RaceDisplay(){

        tm = new Timer(30,this);
        x1=0;
        x2=0;
        velX1=2;
        velX2 =2;
    }

    public void paintComponent(Graphics g){

        super.paintComponent(g);
        ImageIcon car1 = new ImageIcon("...");
        ImageIcon car2 = new ImageIcon("...");

        img1 = car1.getImage(); 
        img2 = car2.getImage();       

        g.drawImage(img1,x1,100,null);
        g.drawImage(img2,x2,200,null);

        tm.start();

    }
    public void actionPerformed(ActionEvent e) {

       x1=x1+velX1;
       velX2= x2+velX2;
       repaint();

     for(int count = 0;count<=4;count++){//<-----loop with issues.
         if(count == 1){
           text1.setText(result());
          }
       if(x1>=650 && x2>=650){ //does this when both cars reach the line
          velX1=0;
          velX2=0;
          try {
             Thread.sleep(2500);
         } catch (InterruptedException ex) {
                    Logger.getLogger(Display.class.getName()).log(Level.SEVERE, null, ex);
         }     
          x1=0;
          x2=0;
          repaint();
          velX1= x1+velX1;
          velX2= x2+velX2;
         }

     }
       repaint();


  }
私有类RaceDisplay扩展JPanel实现ActionListener{
私有图像img1、img2;
私有int velX1,velX2;
私有int-x1,x2;
私人定时器;
私有JTextArea text1=新JTextArea();
公众赛马场展览(){
tm=新计时器(30,此);
x1=0;
x2=0;
velX1=2;
velX2=2;
}
公共组件(图形g){
超级组件(g);
ImageIcon car1=新的ImageIcon(“…”);
ImageIcon car2=新的ImageIcon(“…”);
img1=car1.getImage();
img2=car2.getImage();
g、 drawImage(img1,X1100,空);
g、 drawImage(img2,X2200,空);
tm.start();
}
已执行的公共无效操作(操作事件e){
x1=x1+x1;
velX2=x2+velX2;
重新油漆();
对于(int count=0;count=650){//当两辆车都到达终点线时,会这样做吗
velX1=0;
velX2=0;
试一试{
睡眠(2500);
}捕获(中断异常例外){
Logger.getLogger(Display.class.getName()).log(Level.SEVERE,null,ex);
}     
x1=0;
x2=0;
重新油漆();
velX1=x1+velX1;
velX2=x2+velX2;
}
}
重新油漆();
}
我创建了for循环,当它到达最后一个计数器时,应该检查if语句,它显示winner(代码中winner的方法)。我期望图像从侧面移动四次,并显示四次结果。 但只有当我将if(counter==1)设置为(counter==0)时,它才会显示任何内容。 有人能帮忙吗? 谢谢

  • 不要调用
    tm.start()
    paintComponent
    方法中,这只是自找麻烦。绘画的发生可能有多种原因,其中许多是你无法控制或不了解的
  • 不要在事件调度线程的上下文中调用
    线程。sleep
    。这不是停止计时器,而是阻止EDT处理事件队列,其中包括重绘事件和计时器事件
  • 相反,一旦你检测到一辆车已经过了终点线,你可以停止更新该车的位置和/或停止
    计时器

    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class Test {
    
        public static void main(String[] args) {
            new Test();
        }
    
        public Test() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            private Map<BufferedImage, Rectangle> carBounds;
            private BufferedImage blueCar;
            private BufferedImage redCar;
    
            public TestPane() {
                carBounds = new HashMap<>(25);
                try {
                    blueCar = ImageIO.read(getClass().getResource("/BlueCar.png"));
                    redCar = ImageIO.read(getClass().getResource("/RedCar.png"));
    
                    int x = 0;
                    int y = (200 / 2 ) - blueCar.getHeight();
                    carBounds.put(blueCar, new Rectangle(x, y, blueCar.getWidth(), blueCar.getHeight()));
    
                    y = (200 / 2);
                    carBounds.put(redCar, new Rectangle(x, y, redCar.getWidth(), redCar.getHeight()));
    
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
    
                Timer timer = new Timer(40, new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (BufferedImage img : carBounds.keySet()) {
                            Rectangle bounds = carBounds.get(img);
    
                            int xDelta = (int)Math.round((Math.random() * 7) + 1);
                            bounds.x += xDelta;
                            if (bounds.x + bounds.width > getWidth()) {
                                bounds.x = getWidth() - bounds.width;
                                ((Timer)e.getSource()).stop();
                            }
    
                        }
                        repaint();
                    }
                });
                timer.start();
    
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g.create();
                for (BufferedImage img : carBounds.keySet()) {
                    Rectangle bounds = carBounds.get(img);
                    g2d.drawImage(img, bounds.x, bounds.y, this);
                }
                g2d.dispose();
            }
    
        }
    }
    

    导入java.awt.Dimension;
    导入java.awt.EventQueue;
    导入java.awt.Graphics;
    导入java.awt.Graphics2D;
    导入java.awt.Rectangle;
    导入java.awt.event.ActionEvent;
    导入java.awt.event.ActionListener;
    导入java.awt.image.buffereImage;
    导入java.io.IOException;
    导入java.util.HashMap;
    导入java.util.Map;
    导入javax.imageio.imageio;
    导入javax.swing.JFrame;
    导入javax.swing.JPanel;
    导入javax.swing.Timer;
    导入javax.swing.UIManager;
    导入javax.swing.UnsupportedLookAndFeelException;
    公开课考试{
    公共静态void main(字符串[]args){
    新测试();
    }
    公开考试(){
    invokeLater(新的Runnable(){
    @凌驾
    公开募捐{
    试一试{
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }catch(ClassNotFoundException |实例化Exception | IllegalacessException |不支持ookandfeelException ex){
    例如printStackTrace();
    }
    JFrame=新JFrame(“测试”);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(newtestpane());
    frame.pack();
    frame.setLocationRelativeTo(空);
    frame.setVisible(true);
    }
    });
    }
    公共类TestPane扩展了JPanel{
    私人地图卡邦兹;
    私人BuffereImage blueCar;
    私家车;
    公共测试窗格(){
    carBounds=新的HashMap(25);
    试一试{
    blueCar=ImageIO.read(getClass().getResource(“/blueCar.png”);
    redCar=ImageIO.read(getClass().getResource(“/redCar.png”);
    int x=0;
    int y=(200/2)-blueCar.getHeight();
    carBounds.put(blueCar,新矩形(x,y,blueCar.getWidth(),blueCar.getHeight());
    y=(200/2);
    carBounds.put(redCar,新矩形(x,y,redCar.getWidth(),redCar.getHeight());
    }捕获(IOEX异常){
    例如printStackTrace();
    }
    计时器计时器=新计时器(40,新ActionListener(){
    @凌驾
    已执行的公共无效操作(操作事件e){
    对于(BuffereImage img:carBounds.keySet()){
    矩形边界=carBounds.get(img);
    int xDelta=(int)Math.round((Math.random()*7)+1);
    边界x+=xDelta;
    如果(bounds.x+bounds.width>getWidth()){
    bounds.x=getWidth()-bounds.width;
    ((计时器)e.getSource()).stop();
    }
    }
    重新油漆();
    }
    });
    timer.start();
    }
    @凌驾
    公共维度getPreferredSize(){
    返回新维度(200200);
    }
    @凌驾
    受保护组件(图形g){
    超级组件(g);
    Graphics2D g2d=(Graphics2D)g.create();
    对于(BuffereImage img:carBounds.keySet()){
    矩形b