• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

repaint problem, rectangle selected appears on second time

 
vaibhav punekar
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am selecting the area of a component by mouse click and in the "mouseReleased" method I am taking "GraphicsContext " of that component.Using this "g",I am drawing a rectangle of selected area size.It is displayed when I select the area for the second time.First time hte component disappears for a fraction of a second and then it reappears.
So can anybody throw some light on it?I want user to be known about his area selection everytime he selects the area.
public void mouseReleased(MouseEvent me)
{
xend=me.getX();
yend=me.getY();
Graphics g=visualComponent.getGraphics();
visualComponent.setForeground(Color.red);
g.drawRect(xstart,ystart,xend-xstart,yend-ystart);
repaint();
}
Also there is paint method that has "Graphics g" parameter as usual.
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would save the rectangle outside of this method ( i.e. make the class have an attribute to save the rectangle ), in addition to a boolean that flags whether or not the rectangle needs to be drawn. Then, in my paint method, I would see if the boolean flag is true, and if so draw the rectangle. It isn't good practice to draw outside of the paint or update methods (or methods that are called by the paint or update) because the changes to the graphics context are not permanent. If you minimize and restore your program you will see that this is true because the rectangle will disappear.

-Nate
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic