Java Applet: Moving Image Object

  • Java
  • Thread starter FritoTaco
  • Start date
  • Tags
    Image Java
In summary: Source() == caution) carY =...; else carY +=...; g.setColor(Color.BLUE); g.fillRect(170,carY, 60,90);}}
  • #1
FritoTaco
132
23
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.

Java:
private int carY = 150;
Java:
if (event.getSource()  == stop)
            carY -= 15;
        else if (event.getSource() == caution)
            carY = 15;
        else
            carY += 15;
Java:
 g.setColor(Color.BLUE);
        g.fillRect(170,carY, 60,90);

If you click on "Go", the rectangle will move up at 15
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:
Java:
 private Image Car = null;
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:
 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.

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 occurred - " + e.getMessage());
        }
        return tempImage;
    }
}
 

Attachments

  • TrafficLight.zip
    187.7 KB · Views: 415
Technology news on Phys.org
  • #2
Can you post part of the stack trace error that you're getting? It helps to see where in the program it's failing.
 
  • Like
Likes FritoTaco
  • #3
Borg said:
Can you post part of the stack trace error that you're getting? It helps to see where in the program it's failing.

You mean like this? (In the picture/attachment below).

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

Java:
g.fillRect(170,carY, 60,90);

This works fine, but instead, I want the carY in the image:

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:
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.
 

Attachments

  • Capture.PNG
    Capture.PNG
    36.5 KB · Views: 562
Last edited:
  • #4
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):
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);
 
  • Like
Likes FritoTaco
  • #5
Borg said:
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):

That's definately alright, no rush. As for the code, it was exactly what I was looking for, thank you!
 
  • Like
Likes Borg

1. What is a Java Applet?

A Java Applet is a small application written in the Java programming language that can be embedded into a web page. It is executed by a Java Virtual Machine (JVM) within a web browser, allowing for interactive and dynamic content on the webpage.

2. How do you create a Java Applet?

To create a Java Applet, you need to have a basic understanding of the Java programming language and an integrated development environment (IDE) such as Eclipse or NetBeans. You can then write the applet code using the Java Applet API and compile it into a .class file. This file can then be embedded into an HTML document using the <applet> tag.

3. What is a Moving Image Object in a Java Applet?

A Moving Image Object in a Java Applet is a graphical object that can be animated and moved within the applet. It is typically used to create dynamic and interactive content, such as games or visualizations.

4. How do you create a Moving Image Object in a Java Applet?

To create a Moving Image Object, you need to first define the image or shape you want to use as the object. This can be done using the getImage() or getShape() methods. Then, you can use the drawImage() or drawShape() methods to display the image or shape in the applet. Finally, you can use the translate() or rotate() methods to move and animate the object.

5. What are the benefits of using a Moving Image Object in a Java Applet?

Using a Moving Image Object in a Java Applet allows for more dynamic and interactive content on a webpage. It can make the webpage more engaging and visually appealing, which can be beneficial for educational or entertainment purposes. Additionally, it can also be used to create simple games or animations.

Similar threads

  • Programming and Computer Science
Replies
14
Views
3K
  • Programming and Computer Science
Replies
6
Views
2K
  • Programming and Computer Science
Replies
1
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
Back
Top