4

I am trying to move a train across my java window and am having serious problems. I have a Train class in which I made the train, and a Driver class which is supposed to move the train. I need to make the whole train move from right to left until it 'passes' the left edge of the screen. Then add an if statement to change the dx so the train restarts on the right side . The below is what I have tried but it is not working. Can anyone help me please??

public class Driver extends GraphicsProgram
{
    //~ Instance/static variables .............................................

    private static final int N_STEPS = 1000;
    private static final int PAUSE_TIME = 20;
    private static final double TRAIN_LENGTH = 320;

    //~ Constructor ...........................................................

    // ----------------------------------------------------------
    /**
     * The run() method of the Driver Class.
     * Creates an instance of the Train Class.
     * Responsible for animating the train across the screen.
     */
    public void run()
    {
        Train train = new Train(getGCanvas());
        for (int i = 0; i < N_STEPS; i++) {
            train.move(-100, 0);
            pause(PAUSE_TIME);
    }
Holger
  • 285,553
  • 42
  • 434
  • 765
Emmaline Smith
  • 51
  • 1
  • 1
  • 3
  • Was [**this**](http://stackoverflow.com/questions/19628537/cannot-move-an-image) also your question, or someone else with the same assignment? – Boann Oct 28 '13 at 07:35
  • It is someone else with the same assignment, this is the only time I have posted about this problem. Do you have any suggestions? I have been working for hours but cannot seem to be able to figure out how to move an object across the screen :( – Emmaline Smith Oct 28 '13 at 07:40
  • I can only imagine (as was also suggested in the other thread) that there's some method you need to call to tell it to redraw the screen. `GraphicsProgram` is not a standard Java class so I don't know what that method is. – Boann Oct 28 '13 at 07:42
  • When you say "it's not working", you need to be more specific as it's not clear what the problem is. Is the train not rendering at all? Is it entirely stationary? Does it stop halfway to the edge? Does it overshoot or wrap around? Do you get an exception message? – Andrzej Doyle Oct 28 '13 at 08:39
  • why are you using fixed values in train.move(-100, 0) i; inside a for loop? – Thusitha Thilina Dayaratne Oct 28 '13 at 08:39
  • Did you ever find out what the solution was? I'm curious. – Boann Nov 08 '13 at 09:17

2 Answers2

3

Here is a little demo made with swing. Just replace the black rectangle with an image of your train and you're done.

The trick is to use a separate thread (or timer) to do the animation loop (often called game loop). The loop only tells your window to redraw itself, and on each redraw, you first compute the new positions of the animated objects, then you draw them.

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

public class TrainDemo {

    public static void main(String[] args) {
        JFrame frame = new JFrame("Train Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 400);
        frame.setLocationRelativeTo(null);
        frame.add(new TrainCanvas());
        frame.setVisible(true);
    }

}

class TrainCanvas extends JComponent {

    private int lastX = 0;

    public TrainCanvas() {
        Thread animationThread = new Thread(new Runnable() {
            public void run() {
                while (true) {
                    repaint();
                    try {Thread.sleep(10);} catch (Exception ex) {}
                }
            }
        });

        animationThread.start();
    }

    public void paintComponent(Graphics g) {
        Graphics2D gg = (Graphics2D) g;

        int w = getWidth();
        int h = getHeight();

        int trainW = 100;
        int trainH = 10;
        int trainSpeed = 3;

        int x = lastX + trainSpeed;

        if (x > w + trainW) {
            x = -trainW;
        }

        gg.setColor(Color.BLACK);
        gg.fillRect(x, h/2 + trainH, trainW, trainH);

        lastX = x;
    }

}
Aurelien Ribon
  • 7,548
  • 3
  • 43
  • 54
  • They don't seem to be using Swing. I don't think they can "just replace the black rectangle with the train", and their run() method already seems to be designed for animation so I don't think it needs another thread. – Boann Oct 28 '13 at 16:14
  • @Boann You cannot make that many assumptions based on the OP code. What I see is that the run() method is used to instantiate the train and perform the animation. It doesn't seem to be called in a loop by an external engine. This way, it's the quivalent of my TrainCanvas() constructor. I tried to make the code so simple that the OP could translate Swing ideas into its engine mechanisms, while also providing a working demo for him to be able to play with it, I don't think that really deserves a -1 :-) – Aurelien Ribon Oct 29 '13 at 09:44
-1
color c = color(0); float x = 0; float y = 100; float speed = 1;
void setup() { size(200,200); }
void draw() { background(255); move(); display(); }
void move() { x = x + speed; if (x > width) { x = 0; } }
void display() { fill(c); rect(x,y,30,10); }
Rich
  • 6,470
  • 15
  • 32
  • 53
Mars
  • 1