延迟Java中的图形移动

时间:2018-08-31 07:17:00

标签: java

我在Internet上寻找一辆使用Java图形的汽车。我可以画汽车,但找不到如何延迟汽车运动以使其可见。赛车通过for循环运动非常快。我尝试了Thread.sleep(int);,但显示的是白色边框。我已经编写了以下代码:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*;    

public class car extends JFrame{

    public static final int CANVAS_WIDTH=1360;
    public static final int CANVAS_HEIGHT=680;

    private DrawCanvas canvas;

    public car(){
        canvas=new DrawCanvas(); 
        canvas.setPreferredSize(new Dimension(CANVAS_WIDTH,CANVAS_HEIGHT));
        Container cp=getContentPane();
        cp.add(canvas);


        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();                 
        setTitle("MOVING CAR");     
        setVisible(true);       
    }
    private class DrawCanvas extends JPanel{
        @Override
        public void paintComponent(Graphics g){
            for(int i=0;i<=1360;i++){ 
                super.paintComponent(g); 
                setBackground(Color.BLACK); 

                g.drawLine(0, 322, 1360, 322);

                //car body
                g.drawLine(0+i, 300, 13+i, 298);
                g.drawLine(13+i, 298, 30+i, 280);
                g.drawLine(30+i, 280, 80+i, 280);
                g.drawLine(80+i, 280, 97+i, 298);
                g.drawLine(97+i, 298, 120+i, 300);
                g.drawLine(0+i, 300, 0+i, 315);
                g.drawLine(120+i, 300, 120+i, 315);
                g.drawLine(0+i, 315, 27+i, 315);
                g.drawArc(27+i, 305, 18, 18, 0, 180);
                g.drawOval(30+i, 310, 12, 12);
                g.drawLine(45+i, 315, 67+i, 315);
                g.drawArc(67+i, 305, 18, 18, 0, 180);
                g.drawOval(70+i, 310, 12, 12);
                g.drawLine(85+i, 315, 120+i, 315);

                //First window
                g.drawLine(32+i, 285, 50+i, 285);
                g.drawLine(50+i, 285, 50+i, 295);
                g.drawLine(50+i, 295, 23+i, 295);
                g.drawLine(32+i, 285, 23+i, 295);

                //Second window
                g.drawLine(60+i, 285, 78+i, 285);
                g.drawLine(60+i, 285, 60+i, 295);
                g.drawLine(60+i, 295, 85+i, 295);
                g.drawLine(78+i, 285, 85+i, 295);
            }
        }

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

现在,我该如何延迟代码以使其正确显示正在行驶的汽车?

0 个答案:

没有答案