问题描述
使用affinetransform进行图像的拖动时,鼠标的位置总是处于图像的左上角。如何改变鼠标的位置,使得鼠标可以点中图像中的任意位置而进行拖动?
解决方案
解决方案二:
下面的程序也体现了这个问题,不管当鼠标点中正方形的哪个部分,当拖动时,正方形自动跳到鼠标的右下角。importjava.awt.Graphics;importjava.awt.Graphics2D;importjava.awt.Point;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjava.awt.event.MouseMotionListener;importjava.awt.geom.AffineTransform;importjava.awt.geom.Point2D;importjava.awt.geom.Rectangle2D;importjava.awt.geom.Point2D.Double;importjavax.swing.JFrame;importjavax.swing.JPanel;publicclassAffineTestextendsJFrame{/****/privatestaticfinallongserialVersionUID=1L;publicRectangle2D.Doublerect=newRectangle2D.Double(30,50,60,60);publicdoublemovex=0,movey=0;Point2DclickPoint=newPoint2D.Double(0,0);publicAffineTest(){this.setSize(600,600);this.setLocationRelativeTo(null);this.add(newDrawingPanel());this.setVisible(true);}privateclassDrawingPanelextendsJPanel{publicDrawingPanel(){this.addMouseListener(newpanelListener());this.addMouseMotionListener(newpanelListener());}publicvoidpaintComponent(Graphicsg){super.paintComponent(g);AffineTransformtx=newAffineTransform();if(rect.contains((Point2D.Double)clickPoint)){tx.translate(movex,movey);}Graphics2Dg2d=(Graphics2D)g;g2d.setTransform(tx);g2d.draw(rect);repaint();}}privateclasspanelListenerimplementsMouseListener,MouseMotionListener{@OverridepublicvoidmouseClicked(MouseEvente){clickPoint.setLocation(e.getX(),e.getY());repaint();}@OverridepublicvoidmouseEntered(MouseEventarg0){//TODOAuto-generatedmethodstub}@OverridepublicvoidmouseExited(MouseEventarg0){//TODOAuto-generatedmethodstub}@OverridepublicvoidmousePressed(MouseEventarg0){//TODOAuto-generatedmethodstub}@OverridepublicvoidmouseReleased(MouseEventarg0){//TODOAuto-generatedmethodstub}@OverridepublicvoidmouseDragged(MouseEventarg0){movex=arg0.getX();movey=arg0.getY();}@OverridepublicvoidmouseMoved(MouseEventarg0){//TODOAuto-generatedmethodstub}}publicstaticvoidmain(String[]args){newAffineTest();}}