Java Java Applet: Moving Image Object

  • Thread starter Thread starter FritoTaco
  • Start date Start date
  • Tags Tags
    Image Java
AI Thread Summary
The discussion revolves around moving a car image in a Java applet using JButton actions. The user initially struggles to connect the movement of the car image with the JButton actions, specifically wanting to replace a blue rectangle with the car image. The code includes a method to change the car's vertical position based on button clicks, but an error occurs when trying to implement this change in the image drawing method. Key points include the user’s confusion about how to properly use the variable `carY` for the car image's position, leading to an error message about incompatible types. A solution is provided, clarifying that the user should modify the `g2.drawImage` method to use `carY` for the car's vertical position instead of the fixed coordinates. The advice emphasizes that the car's position should be updated in the drawing method to reflect the changes made by the button actions, ensuring that the car image moves as intended. The user confirms that the provided solution resolves their issue.
FritoTaco
Messages
132
Reaction score
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

Technology news on Phys.org
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
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: 631
Last edited:
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
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
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Back
Top