问题描述
为什么我执行程序后都是变成先从0,0开始画直线,而不是从我按下鼠标的点开始画直线packageFrameGraphics;importjava.awt.Graphics;importjava.awt.event.MouseEvent;importjava.awt.event.MouseListener;importjavax.swing.JFrame;importjavax.swing.JPanel;publicclassGraphics1extendsJPanel{/***@paramargs*///JFramef=newJFrame();intxStrat,yStrat,xEnd,yEnd;JFramef=newJFrame();publicstaticvoidmain(String[]args){//TODOAuto-generatedmethodstubGraphics1d=newGraphics1();d.Init();}publicvoidInit(){f.addMouseListener(newMymouse());//f.add(p);f.add(this);f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);f.setSize(400,400);f.setVisible(true);}classMymouseimplementsMouseListener{@OverridepublicvoidmouseClicked(MouseEvente){//TODOAuto-generatedmethodstub}@OverridepublicvoidmouseEntered(MouseEvente){//TODOAuto-generatedmethodstub}@OverridepublicvoidmouseExited(MouseEvente){//TODOAuto-generatedmethodstub}@OverridepublicvoidmousePressed(MouseEvente){//TODOAuto-generatedmethodstubxStrat=e.getX();yStrat=e.getY();repaint();}@OverridepublicvoidmouseReleased(MouseEvente){//TODOAuto-generatedmethodstubxEnd=e.getX();yEnd=e.getY();repaint();}}publicvoidpaintComponent(Graphicsg){g.drawLine(xStrat,yStrat,xEnd,yEnd);}}大家帮帮我
解决方案
解决方案二:
思考一下,你刚按下鼠标,还没松开的时候,xStrat,yStrat,xEnd,yEnd的值等别是多少?g.drawLine(xStrat,yStrat,xEnd,yEnd)会画出什么结果?
解决方案三:
鼠标按下滑动抬起是一个动作,把这3个动作的鼠标坐标传给drawLine