Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Applet: Moving Image Object

  1. Feb 10, 2017 #1
    Hello, I'm having trouble with moving an object using an image. I want my image "Car" to move left and right when I press one of the JButtons. As you can see, I included a blue rectangle to kind of show you what I mean by "moving". Here is the code for the Blue Rectangle.

    Code (Java):
    private int carY = 150;
    Code (Java):
    if (event.getSource()  == stop)
                carY -= 15;
            else if (event.getSource() == caution)
                carY = 15;
            else
                carY += 15;
    Code (Java):
     g.setColor(Color.BLUE);
            g.fillRect(170,carY, 60,90);
    If you click on "Go", the rectangle will move up at 15
    Code (Java):
    carY += 15;
    . I'm confused on how would you get the image "Car" to move instead of the rectangle.

    Here is the Car image code:
    Code (Java):
     private Image Car = null;
    Code (Java):
    //gets Car image
            if (Car ==null)
                Car = getImage("Car.png");
            Graphics2D g2 = (Graphics2D)g;
            g2.drawImage(Car, 150, 350, 100, 50, this);
    So, I want to insert carY into
    Code (Java):
     g2.drawImage(Car, 150, 350, 100, 50, this);
    but you can't because I get an error: "Incompatible types: int cannot be converted to java.awt.Color". So, I don't know how to connect my image with the actionListener to where if I press a JButton, it will move the car image.

    Here is the full code, but to use the image you would have to open the zip file.

    Code (Java):
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.applet.Applet;
    import javax.swing.*;
    import java.awt.TextField.*;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.net.URL;

    public class TrafficLight extends Applet implements ActionListener
    {
       
        int colorNum; // variable to change traffic light.
     
        //JButton stop;
        Button stop = new Button ("Stop");
        // JButton Caution
        Button caution = new Button ("Caution");
        // JButton Go;
        Button go = new Button ("Go");
       
        // TextField Initialization
        TextField tf;
       
        private Image Car = null;
        private int carY = 150;
           public void init ()
        {
            setBackground (Color.lightGray);
            stop.addActionListener (this); // stop light
            caution.addActionListener (this); // yellow light
            go.addActionListener (this); // green light

            add (stop);
            add (caution);
            add (go);
           
            // stop = Red Light // local declaration
            stop.setForeground(Color.black);
            stop.setBackground(Color.red);
            stop.addActionListener(this);
           
            // caution = Caution Light
            caution.setForeground(Color.black);
            caution.setBackground(Color.yellow);
            caution.addActionListener(this);// the current object is given the special name "this"

           
            // Go = Green Light
            go.setForeground(Color.black);
            go.setBackground(Color.green);
            go.addActionListener(this);// the current object is given the special name "this"
           
            tf = new TextField("Traffic Light");
            add(tf);
         
        }
         public void actionPerformed (ActionEvent event)
        {
            if (event.getSource () == stop)
                colorNum = 1;
            else if (event.getSource () == caution)
                colorNum = 2;
            else
                colorNum = 3;
               
            if (event.getSource()  == stop)
                carY -= 0;
            else if (event.getSource() == caution)
                carY -= 5;
            else
                carY += 15;
               
            repaint ();
        }
        public void paint (Graphics g)  // responsible for graphics "within" the window
        {
            g.setColor (Color.black);

            switch (colorNum)
            {
                case 1:
                    g.setColor (Color.red);
                    break;
            }
           
            g.setColor(colorNum == 1? Color.red : Color.red.darker().darker());
            g.fillOval (30, 40, 20, 20); // red light
            g.setColor(colorNum == 2? Color.yellow : Color.yellow.darker().darker());
            g.fillOval (30, 70, 20, 20); // yellow light
            g.setColor(colorNum == 3? Color.green : Color.green.darker().darker());
            g.fillOval (30, 100, 20, 20); // green light
           
            // Inserting background Image
            Image img = getImage( getCodeBase(), "Road.png" );
            g.drawImage( img, 320, 45, 2200, 1900, 0, 10, 1200, 1200, this );
           
            //gets Car image
            if (Car ==null)
                Car = getImage("Car.png");
            Graphics2D g2 = (Graphics2D)g;
            g2.drawImage(Car, 150, 350, 100, 50, this);
           
            // Draws Rectangle Image
            g.setColor(Color.BLUE);
            g.fillRect(170,carY, 60,90);
        }
       
        // Car Image
        public Image getImage(String path)
        {
            Image tempImage = null;
            try
            {
                URL imageURL = TrafficLight.class.getResource(path);
                tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
            }
            catch (Exception e)
            {
                System.out.println("An error occured - " + e.getMessage());
            }
            return tempImage;
        }
    }
     
     

    Attached Files:

  2. jcsd
  3. Feb 10, 2017 #2

    Borg

    User Avatar
    Science Advisor
    Gold Member

    Can you post part of the stack trace error that you're getting? It helps to see where in the program it's failing.
     
  4. Feb 10, 2017 #3
    You mean like this? (In the picture/attachment below).

    Maybe to help clarify more. This part in the code for the rectangle:

    Code (Java):
    g.fillRect(170,carY, 60,90);
    This works fine, but instead, I want the carY in the image:

    Code (Java):
    g2.drawImage(Car, carY, 150, 350, 100, 50, this);
    This doesn't work, as it gives an error, "Incompatible types: int cannot be converted to java.awt.Color."
    carY is used so that when I click a JButton, and depending on which JButton I click, the object (in this case, I want the image) to move using this:
    Code (Java):
    if (event.getSource()  == stop)
                carY -= 0;
            else if (event.getSource() == caution)
                carY -= 5;
            else
                carY += 15;
    So I want carY to be used for the image, not the rectangle. The rectangle was just an example. I hope that simplified my question a little more.
     

    Attached Files:

    Last edited: Feb 10, 2017
  5. Feb 11, 2017 #4

    Borg

    User Avatar
    Science Advisor
    Gold Member

    Sorry for the delay. I downloaded the zip and modified it to work in my environment this morning. When you mentioned an error in your first post, I thought that you were having trouble compiling but the code does compile and run.
    As for getting the car to move, you are applying the position change to the road's graphic position and not the car's. Change these two lines to get the car to move (original code left as commented):
    Code (Java):

            g2.drawImage(Car, carY, 350, 100, 50, this);
    //      g2.drawImage(Car, 150, 350, 100, 50, this);

            // Draws Rectangle Image
            g.setColor(Color.BLUE);
            g.fillRect(170, 150, 60, 90);
    //      g.fillRect(170, carY, 60, 90);
     
  6. Feb 11, 2017 #5
    That's definetly alright, no rush. As for the code, it was exactly what I was looking for, thank you!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Java Applet: Moving Image Object
  1. Java and missing images (Replies: 14)

  2. Display image in java (Replies: 18)

  3. Java Applet Issues (Replies: 12)

Loading...