Question

Hi! I'm working on building a GUI that makes cars race across the screen. So far...

Hi! I'm working on building a GUI that makes cars race across the screen. So far my code produces three cars, and they each show up without error, but do not move across the screen. Can someone point me in the right direction? Thank you!

CarComponent.java

package p5;

import java.awt.*;

import java.util.*;

import javax.swing.*;

@SuppressWarnings("serial")

public class CarComponent extends JComponent {

private ArrayList<Car> cars;

public CarComponent()

{

cars = new ArrayList<Car>();

}

public void add(Car car)

{

cars.add(car);

}

public void moveCars(int x, int y)

{

/*Controls the cars movement and the car direction.  

* Move the cars 1 pixal at time to start.

* Later move them a random distance, so they race.

*/

int len = cars.size();

for(int i = 0; i < len; i++)

{

cars.get(i).translate(50, 0);

repaint();

}

}

public void paintComponent (Graphics g)

{

Graphics2D g2 = (Graphics2D) g;

Car car1 = new Car(0,5);

//int x = ;

//int y = ;

Car car2 = new Car(0,40);

Car car3 = new Car(0,80);

//int x = ;

//int y = ;

car1.draw(g2);

car2.draw(g2);

car3.draw(g2);

}

}

Car.java

package p5;

import java.awt.*;

import java.awt.geom.Ellipse2D;

import java.awt.geom.Line2D;

import java.awt.geom.Point2D;

@SuppressWarnings("serial")

public class Car {

private int xLeft;

private int yTop;

private boolean forward;

public Car(int x, int y)

{

xLeft = x;

yTop = y;

forward = true;

}

public void translate(int dx, int dy)

{

if (xLeft == 240)

{

forward = false;

}

if(forward)

{

xLeft += dx;

yTop += dy;

}

}

public void draw(Graphics2D g2)

{

Rectangle body = new Rectangle(xLeft, yTop +10, 60, 10);

Ellipse2D.Double frontTire = new Ellipse2D.Double(xLeft + 10, yTop + 20, 10, 10);

Ellipse2D.Double rearTire = new Ellipse2D.Double(xLeft + 40, yTop +20, 10, 10);

//Bottom of front windshield.

Point2D.Double r1 = new Point2D.Double(xLeft + 10, yTop + 10);

//Front of the roof.

Point2D.Double r2 = new Point2D.Double(xLeft + 20, yTop);

//Rear of the roof.

Point2D.Double r3 = new Point2D.Double(xLeft + 40, yTop);

//Bottom of the rear windshield.

Point2D.Double r4 = new Point2D.Double(xLeft + 50, yTop + 10);

Line2D.Double frontWindshield = new Line2D.Double(r1, r2);

Line2D.Double roofTop = new Line2D.Double(r2, r3);

Line2D.Double rearWindshield = new Line2D.Double(r3, r4);

g2.draw(body);

g2.draw(frontTire);

g2.draw(rearTire);

g2.draw(frontWindshield);

g2.draw(roofTop);

g2.draw(rearWindshield);

}

public int getXLeft(int xLeft)

{

return xLeft;

}

public int getYTop(int yTop)

{

return yTop;

}

public boolean getForward(boolean forward)

{

return forward;

}

public void setForward(boolean forward)

{

forward = true;

}

}

CarMover.java

package p5;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.util.Scanner;

import java.util.*;

import javax.swing.Timer;

import javax.swing.JFrame;

import java.awt.event.ActionEvent;

@SuppressWarnings("serial")

public class CarMover {

private static final int FRAME_WIDTH = 300;

private static final int FRAME_HEIGHT = 400;

public static void main(String[] args)

{

JFrame frame = new JFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

CarComponent component = new CarComponent();

component.add(new Car(0, 10));

component.add(new Car(0, 50));

component.add(new Car(0, 100));

frame.add(component);

frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);

frame.setVisible(true);

System.out.println("Set the x value for the movement of the car: ");

Scanner keyboard = new Scanner(System.in);

int movement = keyboard.nextInt();

class TimerListener implements ActionListener

{

public void actionPerformed(ActionEvent event)

{

component.moveCars(50, 0);

}

}

ActionListener listener = new TimerListener();

final int DELAY = 50; // Milliseconds between timer ticks

Timer t = new Timer(DELAY, listener);

t.start();

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1
  • I really understand your concern and debug your rewrite your code in fresh manner so that it produce desirable output.
  • It contain the output of three moving car.

Source code:-

CarsMover

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;


public class CarsMover {

