swing - Trouble with Colours values in Java -
i'm creating class called rectangle, gets 2 ponits (the origin 1 , final one), , used fillrect() , drawrect() functions, activated method called visible. rectangle data coming main java class, both point , b's x's , y's positions, plus outline color (color) , fill color (color2). inside of class, i've created method (type int) called distance, allows me calculate distance between 2 points, giving height , width values (both int), can use value draw rectangle correctly. problem fact need multiply, in cases, height , width values -1. though both int types, wrongly switching color , color2 values (ex color = blue, color2 = red. after *-1, color = red, color2 = blue). of course, error doesn't happen when i'm not multiplying -1.
what doing wrong? why switching this?
check out code:
public class rectangle extends figure { protected point p1, p2, p3, p4; protected int height, width; public rectangle (int x1, int y1, int x2, int y2, color cor, color cor2) { super(cor, cor2); this.p1 = new point (x1, y1, cor, cor2); this.p2 = new point (x1, y2, cor, cor2); this.p3 = new point (x2, y1, cor, cor2); this.p4 = new point (x2, y2, cor, cor2); this.color = color; this.color2 = color2; if (x2 > x1 && y2 > y1) { this.height = distance(p1.getx(), p1.gety(), p3.getx(), p3.gety()); this.width = distance(p1.getx(), p1.gety(), p2.getx(), p2.gety()); }//correct! if (x2 < x1 && y2 < y1) { this.height = -distance(p1.getx(), p1.gety(), p3.getx(), p3.gety()); this.width = -distance(p1.getx(), p1.gety(), p2.getx(), p2.gety()); }//switched color! if (x2 > x1 && y2 < y1) { this.height = distance(p1.getx(), p1.gety(), p3.getx(), p3.gety()); this.width = -distance(p1.getx(), p1.gety(), p2.getx(), p2.gety()); }//switched color! if (x2 < x1 && y2 > y1) { this.height = -distance(p1.getx(), p1.gety(), p3.getx(), p3.gety()); this.width = distance(p1.getx(), p1.gety(), p2.getx(), p2.gety()); }//switched color! } public void visible(graphics g) { g.setcolor(this.cor2); g.fillrect(this.p1.getx(), this.p1.gety(), this.height, this.width); g.setcolor(this.cor); g.drawrect(this.p1.getx(), this.p1.gety(), this.height, this.width); } private int distance(int x1, int y1, int x2, int y2) { int distance = (int) math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)); return distance; }
it gets 2 ponits (the origin 1 , final one),
i'm guessing can't guarantee second point down , right first point. point above, resulting in negative y value or left resulting in negative x value.
i suggest can simplify code creating rectangle out of 2 points using code like:
int x = math.min(startpoint.x, endpoint.x); int y = math.min(startpoint.y, endpoint.y); int width = math.abs(startpoint.x - endpoint.x); int height = math.abs(startpoint.y - endpoint.y); rectangle rectangle = new rectangle(x, y, width, height);
now have rectangle drawrect() , fillrect() methods can use.
by way, don't call class rectangle, class defined in jdk.
Comments
Post a Comment