Reputation: 373
I have a nice problem, because I have 3 classes:
public class GButton extends JComponent implements MouseMotionListener, MouseListener{
int x, y , w, h; //the coordinates of button
Graphics2D g2d;
public GButton(int x, int y){
this.x = x; this.y = y;
this.w = 200; this.h = 100;
... //add listeners, loading some information etc
}
@Override
public void paintComponent(Graphics g){
g2d = (Graphics2D) g;
...//loading and draw on g2d
g2d.drawString("asidoaisjdiajsoidj",x,y);
}
//code with using events of mouse and so on
}
And when I add button, the texture of button is 50px below y! Next buttons has grown this difference from y. Why? I know that because I check it with help MouseMove event. It isn't a bad size of images or something like that. Why it isn't working, and it paint things in other places? Is simpler way to get same effect? Please answer :)
Upvotes: 1
Views: 264
Reputation: 347314
You codes a little thin on the ground, however.
Graphics
context. 1. It is reused; 2. It may change between paint cycles. You are required to paint into the graphics context passed to your componentsuper.paintComponent
, this is incredibly important.I can't be 100% sure, but you appear that be under the impression that you are required to paint to the x/y position that the button appears on the screen, this is incorrect. The Graphics
context has already being translated so that position 0x0 is the top/left corner of your object.
I'd suggest you need to spend some time reading through
Upvotes: 1
Reputation: 16284
Never keep a global reference to Graphics
(and as well 2D).
If you do need, call g2d.dispose()
at the end of each drawing, obtaining a new graphical context the next time you want to use it.
Upvotes: 0