2

I want to create a continuous animation of a moving truck in java applets. In this the truck should reappear from the other side as soon as it disappears. I tried using one truck but then it appears on the other side only after completely disappearing from one side. Hence, I used two.

Following is my code:

public class prc1 extends Applet implements Runnable{
Thread t;
int x=0;
int y=0;
int i;
public void start(){
    t = new Thread(this);
    t.start();
}
public void paint(Graphics g){
    g.setColor(Color.gray);
    g.fillRect(x,10,70,45);
    g.setColor(Color.yellow);
    g.fillRoundRect(50+x,15,35,35,10,10);
    g.setColor(Color.black);
    g.fillArc(5+x,50,10,10,0,360);
    g.fillArc(55+x,50,10,10,0,360);

    g.setColor(Color.gray);
    g.fillRect(y,10,70,45);
    g.setColor(Color.yellow);
    g.fillRoundRect(50+y,15,35,35,10,10);
    g.setColor(Color.black);
    g.fillArc(5+y,50,10,10,0,360);
    g.fillArc(55+y,50,10,10,0,360);
}
public void run(){
    try{
        y=-90;
        x=0;    
        for(; ;){
            Thread.sleep(100);
            repaint();
            run();
            x=x+5;
            if(x==400){
                for(; ;){
                    y=y+5;
                    Thread.sleep(100);
                    repaint();
                    run();
                    x=x-5;
                    if(x==0){
                        y=-90;      
                        break;
                    }
                }
            }

        }
    }catch(InterruptedException e){ }
  }
}

Now the problem is that the truck does not move at all.

user3382203
  • 169
  • 1
  • 6
  • 25
  • 3
    Applets are dead, long live HTML. [Java Plugin support deprecated](http://www.gizmodo.com.au/2016/01/rest-in-hell-java-plug-in/) and [Moving to a Plugin-Free Web](https://blogs.oracle.com/java-platform-group/entry/moving_to_a_plugin_free) and [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/) – MadProgrammer Apr 13 '16 at 08:14
  • Have you tried to use `paint()``instead of `repaint()`? Have you tried to print to the console the variables `x` and `y` if they really change? – Nikolas Charalambidis Apr 13 '16 at 08:14
  • Take care of swing threading practices when working from the non-swing-thread – Ferrybig Apr 13 '16 at 08:17
  • Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT using components in favor of Swing. – Andrew Thompson Apr 14 '16 at 02:02
  • Well this is a college assignment and the teacher has instructed us to do using AWT only. – user3382203 Apr 14 '16 at 07:15

1 Answers1

1

So the basic idea is, you need to determine when the truck begins to leave the viewable area and then calculate the amount of "overflow", which would then allow you to paint the truck a second time at a new position subtracted from the overflow.

I've broken you code down so the Truck is it's own class, this makes it easier to deal with and allows a little more control over the painting process.

Truck

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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 Truck truck;

        public TestPane() {
            truck = new Truck();
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    truck.update(getSize());
                    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();
            truck.paint(g2d);
            g2d.dispose();
        }

    }

    public class Truck {

        private int x, y;
        // I had to calculate these
        private int width = 85;
        private int height = 65;

        private int xDelta = 4;

        private int xOverFlow = 0;

        public void update(Dimension bounds) {
            x += xDelta;
            if (x > bounds.width) {
                x = 0;
            }

            if (x + width > bounds.width) {
                xOverFlow = (x + width) - bounds.width;
            } else {
                xOverFlow = -1;
            }
        }

        public void paint(Graphics2D g) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.translate(x, y);
            paintTruck(g2d);
            g2d.dispose();

            if (xOverFlow > 0) {
                g2d = (Graphics2D) g.create();
                g2d.translate(xOverFlow - width, y);
                paintTruck(g2d);
                g2d.dispose();
            }
        }

        protected void paintTruck(Graphics2D g2d) {
            g2d.setColor(Color.gray);
            g2d.fillRect(0, 10, 70, 45);
            g2d.setColor(Color.yellow);
            g2d.fillRoundRect(50, 15, 35, 35, 10, 10);
            g2d.setColor(Color.black);
            g2d.fillArc(5, 50, 10, 10, 0, 360);
            g2d.fillArc(55, 50, 10, 10, 0, 360);

            g2d.setColor(Color.gray);
            g2d.fillRect(0, 10, 70, 45);
            g2d.setColor(Color.yellow);
            g2d.fillRoundRect(50, 15, 35, 35, 10, 10);
            g2d.setColor(Color.black);
            g2d.fillArc(5, 50, 10, 10, 0, 360);
            g2d.fillArc(55, 50, 10, 10, 0, 360);
        }
    }

}

Another option might be to have more than one instance of truck, so as the second one begins to leave the viewable you could create another one

For example...

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
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 List<Truck> trucks;

        public TestPane() {
            trucks = new ArrayList<>(2);
            trucks.add(new Truck());
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Truck[] truckArray = trucks.toArray(new Truck[trucks.size()]);
                    for (Truck truck : truckArray) {
                        truck.update(getSize());
                        if (truck.getX() > getWidth()) {
                            trucks.remove(truck);
                        } else if (truck.getX() + truck.getWidth() > getWidth() && trucks.size() == 1) {
                            trucks.add(new Truck());
                        }
                    }
                    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 (Truck truck : trucks) {
                truck.paint(g2d);
            }
            g2d.dispose();
        }

    }

    public class Truck {

        // I had to calculate these
        private int width = 85;
        private int height = 65;

        private int x = -width;
        private int y;

        private int xDelta = 4;

        public void update(Dimension bounds) {
            x += xDelta;
        }

        public int getX() {
            return x;
        }

        public int getY() {
            return y;
        }

        public int getWidth() {
            return width;
        }

        public int getHeight() {
            return height;
        }

        public void paint(Graphics2D g) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.translate(x, y);
            paintTruck(g2d);
            g2d.dispose();
        }

        protected void paintTruck(Graphics2D g2d) {
            g2d.setColor(Color.gray);
            g2d.fillRect(0, 10, 70, 45);
            g2d.setColor(Color.yellow);
            g2d.fillRoundRect(50, 15, 35, 35, 10, 10);
            g2d.setColor(Color.black);
            g2d.fillArc(5, 50, 10, 10, 0, 360);
            g2d.fillArc(55, 50, 10, 10, 0, 360);

            g2d.setColor(Color.gray);
            g2d.fillRect(0, 10, 70, 45);
            g2d.setColor(Color.yellow);
            g2d.fillRoundRect(50, 15, 35, 35, 10, 10);
            g2d.setColor(Color.black);
            g2d.fillArc(5, 50, 10, 10, 0, 360);
            g2d.fillArc(55, 50, 10, 10, 0, 360);
        }
    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Well thanks for the reply, but i just want a simpler version(without the jpanel or swing). Could you please suggest any changes to my existing code and find out any bugs in my code. – user3382203 Apr 13 '16 at 19:54
  • Well, the basic solution is to use the Truck based class and make use of it, frankly, you're r code just scares me. You need to be aware that Applets are no longer supported and AWT is over 16 years out of date, so you're unlikely to get any support for that either. – MadProgrammer Apr 13 '16 at 21:10