aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes drawRect() issues Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "drawRect() issues" Watch "drawRect() issues" New topic
Author

drawRect() issues

Chris Dancy
Ranch Hand

Joined: Feb 14, 2006
Posts: 136
got a quick question if anyone can answer it. I want the drawRect(int,int,int,int) method to draw a rect in from one point to the next point. The problem is that drawRect() only draws from the topLeft corner of the screen to the bottomRight corner of the screen. If you try to draw it another way, it doesent work. Here is my code, can someone please tell me what im doing wrong? thanks
//Main class
class MouseDrawer extends MouseAdapter
{
public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();
fUpperLeft.setText(String.format("%d,%d",x1,y1));
mainPanel2.repaint();
}
}
class MouseMotionDrawer extends MouseMotionAdapter
{
public void mouseDragged(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
mainPanel2.setValues(x1,y1,x2,y2);
fArea.setText(String.format("%d",mainPanel2.getArea()));
fPerimeter.setText(String.format("%d",mainPanel2.getPerimeter()));
fLowerRight.setText(String.format("%d,%d",x2,y2));
fUpperLeft.setText(String.format("%d,%d",x1,y1));
mainPanel2.repaint();
}
}
}
class MyCirclePanel extends JPanel
{
private int length,width,x1,y1,x2,y2;
public void setValues(int x1,int y1,int x2, int y2)
{
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}
public int getPerimeter()
{
return Math.abs(length*2)+(length*2);
}
public int getArea()
{
return Math.abs(length*width);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(x1 < x2 && y1 < y2)
{
length = x2-x1;
width = y2-y1;
g.drawRect(x1,y1,x2-x1,y2-y1);
}
else if(x1 > x2 && y1 < y2)
{
length = y2-y1;
width = x1-x2;
g.drawRect(x1,y1,y2-y1,(x1-x2));
}
else if(x1 < x2 && y1 > y2)
{
length = x2-x1;
width = y1-y2;
g.drawRect(x1,y1,x2-x1,(y1-y2));
}
else // x1 > x2 && y1 > y2
length = x1-x2;
width = y1-y2;
g.drawRect(x1,y1,(x1-x2),(y1-y2));
}
}


("Anger is not an emotion, its a symptom of fear.")
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
I haven't tried running your code, but what about something like this to simplify the logic:


There is no emoticon for what I am feeling!
Chris Dancy
Ranch Hand

Joined: Feb 14, 2006
Posts: 136
Thanks a lot, it worked.

Sincerely,
Chris Dancy
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: drawRect() issues