    private static final int FRAME_WIDTH = 300;
    private static final int FRAME_HEIGHT = 400;
    private static final int CAR_HEIGHT = 40;
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame frame = new JFrame();

        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.setLayout(new GridLayout(3,1));
        frame.setTitle("CarMover");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final CarComponent component = new CarComponent();
        component.setPreferredSize(new Dimension(FRAME_WIDTH, CAR_HEIGHT));
      
        final CarComponent blueCar = new CarComponent(FRAME_WIDTH-80, 0, Color.BLUE);
        component.setPreferredSize(new Dimension(FRAME_WIDTH, CAR_HEIGHT));
      
      
        final CarComponent redCar = new CarComponent(0,0, Color.RED);
        component.setPreferredSize(new Dimension(FRAME_WIDTH, CAR_HEIGHT));
      
        frame.add(component);
        frame.add(blueCar);
        frame.add(redCar);
        frame.setVisible(true);

        class TimerListener implements ActionListener {

            public void actionPerformed(ActionEvent event) {
                component.moveCarBy(5, 0);
                component.repaint();
                blueCar.moveCarBy(-5,0);
                blueCar.repaint();
                redCar.moveCarBy(5,0);
                redCar.repaint();
            }
        }
        ActionListener listener = new TimerListener();

        final int DELAY = 100; // Milliseconds between timer ticks
        Timer t = new Timer(DELAY, listener);
        t.start();
    }

}

---------------------------------------------------------------------------------------------------------------

CarComponent

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;


/**
* This component displays a car that can be moved.
*/
public class CarComponent extends JComponent {

    private Car car;
    private Color bodyColor;
  
    public CarComponent() {
        // The rectangle that the paint method draws
        car = new Car(0, 0);
    }
  
    public CarComponent(int x, int y, Color _bodyColor)
    {
        bodyColor = _bodyColor;
        car = new Car(x, y);
    }
  
    public void paintComponent(Graphics g) {
        g.setColor(bodyColor);
        car.draw(g);
    }

    /**
     * Moves the rectangle by a given amount.
     *
     * @param x the amount to move in the x-direction
     * @param y the amount to move in the y-direction
     */
    public void moveCarBy(int dx, int dy) {
        car.translate(dx, dy);
        repaint();
    }

}

------------------------------------------------------------------------------------------

Car

import java.awt.Graphics;
import javax.swing.JComponent;


/**
* A car shape that can be positioned anywhere on the screen.
*/
public class Car {

    private int xLeft;
    private int yTop;

    /**
     * Constructs a car with a given top left corner
     *
     * @param x the x coordinate of the top left corner
     * @param y the y coordinate of the top left corner
     */
    public Car(int x, int y) {
        xLeft = x;
        yTop = y;
    }

    /**
     * Moves this car by a given distance.
     *
     * @param dx the distance in x-direction
     * @param dy the distance in y-direction
     */
    public void translate(int dx, int dy) {
        xLeft = xLeft + dx;
        yTop = yTop + dy;
    }

    /**
     * Draws the car.
     *
     * @param g the graphics context
     */
    public void draw(Graphics g) {
        g.drawRect(xLeft, yTop + 10, 60, 10);
        g.drawOval(xLeft + 10, yTop + 20, 10, 10);
        g.drawOval(xLeft + 40, yTop + 20, 10, 10);

        g.drawLine(xLeft + 10, yTop + 10, xLeft + 20, yTop);
        g.drawLine(xLeft + 20, yTop, xLeft + 40, yTop);
        g.drawLine(xLeft + 40, yTop, xLeft + 50, yTop + 10);
    }
}

---------------------------------------------------------------------------------------------

Output:-

******************************************************************************************

if you are satisfy with my answer then please,please like it.

