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;
}
}
Related
I am trying to move actor on stage from point to point by actions and it is not working, i have tried for hours and it just not working, i will be glad for help..
I have searched by the internet for codes and all i tried didn't worked, i really dont understand what is wrong with this code, it is basically the same as a working one on a tutorial in the internet
the actor class:
public class Player extends Actor {
float x,y;
float screenWidth,screenHeight;
private Sprite sprite;
Texture image;
float width,height;
public Player(Texture image,float x, float y,float width,float height, float screenWidth, float screenHeight)
{
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.screenWidth = screenWidth;
this.screenHeight = screenHeight;
this.image = image;
sprite = new Sprite(image, 0, 0, image.getWidth(), image.getHeight());
sprite.setPosition(x, y);
}
#Override
public float getX() {
return x;
}
#Override
public void setX(float x) {
this.x = x;
}
#Override
public float getY() {
return y;
}
#Override
public void setY(float y) {
this.y = y;
}
#Override
public float getWidth() {
return width;
}
#Override
public void setWidth(float width) {
this.width = width;
}
#Override
public float getHeight() {
return height;
}
#Override
public void setHeight(float height) {
this.height = height;
}
#Override
public void act(float delta) {
super.act(delta);
}
#Override
public void draw (Batch batch, float parentAlpha) {
batch.draw(sprite,x,y,width,height);
}
}
and the main class:
player = new Player(playerTexture,screenWidth/2,screenHeight-200,playerTexture.getWidth(),playerTexture.getHeight(),screenWidth,screenHeight);
MoveToAction action = new MoveToAction();
action.setPosition(300f,0f);
action.setDuration(10f);
player.addAction(action);
#Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.setProjectionMatrix(orthographicCamera.combined);
batch.begin();
// batch.draw(playerTexture,10,10,10,10);
batch.end();
stage.act(Gdx.graphics.getDeltaTime());
stage.draw(); //this will call the batch to draw the sprite
}
Actor already has x, y, width, and height fields. Since you created your own, you have hidden those parameters.
The source of your problem is that you failed to override setPosition() to use your fields. So the move action calls that and changes the fields that you have hidden and when you draw it, you are using your own fields that have not been changed.
Don't hide fields. It is very error-prone. You should delete the fields I mentioned above, along with all your overrides of getters and setters.
Here's a rule of thumb for OOP in general: if you are overriding any getter or setter without calling the super method, you are probably breaking something.
Unrelated, but you should be using TextureRegion instead of Sprite. A Sprite is a TextureRegion with additional parameters for size and position. Since those features are also in Actor, it is redundant and error-prone to use Sprite.
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;
}
}
I have a class named Circle and another class named POINT,thus Circle is made of radius and point(which is the center point of the circle).I'm trying to build a constructor and I bumped into an error message and I can't figure out the issue.
(Class Circle,the beginning of it)
public class Circle extends Shape {
private int radius, x, y;
Point point = new Point(0,0);
public Circle(radius,x, y){
this(5, 3, 6);
}
Class Point:
public class Point {
private int xPos,yPos;
public Point(int x, int y){
setxPos(x);
setyPos(y);
}
public int getxPos() {
return xPos;
}
public void setxPos(int xPos) {
this.xPos = xPos;
}
public int getyPos() {
return yPos;
}
public void setyPos(int yPos) {
this.yPos = yPos;
}
...
Change
public Circle(radius,x, y){
this(5, 3, 6);
}
To
public Circle(int radius,int x, int y){ //need to add types to parameters
this.radius=radius;
this.x=x;
this.y=y;
}
Or if you plan to use 5,3,6 as constant values add
public Circle(){
this.radius=5;
this.x=3;
this.y=6;
}
Your constructor is recursive eventhough your declaration is wrong as suggested by other answers I suggest you to change declaration and think again about your code you may want to initialize radius,x and y in constructor and you may want to declare some method to do operation on initialized value.
public Circle(int radius,int x, int y){
//Remove this from the constructor and perform initialization
this.radius=radius;
this.x=x;
this.y=y
}
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();
}
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.