Java Applet: Moving Image Object

  • Context: Java 
  • Thread starter Thread starter FritoTaco
  • Start date Start date
  • Tags Tags
    Image Java
Click For Summary

Discussion Overview

The discussion revolves around moving an image object (a car) in a Java applet using JButton actions. Participants explore how to modify the position of the car image based on button presses, contrasting it with a rectangle that serves as a visual reference.

Discussion Character

  • Technical explanation
  • Exploratory
  • Homework-related

Main Points Raised

  • One participant describes their intention to move an image of a car left and right using JButton actions, sharing relevant code snippets.
  • Another participant requests the stack trace of an error to better understand the issue being faced.
  • A later reply clarifies that the error is not related to compilation, as the code compiles and runs, but rather to the logic of applying position changes to the wrong graphic element.
  • One participant suggests modifying the code to correctly apply the position change to the car image instead of the rectangle, providing specific lines of code as guidance.
  • Another participant expresses gratitude for the clarification and confirms that the provided solution aligns with their needs.

Areas of Agreement / Disagreement

Participants generally agree on the need to adjust the code to move the car image correctly, but there is no consensus on the initial misunderstanding regarding the error and its implications.

Contextual Notes

There are unresolved aspects regarding the exact nature of the error messages and the specific conditions under which the car image movement is implemented. The discussion reflects varying levels of understanding about the Java applet's graphical rendering process.

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   Reactions: 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: 654
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   Reactions: 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 definitely alright, no rush. As for the code, it was exactly what I was looking for, thank you!
 
  • Like
Likes   Reactions: Borg

Similar threads

  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 14 ·
Replies
14
Views
6K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K