Add a comment
Know the answer?
Add Answer to:
Hi! I'm working on building a GUI that makes cars race across the screen. So far...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Modify the NervousShapes program so that it displays equilateral triangles as well as circles and rectangles....

    Modify the NervousShapes program so that it displays equilateral triangles as well as circles and rectangles. You will need to define a Triangle class containing a single instance variable, representing the length of one of the triangle’s sides. Have the program create circles, rectangles, and triangles with equal probability. Circle and Rectangle is done, please comment on your methods so i can understand */ package NervousShapes; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; public class...

  • Need help writing Java code for this question. CircleFrame class is provided below. what happen after...

    Need help writing Java code for this question. CircleFrame class is provided below. what happen after u add the code and follow the requirement? It would be nice to be able to directly tell the model to go into wait mode in the same way that the model's notify method is called. (i.e. notify is called directly on the model, whereas wait is called indirectly through the suspended attribute.) Try altering the the actionPerformed method of the SliderListener innner class...

  • Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent()...

    Keep the ball in bounds by adding conditional statements after the TODO comments in the paintComponent() method to check when the ball has hit the edge of the window. When the ball reaches an edge, you will need to reverse the corresponding delta direction and position the ball back in bounds. Make sure that your solution still works when you resize the window. Your bounds checking should not depend on a specific window size This is the java code that...

  • ***This is a JAVA question*** ------------------------------------------------------------------------------------------------ import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*;...

    ***This is a JAVA question*** ------------------------------------------------------------------------------------------------ import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.imageio.*; import javax.swing.*; import javax.swing.event.*; public class DrawingPanel implements ActionListener { public static final int DELAY = 50; // delay between repaints in millis private static final String DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save"; private static String TARGET_IMAGE_FILE_NAME = null; private static final boolean PRETTY = true; // true to anti-alias private static boolean DUMP_IMAGE = true; // true to write DrawingPanel to file private int width, height; // dimensions...

  • import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow...

    import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow for simple graphical drawing on a canvas. * This is a modification of the general purpose Canvas, specially made for * the BlueJ "shapes" example. * * @author: Bruce Quig * @author: Michael Kolling (mik) * Minor changes to canvas dimensions by William Smith 6/4/2012 * * @version: 1.6 (shapes) */ public class Canvas { // Note: The implementation of this class (specifically the...

  • import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow...

    import javax.swing.*; import java.awt.*; import java.util.List; import java.util.*; /** * Canvas is a class to allow for simple graphical drawing on a canvas. * This is a modification of the general purpose Canvas, specially made for * the BlueJ "shapes" example. * * @author: Bruce Quig * @author: Michael Kolling (mik) * Minor changes to canvas dimensions by William Smith 6/4/2012 * * @version: 1.6 (shapes) */ public class Canvas { // Note: The implementation of this class (specifically the...

  • Please I need your help I have the code below but I need to add one...

    Please I need your help I have the code below but I need to add one thing, after player choose "No" to not play the game again, Add a HELP button or page that displays your name, the rules of the game and the month/day/year when you finished the implementation. import java.awt.*; import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; import javax.swing.event.*; import java.util.Random; public class TicTacToe extends JFrame implements ChangeListener, ActionListener { private JSlider slider; private JButton oButton, xButton; private Board...

  • Add another changeColor() method (i.e. you will now have 2 methods called "changeColor"). This one accepts...

    Add another changeColor() method (i.e. you will now have 2 methods called "changeColor"). This one accepts an int parameter and changes the color based on that int. The valid colors are "red", "yellow", "green", "blue", "magenta" and "black". In your code, map each color to an integer (e.g. in my code 3 means green.) If the number passed to the method is not valid, change the color to red. In the bounceTheBall() method, where you test for collisions with top...

  • **JAVA** Hi! Can't figure this out, but if you could give it a shot, I'd appreciate...

    **JAVA** Hi! Can't figure this out, but if you could give it a shot, I'd appreciate it! Everything is explained in the program via comments, and I just need help implementing the methods. Instructions for the methods are commented on top of said method. It's supposedly straightforward. Methods that need to be solved are in bold. Some might already be implemented. Just based off what's in this class, is supposed to lead to the outcome. This is all the info...

  • could you please help me with this problem, also I need a little text so I...

    could you please help me with this problem, also I need a little text so I can understand how you solved the problem? import java.io.File; import java.util.Scanner; /** * This program lists the files in a directory specified by * the user. The user is asked to type in a directory name. * If the name entered by the user is not a directory, a * message is printed and the program ends. */ public class DirectoryList { public static...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT