How to make a triangle in java with getX() and getY()? - java

This is for a homework problem. I'm having a heck of a time trying to create xPoints and yPoints using getX() and getY() please help.
package shapes;
import java.awt.Color;
import java.awt.Graphics;
public class Triangle extends Rectangle {
//private int[] xPoints = {50, 100, 150};
//private int[] yPoints = {200, 100, 200};
private int[] xPoints = {(getX()/2), getX(), (getX()+(getX()/2))};
private int[] yPoints = {(getY()+getY()), getY(),(getY()+getY())};
public Triangle(int x, int y, int w, int h, Color lineColor, Color fillColor, boolean fill) {
super(x, y, w, h, lineColor, fillColor, fill);
}
public void draw(Graphics g) {
// Be nice. Save the state of the object before changing it.
Color oldColor = g.getColor();
if (isFill()) {
g.setColor(getFillColor());
g.fillPolygon(xPoints, yPoints, 3);
}
g.setColor(getLineColor());
g.drawPolygon(xPoints, yPoints, 3);
//g.drawOval(getX(), getY(), getWidth(), getHeight());
// Set the state back when done.
g.setColor(oldColor);
}
public int getArea() {
//return area;
return getWidth()*getHeight();
}
/**
* Returns a String representing this object.
*/
public String toString() {
//return "Triangle: \n\tx = " + getX() + "\n\ty = " + getY() +
//"\n\tw = " + getWidth() + "\n\th = " + getHeight();
return "Triangle";
}
}
// HERE IS THE SHAPE.JAVA FILE...
package shapes;
import java.awt.Color;
import java.awt.Graphics;
public abstract class Shape {
private int x, y;//,w,h;
private Color lineColor;
public Shape(int x, int y, Color lineColor) {
this.x = x;
this.y = y;
this.lineColor = lineColor;
}
public abstract void draw(Graphics g);
public abstract boolean containsLocation(int x, int y);
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 Color getLineColor() {
return lineColor;
}
public void setLineColor(Color lineColor) {
this.lineColor = lineColor;
}
}

First off, let's think about what you're trying to do in the opening line.
public class Triangle extends Rectangle {
Last I checked, a Triangle wasn't a type of Rectangle. Perhaps you should modify this to something like
public class Triangle extends Shape {
Or something more appropriate. Look in the shapes class to find the exact one.
Now, let's consider what you're doing in the class.
private int[] xPoints = {(getX()/2), getX(), (getX()+(getX()/2))};
private int[] yPoints = {(getY()+getY()), getY(),(getY()+getY())};
Are you sure you need to define these here? I'll bet you the Shape class already has arrays for xPoints and yPoints. Look in there for inspiration.
Also, if Shape DOES have xPoints and yPoints, and they're trying to use them, they won't be able to! Because you're defining Triangle.xPoints, Shape.xPoints will get "shadowed"... meaning xPoints in Shape will point to it's own xPoints, not the one you defined, resulting in a very quick NullPointerException.
Now, with a Rectangle, it's easy to define it as X,Y + W,H. It looks like this:
X,Y X+W,Y
+---------+
| |
| |
+---------+
X,Y+H X+W,Y+H
Now how are you going to represent your Triangle like that? Looks like you need to put some thought into how to represent your Triangle. Maybe there's some information in the Shape class that can help you here too.

Related

What is wrong with my jump logic?

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.

Most efficient way of using constructors, methods, data members in other classes JAVA

Couldn't find a relevant explanation online
I have homework to do I should create a class called Shapes and 2 more classes one for rectangle and the second is for a circle.
I wanted to know what is the best way to arrange constructors, data members and methods because for example for a rectangle I should have height and width and the circle has a radius.
public class Shapes {
//Should I use only common Data members, constructors and functions in the base class?
private int x;
private int y;
private int width;
private int height;
private String color;
private double radius;
also how do I create the relevant constructors using super()?
I think I got it all mixed up:
//Constructors:
public Shapes() {
}
//Common constructor
public Shapes(int x, int y, String color) {
setX(x);
setY(y);
setColor(color);
}
//Circle constructor:
public Shapes(int x, int y, String color, double radius) {
this(x, y, color);
setRadius(radius);
}
//Rectangle constructor:
public Shapes(int x, int y, int width, int height, String color) {
this(x, y, color);
setWidth(width);
setHeight(height);
}
in the rectangle class it looks like this:
public Rectangle() {
super();
}
public Rectangle(int x, int y, int width, int height, String color) {
super(x, y, width, height, color);
}
and in the circle class I did it like that:
public Circle() {
super();
}
public Circle(int x, int y, String color, double radius) {
super(x, y, color, radius);
}
I need a print method to print all info from each class that is relevant to the class is there any way using this print method in the base (shapes) class to avoid multiple print methods?
There are different parameters to show but we've been told to avoid multiplication of the code.
A base class should never have any properties that are not common to all of its subclasses. In fact, it shouldn't even know about its subclasses. For more information, read about the Liskov Substitution Principle and the Open/Closed Principle.
Therefore the base class should probably only have the parameters x, y and color. So the Shapes constructor could be like this:
public Shapes(int x, int y, String color) {
setX(x);
setY(y);
setColor(color);
}
and the Circle constructor like this:
public Circle(int x, int y, String color, double radius) {
super(x, y, color);
this.radius = radius;
}
The way you overloaded the base class constructors for fitting the different derived classes is really a very bad design. Not only does it contradict the aforementioned principles. It will also be very hard to understand for someone who reads the code.
Only put members in a super class if they will make sense for all sub-classes. You should also be using an abstract class to prevent creation of a plain Shape object, and the protected keyword in order to hide members from the outside world, but allow sub-classes to view them.
public abstract class Shape {
protected int x;
protected int y;
protected String color;
protected Shape() { this(0, 0, ""); }
protected Shape(int x, int y, String color) {
this.x = x;
this.y = y;
this.color = color;
}
// setter and getters for x, y, and color
}
public class Rectangle extends Shape {
private int width;
private int height;
public Rectangle() { this(0, 0, "", 0, 0); }
public Rectangle(int x, int y, String color, int width, int height) {
super(x, y, color);
this.width = width;
this.height = height;
}
// setters and getters for width and height
}
public class Circle extends Shape {
private double radius;
public Circle() { this(0, 0, "", 0.0); }
public Circle(int x, int y, String color, double radius) {
super(x, y, color);
this.radius = radius;
}
// setter and getter for radius
}
Let's start with the attributes. You should think if an attribute applies for subclasses of a class, or only for some of them. For example, does it make sense to put a "radius" attribute in the Shapes class? Will all subclasses of Shape need that attribute? Think of Rectangle: does a rectangle (instance) have a radius? If you declare the radius attribute in Shapes, what would be its value for rectangle instances? Avoid having spare attributes in classes, for perfomance but mainly for readability. The same applies to width and height.
Now, what about color? Will each and every shape have a color? So, it is a shared attribute?.
The x and y attributes are some kind of special here: the same attribute can mean two completely different things: for a circle should it be the center, but for rectangles could be the top-left (or whatever) point. Should them be the same attribute, or should be two different pair of attributes? I would go for the second, but it's my opinion.
Finally, regarding the constructors: would you let someone to create a shape instance without being either a circle or a rectangle? Do you need a public constructor in the Shapes class? Does have sense a shape being just a shape and not a circle or a rectangle (or any other subclass of Shape)?
By the way: I think it would be better to rename your Shapes class to just Shape.. a class represents one concept; then you can create instances of that concept, which are shapes...
=== EDIT ===
I forgot the last part of your question about print methods: one you decide where to put each attribute, you will find and answer for yourself.. can a method of a class access attributes in some of their subclasses?
Oh, something else: the toString method is allways present because it is defined in the Object class.. think about the relation of the toString method and the print method you need.
Make the shape class an abstract class with one abstract method which all the other classes will have to define
public abstract class Shape {
protected int x;
protected int y;
protected String color;
public Shape(String color) {
this.color = color;
}
public Shape() {
this("0xfffffff");
}
public Shape(int x, int y, String color) {
this(color);
this.x = x;
this.y = y;
}
public Shape(int x, int y) {
this();
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
public String getColor() { return color; }
public void setX(int x) { this.x = x; }
public void setY(int y) { this.y = y; }
public void setColor(String color) { this.color = color; }
#Override
public abstract String toString();
}
public class Rectangle extends Shape {
private int width;
private int height;
public Rectangle(int width, int height){
super();
this.width = width;
this.height = height;
}
public Rectangle(int width, int height, String color){
super(color);
this.width = width;
this.height = height;
}
public int getWidth() { return width; }
public int getHeight() { return height; }
// Also include setters if you don't need immutability
#Override
public String toString() {
return String.format("Rectangle\nWidth: %d\nHeight: %d\nColor: %s", width, height, color);
}
}
This is just my opinion. There are many other ways of structuring these classes, but it all depends on how you want to use them. The way I have provided makes it easy to extend this into 3D, so you can have 3D Shape base class declared like this:
public abstract class Shape3D extends Shape {
protected int z;
public Shape3D() {
super();
}
}
Not saying you will need a 3D object, but it's all about not entrapping yourself with design as the project gets more complex.
In your main class, you can have an array of Shapes and you can easily print them all knowing that they would have all defined the toString method.
public final class Main {
public static void main(String []args) {
List<Shape> shapes = new ArrayList<>();
// fill the list with all kinds of shapes
for (Shape shape: shapes) {
System.out.println(shape); // Will default to System.out.println(shape.toString());
}
}
}
One last to to make note of; When you find yourself having to write long constructors for a class, you might want to ask yourself if you will benefit from making use of the Builder pattern. For example the Rectangle class can be created with a builder like:
public abstract class ShapeBuilder {
int x, y;
String color;
public ShapeBuilder setX(int x) {
this.x = x;
return this;
}
public ShapeBuilder setY(int y) {
this.y = y;
return this;
}
public ShapeBuilder setColor(String color) {
this.color = color;
return this;
}
public abstract <T extends Shape> T build();
}
public class RectangleBuilder extends ShapeBuilder {
int width;
int height;
public RectangleBuilder setWidth(int width) {
this.width = width;
return this;
}
...
#Override
public Rectangle build() {
Rectangle rect = new Rectangle(width, height, color);
rect.setX(x);
rect.setY(y);
return rect;
}
}

Blackberry[CodeNameone]- Drawing on screen

I am beginner in codenameone. I have task assigned that draws anything[not rectangles or any shapes] on screen. Anything means It could be anything with fingers. Like android has gesturelayout where you can draw anything on surface.
I have seen some forums that said I should derive the container and override paint method. That never led me to anything. Even the tutorial guide just goes through steps.I won't some working examples or any link where i can find some suitable material.
Did you read the developer guide: http://www.codenameone.com/developer-guide.html
JavaDocs: https://codenameone.googlecode.com/svn/trunk/CodenameOne/javadoc/index.html
You should derive component and override paint, notice this code is really bad since it doesn't eliminate duplicates or do anything clever:
class Draw extends Component {
private ArrayList<Point> points = new ArrayList<Point>();
public Draw() {
setFocusable(true);
}
public void pointerPressed(int x, int y) {
points.add(new Point(x, y, 0xff0000));
}
public void pointerDragged(int x, int y) {
points.add(new Point(x, y, 0xff0000));
}
public void pointerReleased(int x, int y) {
points.add(new Point(x, y, 0xff0000));
}
public void paint(Graphics g) {
Point lastPoint = null;
for(Point p : points) {
if(lastPoint != null) {
g.setColor(p.color);
g.drawLine(lastPoint.x, lastPoint.y, p.x, p.y);
}
lastPoint = p;
}
}
}
class Point {
int x;
int y;
int color;
public Point(int x, int y, int color) {
this.x = x; this.y = y; this.color = color;
}
}

java space ship game

here is the entire code for the classes Ship,Asteroids,BaseShapeClass. Ship Class inherits from the BaseShapeClass for its shape. Asteroid class is the main source code which declares the Graphics2D object,AffineTransform(for identity creation),declares double image buffer...
Code for BaseShapeClass..
package baseshapeclass;
import java.awt.Shape;
public class BaseShapeClass {
private Shape shape;
private double x, y;
private double velX, velY;
private double moveAngle, faceAngle;
private boolean alive;
//accessors and mutators
public Shape getShape(){return shape;}
public void setShape(Shape shape){ this.shape = shape; }
public double getX() { return x; }
public void setX(double x) { this.x = x; }
public void incX(double ix) { this.x += ix; }
public double getY() { return y; }
public void setY(double y) { this.y = y; }
public void incY(double iy) { this.y += iy; }
public double getVelX() { return velX; }
public void setVelX(double velX) { this.velX = velX; }
public void incVelX(double ivX) { this.velX += ivX; }
public double getVelY() { return velY; }
public void setVelY(double velY) { this.velY = velY; }
public void incVelY(double ivY) { this.velY += ivY; }
//MoveAngle refers to the objects angular movement
public double getMoveAngle() { return moveAngle; }
public void setMoveAngle(double mAngle) { this.moveAngle = mAngle; }
public void incMoveAngle(double imAngle) { this.moveAngle += imAngle; }
//FaceAngle refers to the objects face/heads angular movement
public double getFaceAngle() { return faceAngle; }
public void setFaceAngle(double fAngle) { this.faceAngle = fAngle; }
public void incFaceAngle(double ifAngle) { this.faceAngle += ifAngle; }
public boolean isAlive() { return alive; }
public void setAlive(boolean alive) { this.alive = alive; }
//default constructor everything will be set to original state
//when update is called everything will start to move
BaseShapeClass(){
setShape(null);
setAlive(false);
//all of them are set to '0' representing their initial position,
//which will be called during the update() Event of the graphics objects
setX(0.0);
setY(0.0);
setVelX(0.0);
setVelY(0.0);
setMoveAngle(0.0);
setFaceAngle(0.0);
}
}
Code for Ship class...
package baseshapeclass;
import java.awt.Rectangle;
import java.awt.Polygon;
public class Ship extends BaseShapeClass {
//ships shape along the x and y cordinates
private final int[] shipx = {-6,3,0,3,6,0};
private final int[] shipy = {6,7,7,7,6,-7};
public Rectangle getBounds(){
Rectangle r = new Rectangle((int)getX()-6, (int)getY()-6, 12, 12);
return r;
}
Ship(){
setShape(new Polygon(shipx, shipy, shipx.length));
setAlive(true);
}
}
Code for Asteroid(Main source code)...
package baseshapeclass;
import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
public abstract class Asteroid extends Applet implements Runnable, KeyListener {
BufferedImage backbuffer;
Graphics2D g2d;
Ship ship = new Ship();
boolean showBounds= true;
AffineTransform identity = new AffineTransform();
#Override public void init(){
backbuffer = new BufferedImage(640,480,BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
ship.setX(320);
ship.setY(240);
addKeyListener(this);
}
#Override public void update(Graphics g){
g2d.setTransform(identity);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, getSize().width, getSize().height);
g2d.setColor(Color.WHITE);
g2d.drawString("Ship: "+Math.round(ship.getX())+" , "+Math.round(ship.getY()),2, 150);
g2d.drawString("Face Angle: "+Math.toRadians(ship.getFaceAngle()),5, 30);
g2d.drawString("Move Angle: "+Math.toRadians(ship.getMoveAngle())+90,5,50);
drawShip();
paint(g);
}
public void drawShip(){
g2d.setTransform(identity);
g2d.translate(ship.getX(),ship.getY());
g2d.rotate(Math.toRadians(ship.getFaceAngle()));
g2d.setColor(Color.ORANGE);
g2d.fill(ship.getShape());
}
}
I hope you guys get a better idea with all the code in place. Just wanted to know on the part of Ship class why are the ships x and y cordinates such as under:
public class ship extends BaseShapeClass{
private int[] shipx = {-6,3,0,3,6,0};
private int[] shipy = {6,7,7,7,6,-7};
}
I cant follow on how those values will make upto a Polygon??
Ship(){
setShape(new Polygon(shipx,shipy,shipx.length));
setAlive(true);
}
You can see that the two arrays you are confused about go into the initialization of a Polygon. These two arrays, taken as a pair, give the x and y coordinates of each point in the Polygon.
This post is in answer to your comment in Kronion's answer; I was going to post it as a comment, but there is too much to say and I wanted to show you some code, which is not as legible in the comments.
As Kronion said, the Polygon class does indeed accept an array of X coordinates, and an array of Y coordinates. The reason for this is that the X and Y coordinate are stored at the same position in both arrays. So if int index = 0, then that X,Y coordinate pair would be xArray[index] and yArray[index].
If that doesn't make any sense, examine the Polygon class source code. For example, you'll see this happening in the contains method, here:
for (int i = 0; i < npoints; lastx = curx, lasty = cury, i++) {
curx = xpoints[i];
cury = ypoints[i];
// remainder of loop
}
So in short, they are assigned in this manner because the X and Y are paired by their index positions.
Hope that helps.

Call an method of a class in an array - Java

I am having a problem with a project.
So basically what I have is a class Shape with some sub-class ( ShapeRectangle, ShapeTriangle, etc ).
In each sub-class, I got an outputShape method:
g.fillRect(getX(), getY(), getWidth(), getHeight());
In another class, showShapes, I got an array that contains the sub-classes.
I would like to run the method via the array.
Is there any way to do it?
EDIT:
The array in showShapes is a Shape[] array.
Here are the code of ShapeRect ( sorry, bits are in french ):
import java.awt.Color;
import java.awt.Graphics;
public class FormeRectangulaire extends Forme {
public FormeRectangulaire(int x, int y, int width, int height){
setX(x);
setY(y);
setWidth(width);
setHeight(height);
setColor(Color.RED);
}
public void afficherForme(Graphics g){
g.setColor(getColor());
g.fillRect(getX(), getY(), getWidth(), getHeight());
}
}
Here is the shape:
import java.awt.Color;
import java.awt.Graphics;
public class Forme {
private int x;
private int y;
private int width;
private int height;
private Color color;
/*public void afficherForme(Graphics g){
afficherForme(g);
}*/
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 Color getColor(){
return color;
}
public void setColor(Color color){
this.color = color;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
}
And here is how I put each class inside the array:
public void creerArrayFormes(){
String[][] donnes = getDatas();
if(donnes[getDatasElement()][0].equals("CARRE") || donnes[getDatasElement()][0].equals("RECTANGLE")){
FormeRectangulaire rect = new FormeRectangulaire(Integer.parseInt(donnes[getDatasElement()][1]),Integer.parseInt(donnes[getDatasElement()][2]),Integer.parseInt(donnes[getDatasElement()][3]),Integer.parseInt(donnes[getDatasElement()][4]));
setFormes(rect, getDatasElement());
}
}
You must create an array object or a List of SuperClass :
List<Form> shapes = new ArrayList<Form>();
//List<Form> shapes = new ArrayList<>(); in JDK 7
shapes.add(new ShapeRectangle());
shapes.add(new ShapeTriangle());
//....
Create a loop to get the objects :
for(int i = 0; i<shapes.size();i++){
Object obj = shapes.get(i);
if(objinstanceof ShapeRectangle){
((ShapeRectangle)obj).fillRect(....);
}
else if(list.get(i)
}
I strongly recommend adding outputShape to the Shape class. If Shape is naturally abstract (no expectation of actually creating a new Shape()) it can be abstract.
If you do that, you can just iterate over your Shape[] and call outputShape for an element. That will call the version of outputShape for the actual class of the element:
for(Shape s: shapes) {
s.outputShape();
}

Categories