Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Game extends JComponent implements ActionListener {
    Timer t = new Timer(5, this);
    int wx;
    int rx = 10;
    int rx2 = 10;
    int carx = 10;
    int velX = 2;

    public static void main(String[] args) {
        JFrame window = new JFrame("Frogger");
        window.add(new Game());
        window.pack();
        window.setSize(800, 600);
        window.setLocationRelativeTo(null);
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setVisible(true);



    }
    public void actionPerformed(ActionEvent e){
        carx+=velX;
        repaint();
    }

    boolean firstFrame = true;
    @Override
    protected void paintComponent(Graphics g) {

        super.paintComponent(g);
        if (firstFrame) {
            t.start();
            firstFrame = false;
        }
        g.setColor(new Color(173, 216, 230));
        g.fillRect(0, 0, 800, 600); //background
        g.setColor(Color.lightGray);
        g.fillRect(0, 525, 800, 75); //start
        g.fillRect(0, 0, 800, 30); //end
        g.setColor(Color.black);
        g.fillRect(0, 300, 800, 225); //street
        g.setColor(Color.white);

        for (int n = 0; n < 16; n++) {
            g.fillRect(rx, 450, 20, 10);
            rx += 50;
        }
        for (int n = 0; n < 16; n++) {
            g.fillRect(rx2, 375, 20, 10);
            rx2 += 50;
        }
        rx = rx2 = 10;
        while(true){
            g.fillRect(carx, 477, 60, 30);
        }

    }




}


I am trying to make an object move across the screen and when it gets to a certain point the program will copy itself and move across the screen with the other object still going. I am trying to figure out how to do this infinitely. I tried to use a while loop but that obviously didn't work. Any help is appreciated.
Posted

1 solution

It is just a question of creating a loop with a timed delay, or using a timer to call the redraw mwthod. Start by drawing the object at the left side of the screen. Then after each interval you redraw it at some point slightly to the right. Continue until the object hits the right hand side then start again, or start moving it to the left. That makes it look like it bounces off the edges.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900