java - MouseMotionListener showing (x,y) offset -
first of all, here related code:
canvas = new canvaspanel(); canvas.setbackground(color.white); canvas.addmouselistener(new pointlistener()); canvas.addmousemotionlistener(new pointlistener()); jsplitpane sp = new jsplitpane(jsplitpane.horizontal_split, leftpanel, canvas); class canvaspanel extends jpanel { public void paintcomponent(graphics page) { super.paintcomponent(page); if (mousedragged == true) { page.drawrect(x1, y1, x3, y3); canvas.repaint(); } } } class pointlistener implements mouselistener, mousemotionlistener { public void mousepressed (mouseevent event) { mousedragged = true; x1 = event.getx(); y1 = event.gety(); } public void mousereleased (mouseevent event) { // code } public void mousedragged(mouseevent event) { x3 = event.getx(); y3 = event.gety(); canvas.repaint(); }
so code doing when click on canvas component, draw outline of rectangle , size changes drag mouse
however, when click , start drag mouse, there's offset in bottom right corner of rectangle. seems jump bigger size second drag mouse. interestingly, closer upper left corner of canvas component click, closer rectangle size rectangle draw mouse.
how can fix this?
remember, drawrect
uses x
, y
, width
, height
it's parameters, should using delta between click point , drag point
maybe like...
public void paintcomponent(graphics page) { super.paintcomponent(page); if (mousedragged == true) { int x = math.min(x1, x3); int y = math.min(y1, y3); int width = math.max(x1, x3) - x; int height = math.max(y1, y3) - y; page.drawrect(x, y, width, height); } }
and, don't call repaint
within paint
methods
Comments
Post a Comment