This is my class that everything is done in:
import java.awt.Color;
import java.awt.Graphics;
//This class will not compile until all
//abstract Locatable methods have been implemented
public class Block implements Locatable
{
//instance variables
private int xPos;
private int yPos;
private int width;
private int height;
private Color color;
//constructors
public Block () {}
public Block(int x,int y,int w,int h)
{
xPos = x;
yPos = y;
width = w;
height = h;
}
public Block(int x,int y,int w,int h, Color c)
{
xPos = x;
yPos = y;
width = w;
height = h;
color = c;
}
//set methods
public void setBlock(int x, int y, int w, int h)
{
xPos = x;
yPos = y;
width = w;
height = h;
}
public void setBlock(int x, int y, int w, int h, Color c)
{
xPos = x;
yPos = y;
width = w;
height = h;
color = c;
}
public void draw(Graphics window)
{
window.setColor(color);
window.fillRect(getX(), getY(), getWidth(), getHeight());
}
//get methods
public int getWidth()
{
return width;
}
public int getHeight()
{
return height;
}
//toString
public String toString()
{
String complete = getX() + " " + getY() + " " + getWidth() + " " + getHeight() + " java.awt.Color[r=" + color.getRed() + ", g=" + color.getGreen() + ", b=" + color.getBlue() + "]";
return complete;
}
}
and here is my interface class that has to be implemented:
public interface Locatable
{
public void setPos( int x, int y);
public void setX( int x );
public void setY( int y );
public int getX();
public int getY();
}
I haven't had formal instruction yet on interfaces/implementations and thus, am not sure what needs to be done to get the first class to run right
When you implementing an interface, you have to implement all the methods declared in that interface.
Interface is a contract that your implementing class must full fill.in your case your implementing class Block should implement the following methods to full fill the contract.
public void setPos( int x, int y);
public void setX( int x );
public void setY( int y );
public int getX();
public int getY();
public class Block implements Locatable {
public void setPos( int x, int y){
// your implementatioon code
}
public void setX( int x ) {
// your implementatioon code
}
public void setY( int y ){
// your implementatioon code
}
public int getX(){
// your implementatioon code
return (an int value);
}
public int getY(){
// your implementatioon code
return (an int value);
}
}
EDIT: for your NPE from the comments.
you never initialized your Color object.and trying to call a method on its refrence in your toString method.
private Color color;
initialize it like this
private Color color = new Color(any of the Color constructors);
check here for Color API
Related
For some reason, every time I jump in my the game I'm making, the jump gets shorter than the previous jump. Jumps start long and majestic (my game is set in space) and after about 10 jumps, my character is literally twitching against the ground because the jump is practically less than one pixel in height. I honestly cannot find out what is wrong with it, but I feel like it has something to do with the way I find deltaTime. Please help. I'm usually able to solve my own problems with a bit of troubleshooting and/or a bit of Googling, but I honestly don't know what's wrong and it all looks logical to me.
Sorry for the lack of comments. As you can probably tell from my nasty styles of implementing, this is kinda just a quick-write project so I don't really care much to look at the code later. I'm making this mainly to learn and practice Java.
I know there are a lot of out of class references so if you need to see one (I believe I included the important ones), just let me know.
Player Class (which extends Entity):
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.ArrayList;
import main.Main;
import scenes.Scene;
import threads.Time;
public class Player extends Entity {
private Scene scene;
private int HorizontalAxis = 0;
public float speed = 0.5f;
public float gravity = 0.001f;
public float jumpSpeed = 1f;
private float moveVelX = 0, moveVelY = 0;
public Player(String name, String tag, int x, int y, int w, int h, String spritePath, Scene scene) {
super(name, tag, x, y, w, h, spritePath);
this.scene = scene;
}
public void Update() {
//System.out.println(isGrounded());
if (Main.keyInput.getKeyState("MoveLeft")) {
HorizontalAxis = -1;
}
if (Main.keyInput.getKeyState("MoveRight")) {
HorizontalAxis = 1;
}
if (Main.keyInput.getKeyState("MoveLeft") == Main.keyInput.getKeyState("MoveRight")) {
HorizontalAxis = 0;
}
moveVelX = (HorizontalAxis * speed);
if (isGrounded()) {
moveVelY = 0;
if (Main.keyInput.getKeyState("Jump") || Main.keyInput.getKeyState("JumpAlt")) {
moveVelY = -jumpSpeed;
}
} else {
moveVelY += gravity * Time.deltaTime.getSeconds();
}
setTrueX(getTrueX() + moveVelX);
setTrueY(getTrueY() + moveVelY);
System.out.println(moveVelY);
}
public void render(Graphics2D g) {
g.drawImage(getSprite(), getX(), getY(), getWidth(), getHeight(), Main.display);
}
public boolean isGrounded() {
ArrayList<Entity> groundEntities = scene.FindEntitiesWithTag("Ground");
if (groundEntities.size() > 0) {
for (int i = 0; i < groundEntities.size(); i++) {
if (this.hitbox.intersects(groundEntities.get(i).hitbox)) {
return true;
}
}
return false;
} else {
System.err.println("There is no ground in the scene!");
return false;
}
}
}
Entity Class:
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import main.Main;
public class Entity {
public static enum AutoDrawTypes { NONE, RECTANGLE, RECTANGLE_ROUND, OVAL };
public static AutoDrawTypes autoDrawType = Entity.AutoDrawTypes.NONE;
public String name;
public String tag;
protected float x, y;
protected int arcWidth, arcHeight;
protected Rectangle hitbox = new Rectangle();
protected Image sprite;
protected Color color;
public Entity(String tag, String name, int x, int y, int w, int h, String spritePath) {
this.name = name;
this.tag = tag;
this.x = x;
this.y = y;
hitbox.setBounds((int)(getTrueX() - Camera.getX()), (int)(getTrueY() - Camera.getY()), w, h);
setSprite(spritePath);
this.autoDrawType = Entity.AutoDrawTypes.NONE;
}
public Entity(String tag, String name, int x, int y, int w, int h) {
this.name = name;
this.tag = tag;
this.x = x;
this.y = y;
hitbox.setBounds((int)(getTrueX() - Camera.getX()), (int)(getTrueY() - Camera.getY()), w, h);
this.autoDrawType = Entity.AutoDrawTypes.NONE;
}
public Entity(String tag, String name, int x, int y, int w, int h, Entity.AutoDrawTypes autoDrawType, Color color) {
this.name = name;
this.tag = tag;
this.x = x;
this.y = y;
hitbox.setBounds((int)(getTrueX() - Camera.getX()), (int)(getTrueY() - Camera.getY()), w, h);
this.autoDrawType = autoDrawType;
this.color = color;
}
public Entity(String tag, String name, int x, int y, int w, int h, Entity.AutoDrawTypes autoDrawType, Color color, int arcWidth, int arcHeight) {
this.name = name;
this.tag = tag;
this.x = x;
this.y = y;
hitbox.setBounds((int)(getTrueX() - Camera.getX()), (int)(getTrueY() - Camera.getY()), w, h);
this.autoDrawType = autoDrawType;
this.color = color;
this.arcWidth = arcWidth;
this.arcHeight = arcHeight;
}
public void UpdatePositionRelativeToCamera() {
hitbox.setBounds((int)(getTrueX() - Camera.getX()), (int)(getTrueY() - Camera.getY()), getWidth(), getHeight());
}
public Entity() {
}
public void Update() {
}
public void render(Graphics2D g) {
g.setColor(color);
if (autoDrawType == Entity.AutoDrawTypes.RECTANGLE) {
g.fillRect(getX(), getY(), getWidth(), getHeight());
}
if (autoDrawType == Entity.AutoDrawTypes.RECTANGLE_ROUND) {
g.fillRoundRect(getX(), getY(), getWidth(), getHeight(), arcWidth, arcHeight);
}
if (autoDrawType == Entity.AutoDrawTypes.OVAL) {
g.fillOval(getX(), getY(), getWidth(), getHeight());
}
}
public void setTrueX(float x) {this.x = x;}
public void setTrueY(float y) {this.y = y;}
public void setX(int x) {hitbox.x = x;}
public void setY(int y) {hitbox.y = y;}
public void setWidth(int width) {hitbox.width = width;}
public void setHeight(int height) {hitbox.height = height;}
public void setSprite(String path) {
Toolkit tk = Toolkit.getDefaultToolkit();
if (tk == null) {
System.err.println("Default Toolkit could not be fetched.");
return;
}
sprite = tk.getImage(Main.class.getResource(path));
if (sprite == null) {
System.err.println("Image not found at + '" + path + "'. Check path in resources folder.");
return;
}
}
public float getTrueX() {return this.x;}
public float getTrueY() {return this.y;}
public int getX() {return hitbox.x;}
public int getY() {return hitbox.y;}
public int getWidth() {return hitbox.width;}
public int getHeight() {return hitbox.height;}
public Image getSprite() {return sprite;}
}
Timing Class (which is run as a thread at the start of the application):
import java.time.Duration;
import java.time.Instant;
public class Time implements Runnable {
public static boolean running = false;
public static Duration deltaTime = Duration.ZERO;
public static Instant beginTime = Instant.now();
public void run() {
while (running) {
deltaTime = Duration.between(beginTime, Instant.now());
}
}
}
Nevermind, I fixed it. It was the way I calculated deltaTime. I decided just to remove deltaTime and reduce the gravity (even though it's already insanely small lol). That fixed the weird "smaller jumps over time" bug thing.
Take a look at this code for causing the player to fall down:
moveVelY += gravity * Time.deltaTime.getSeconds();
Notice that this causes the player's y velocity to increase by an amount that increases as a function of time. That is, it's as if gravity is constantly increasing as time passes. As a result, if you jump early on, it's like jumping on the moon, and if you jump later it's like jumping on Jupiter or the surface of a neutron star.
To fix this, remove the dependency on the current time. Just increase the y velocity by the gravity term, which should probably just be a fixed constant unless you're doing something cool with the world physics.
Could someone explain to me why I am getting these errors on my coding when it comes to the main method project5 class. thearray[count++] keeps giving me errors, and I am not entirely sure where I made my error. I've been stuck on it for awhile now. Some guidance would be nice.
Here is my main method:
public class Project5 {
private Shape [] thearray = new Shape[100];
public static void main (String [] args) {
Project5 tpo = new Project5();
tpo.run();
}
public void run () {
int count = 0;
thearray[count++] = new Circle(20, 20, 40);
thearray[count++] = new Triangle(70, 70, 20, 30);
thearray[count++] = new Rectangle(150, 150, 40, 40);
for (int i = 0; i < count; i ++ ) {
thearray[i].display();
}
int offset = 0;
double totalarea = 0.0;
while (thearray[offset] != null) {
totalarea = totalarea + thearray[offset].area();
offset++;
}
System.out.println("The total area for " + offset + " Shape objects is " + totalarea);
}
}
Here is my Circle class:
public class Circle {
private double radius;
public Circle() {
radius = 1.0;
}
public Circle(double newRadius) {
radius = 1.0;
setRadius(newRadius);
}
public void setRadius(double newRadius) {
if(newRadius > 0) {
radius = newRadius;
}
else {
System.out.println("Error: "
+ newRadius + " is a bad radius value.");
}
}
public double getRadius() {
return radius;
}
public double getArea() {
return radius * radius * Math.PI;
}
}
and here is my Shape class:
abstract class Shape{
int x = 1;
int y = 1;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Shape(int x, int y) {
this.x = x;
this.y = y;
}
public void display() {
}
public abstract double area();
}
I would post my triangle and rectangle class, but I figured this would be enough to at least have it explained where I am messing up.
I looked at your Circle class and the constructor currently only takes one argument. However, when you create a Circle you are specifying 3 arguments.
Circle should probably extend from Shape and the first two parameters are then the x and y position of the shape, correct? If this is the case, change your class as follows:
public class Circle extends Shape {
private double radius;
public Circle(int x, int y) {
super(x, y);
radius = 1.0;
}
public Circle(int x, int y, double newRadius) {
super(x, y);
setRadius(newRadius);
}
...etc
I was given an assignment to create a 3-d shape and prompt the user for the surface area and volume. I have multiple errors in my coding, but after research, I can not solve the problems.I attempted to fix the problem,but can not so I have // it out. Can anyone solve or steer me in the right direction?
The code is below:
//Point originOne = new Point(23, 94);
//Rectangle rectOne = new Rectangle(originOne, 100, 200);
//Rectangle rectTwo = new Rectangle(50,100);
//Point originOne;
//Point originOne = new Point(23, 94);
import javax.swing.JOptionPane;
public static void main(String[] args) {
int width;
int height;
Rectangle(volume,area);
JOptionpane.showMessageDialog("please input integer");
public static int volume;
int vol;
int side;
vol =side*3;
public static int area;
int
JOptionPane.showMessageDialog( null,"information",
, JOptionPane.OK_CANCEL_OPTION);
JOptionPane.showInputDialog("Please input a value");
public static int surfacearea;
}
public class Rectangle {
public int x = 0;
public int y = 0;
//constructor
public void Point(int a, int b) {
x = a;
y = b;
}
public int width = 0;
public int height = 0;
public int Point ;
public int origin;
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x;
origin.y = y;
}
// a method for computing the area of the rectangle
public int Area() {
//return width * height;
}
}
This should help slightly.. There is still a lot wrong with it. I hope my comments help a little, if you need anything else feel free to comment.
import javax.swing.JOptionPane;
import java.awt.Point;
public class Rectangle {
public static int area;
public static int volume;
public int x = 0;
public int y = 0;
public int width = 0;
public int height = 0;
public int Point; // Uh?
public int origin; // this isnt a Point and yet you are creating an instance of Point..
//constructor
/**
* What is even the point of this????
*/
public void Point(int a, int b) {
x = a;
y = b;
}
// main needs to go in a class
public static void main(String[] args) {
int width;
int height;
Rectangle myRectangle = new Rectangle(volume,area); // actually set a variable
//JOptionpane.showMessageDialog("please input integer"); // research this..
int vol;
int side; //side isnt initialized?
vol = side*3; //this will not work
//JOptionPane.showMessageDialog( null,"information", JOptionPane.OK_CANCEL_OPTION);
//JOptionPane.showInputDialog("Please input a value");
}
// four constructors
public Rectangle() {
origin = new Point(0, 0);
}
public Rectangle(Point p) {
origin = p;
}
public Rectangle(int w, int h) {
//This isnt calling your point method...
origin = new Point(0, 0);
width = w;
height = h;
}
public Rectangle(Point p, int w, int h) {
origin = p;
width = w;
height = h;
}
// a method for moving the rectangle
public void move(int x, int y) {
origin.x = x; // Again, this is declared as an int.
origin.y = y; // this is declared as a int.
}
// a method for computing the area of the rectangle
public int Area() {
return width * height;
}
}
I am trying to develop a checkerboard given a template of classes and some code for school. I got the board to appear but the right amount of checkers are not being drawn. There are supposed to be 7 red and 9 black checkers but each time I run the program a different amount of each is drawn.
import java.applet.Applet;
import java.awt.*;
import java.util.Random;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Checkers extends JApplet
{
private final int MAX_SIZE = 8;
private final int APP_WIDTH = 400;
private final int APP_HEIGHT = 400;
private final int MAXSIZE = 8;
Square[][] sq;
public void paint(Graphics page)
{
setBackground(Color.white);
fillBoard(page); // draws the method that will draw the checkers
placeCheckers(page, 7, Color.red); //method to place the red checkers
placeCheckers(page, 9, Color.black); //method to draw black checkers
CheckJumps(page); //check if checkers can jump
setSize (APP_WIDTH,APP_HEIGHT);
}
public void fillBoard(Graphics page)
{
sq = new Square[8][8];
int x,y;
Color rb;
for (int row = 0; row < MAXSIZE; row++)
for (int col = 0; col < MAXSIZE; col++)
{
x = row * (APP_WIDTH/MAXSIZE);
y = col * (APP_HEIGHT/MAXSIZE);
if ( (row % 2) == (col % 2) )
rb = Color.red;
else
rb = Color.black;
sq[row][col] = new Square (x, y, rb);
}
for (int row = 0; row < 8; row++)
for (int col = 0; col < 8; col++)
sq[row][col].draw(page);
}
public void placeCheckers (Graphics page, int num_checkers, Color ncolor)
{
int count, row, col;
int x, y;
Circle c;
Random rand = new Random();
for (count = 0; count < num_checkers; count++)
{
do
{
row = rand.nextInt(8);
col = rand.nextInt(8);
} while (sq[row][col].getOccupy() || ncolor == sq[row][col].getColor());
x = row * (APP_WIDTH/MAXSIZE);
y = col * (APP_HEIGHT/MAXSIZE);
c = new Circle (x, y, 50, ncolor);
c.draw(page);
sq[row][col].setOccupy(true);
}
}
class Square
{
private int x, y = 0;
private Color c;
private boolean occupied;
public Square (int x, int y, Color c)
{
this.x = x;
this.y = y;
this.c = c;
}
public void setX (int x)
{
x = this.x;
}
public int getX ()
{
return x;
}
public void setY (int y)
{
y= this.y;
}
public int getY ()
{
return y;
}
public void setColor (Color c)
{
c = this.c;
}
public Color getColor ()
{
return c;
}
public void setOccupy (boolean occupied)
{
occupied = this.occupied;
}
public boolean getOccupy ()
{
return occupied;
}
public String toString()
{
return ("X coordinate: " + x + "\nY coordinate:" + y + "\nSquare color: " + c);
}
public void draw (Graphics page)
{
page.setColor(c);
page.fillRect(x, y, 50, 50);
}
}
class Circle
{
private int x,y;
private int diameter;
private Color c;
public Circle (int x, int y, int diameter, Color c)
{
this.x = x;
this.y = y;
this.diameter = diameter;
this.c = c;
}
public void setX (int x)
{
x = this.x;
}
public int getX ()
{
return x;
}
public void setY (int y)
{
y= this.y;
}
public int getY ()
{
return y;
}
public void setColor (Color c)
{
c = this.c;
}
public Color getColor ()
{
return c;
}
public void setDiameter (int x)
{
diameter = x;
}
public void draw (Graphics page)
{
page.setColor(c);
page.fillOval(x, y, diameter, diameter);
}
}
If, you have followed some of the advice from your previous question you may have avoided this issue.
As near as I can tell, your problem is you're not calling super.paint, which is responsible for (amongst a lot of other things) preparing the Graphics context for painting. It does this, by clearing what ever was painted on it previously.
Instead of overriding paint of JApplet, which will cause flicker when the applet is updated, you should start with something like a JPanel and override it's paintComponent method. JPanel is double buffered, which will prevent any flicker from occuring. Don't forget to call super.paintComponent.
You shouldn't be calling fillBorder every time paint is called, this is wasteful on a number of levels, instead, you should only call it when you need to. With a little bit more clever design, you could actually get away with calling it from the constructor, but I don't have the time to re-code your entire program.
The size the applet is defined by the HTML page which contains it, not the applet itself, relying on magic numbers (like APP_WIDTH and APP_HEIGHT) is a bad idea. You should, instead, rely on known values, like getWidth and getHeight. This of course assumes you'd like to be able to resize the playable area and avoid possible issues with people deploying your applet with the wrong size ;)
While, I'm guessing that placeCheckers is a test method, you should know, paint can be called any number of times for any number of reasons, many of which you don't control, this means that the checkers will be randomized each time paint is called.
Instead, you should consider creating a virtual board which contains the information about the state of the game and update this as required. You would then simply use the painting process to reflect this model.
An example of how I might "start"...
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JApplet;
import javax.swing.JPanel;
public class Checkers extends JApplet {
#Override
public void init() {
add(new Board());
}
public class Board extends JPanel {
private final int APP_WIDTH = 400;
private final int APP_HEIGHT = 400;
private final int MAXSIZE = 8;
Square[][] sq;
#Override
public void invalidate() {
fillBoard();
super.invalidate();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
for (int row = 0; row < 8; row++) {
for (int col = 0; col < 8; col++) {
sq[row][col].draw(g);
}
}
setBackground(Color.white);
placeCheckers(g, 7, Color.red); //method to place the red checkers
placeCheckers(g, 9, Color.black); //method to draw black checkers
}
#Override
public Dimension getPreferredSize() {
return new Dimension(APP_WIDTH, APP_HEIGHT);
}
public void fillBoard() {
sq = new Square[8][8];
int x, y;
Color rb;
int gridSize = Math.min(getWidth(), getHeight());
int size = gridSize / MAXSIZE;
for (int row = 0; row < MAXSIZE; row++) {
for (int col = 0; col < MAXSIZE; col++) {
x = row * (gridSize / MAXSIZE);
y = col * (gridSize / MAXSIZE);
if ((row % 2) == (col % 2)) {
rb = Color.red;
} else {
rb = Color.black;
}
sq[row][col] = new Square(x, y, rb, size);
}
}
}
public void placeCheckers(Graphics page, int num_checkers, Color ncolor) {
int count, row, col;
int x, y;
Circle c;
int gridSize = Math.min(getWidth(), getHeight());
int size = gridSize / MAXSIZE;
Random rand = new Random();
for (count = 0; count < num_checkers; count++) {
do {
row = rand.nextInt(8);
col = rand.nextInt(8);
} while (sq[row][col].getOccupy() || ncolor == sq[row][col].getColor());
x = row * (gridSize / MAXSIZE);
y = col * (gridSize / MAXSIZE);
c = new Circle(x, y, size, ncolor);
c.draw(page);
sq[row][col].setOccupy(true);
}
}
}
class Square {
private int x, y = 0;
private Color c;
private boolean occupied;
private int size;
public Square(int x, int y, Color c, int size) {
this.x = x;
this.y = y;
this.c = c;
this.size = size;
}
public void setX(int x) {
x = this.x;
}
public int getX() {
return x;
}
public void setY(int y) {
y = this.y;
}
public int getY() {
return y;
}
public void setColor(Color c) {
c = this.c;
}
public Color getColor() {
return c;
}
public void setOccupy(boolean occupied) {
occupied = this.occupied;
}
public boolean getOccupy() {
return occupied;
}
public String toString() {
return ("X coordinate: " + x + "\nY coordinate:" + y + "\nSquare color: " + c);
}
public void draw(Graphics page) {
page.setColor(c);
page.fillRect(x, y, size, size);
}
}
class Circle {
private int x, y;
private int diameter;
private Color c;
public Circle(int x, int y, int diameter, Color c) {
this.x = x;
this.y = y;
this.diameter = diameter;
this.c = c;
}
public void setX(int x) {
x = this.x;
}
public int getX() {
return x;
}
public void setY(int y) {
y = this.y;
}
public int getY() {
return y;
}
public void setColor(Color c) {
c = this.c;
}
public Color getColor() {
return c;
}
public void setDiameter(int x) {
diameter = x;
}
public void draw(Graphics page) {
page.setColor(c);
page.fillOval(x, y, diameter, diameter);
}
}
}
Updated
This ones had me scratching me head for a while. Basically, after some additional checking I discovered that the checkers where being allowed to occupy space that was suppose to be already taken. After bashing me head against the do-while loop, I check the setOccupy method and found...
public void setOccupy(boolean occupied) {
occupied = this.occupied;
}
You're assiging the Square's occupied state back to the value you are passing, which has no effect on anything
Instead, it should look more like...
public void setOccupy(boolean occupied) {
this.occupied = occupied;
}
You may also like to have a read through Why CS teachers should stop teaching Java applets
Bah. I figured out the bug. Of course it was absurdly simple. The overridden update under MovingPanelItem needs to be written as follows:
#Override
public void update( int x, int y )
{
xCoord = xCoord + getxStep();
yCoord = yCoord + getyStep();
}
FULL DISCLOSURE: This is homework.
The PROBLEM:
Upon each Key listener event the screen should be updated and the moving objects should move. Currently, while the objects show up initially, if I press the prescribed key they disappear.
Also, all of the PanelItem's are stored in an ArrayList ( in another class ). All of the objects which are not subclasses of MovingPanelItem remain on the screen upon the KeyEvent.
I know I've left a lot to the imagination so if more detail is needed please let me know.
The superclass:
public class PanelItem
{
private Image img;
protected int xCoord;
protected int yCoord;
protected int width;
protected int height;
//constructor
public SceneItem( String path, int x, int y, int w int h )
{
xCoord = x;
yCoord = y;
setImage( path, w, h );
}
public void SetImage( String path, int w, int h )
{
width = w;
height = h;
img = ImageIO.read(new File(path));
}
//to be Overriden
public void update( int width, int height )
{
}
}
The Subclass:
public class MovingPanelItem extends PanelItem
{
private int xStep, yStep;
// x & y correspond to the coordinate plane
// w & h correspond to image width and height
// xs & ys correspond to unique randomized 'steps' in the for the x and y values
public MovingSceneItem(String path, int x, int y, int w, int h, int xs, int ys)
{
super( path, x, y, w, h);
setxStep(xs);
setyStep(ys);
update( x, y );
}
#Override
public void update( int x, int y )
{
this.xCoord = x + getxStep();
this.yCoord = y + getyStep();
}
}
(In response to Eels)
The panel/window itself is contained within the following class:
public class Panel extends JPanel {
protected ArrayList<PanelItem> panelItems;
private JLabel statusLabel;
private long randomSeed;
private Random random;
public Panel(JLabel sl) {
panelItems = new ArrayList<PanelItem>();
statusLabel = sl;
random = new Random();
randomSeed = 100;
}
private void addPanel() {
addPanelItems(10, "Mouse");
}
private void addPanelItems(int num, String type) {
Dimension dim = getSize();
dim.setSize(dim.getWidth() - 30, dim.getHeight() - 30);
synchronized (panelItems) {
for (int i = 0; i < num; i++) {
int x = random.nextInt(dim.width);
int y = random.nextInt(dim.height);
if (type.equals("Person")) {
int xs = random.nextInt(21) - 10;
int ys = random.nextInt(21) - 10;
panelItems.add(new Mouse(x, y, xs, ys));
}
}
repaint();
}
// causes every item to get updated.
public void updatePanel() {
Dimension dim = getSize();
synchronized (panelItems) {
for (PanelItem pi : panelItems) {
pi.update(dim.width, dim.height);
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
synchronized (panelItems) {
for (PanelItem pi : panelItems) {
pi.draw(g);
}
}
}
}
KeyListener class within the test class:
private class MyKeyListener extends KeyAdapter
{
#Override public void keyTyped(KeyEvent e)
{
if(e.getKeyChar() == 'f') {
panel.updatePanel();
panel.repaint();
}
// other key events include reseting the panel &
// creating a new panel, both of which are working.
}
}
Within the above code the only code I'm allowed to change ( & the only code I've written ) is the subclass MovingPanel item.