全局变量的声明
当一个类中有几个方法中都用到了一个变量名时,把这个变量在这个类的属性部分声明为全局变量,这样在下边的函数方法中就把那个变量的类型去掉。
package mydraw1.copy;import java.awt.Color;import java.awt.Graphics;import java.awt.event.MouseAdapter;import java.awt.event.MouseEvent;/* * 自定义鼠标监听类,继承MouseAdapter(或实现了MouseListener、MouseMotionListener) */public class MyMouseListener extends MouseAdapter{private int x1,y1,x2,y2;private Graphics g;private ToolPanel tool_panel;private ColorPanel color_panel;private Color color;private String command;//构造方法public MyMouseListener(ToolPanel tool_panel,ColorPanel color_panel,DrawPanel draw_panel){g=draw_panel.getGraphics();//获取画布this.tool_panel=tool_panel;//接收对象this.color_panel=color_panel;//接收对象}//按下public void mousePressed(MouseEvent e){x1=e.getX();y1=e.getY();command=tool_panel.getCommand();//获取标志color=color_panel.getColor();//获取颜色g.setColor(color);//设置画布的颜色}//释放public void mouseReleased(MouseEvent e){x2=e.getX();y2=e.getY();if("line".equals(command)){Line line=new Line(x1,y1,x2,y2,color);line.draw(g);}else if("rect".equals(command)){Rect rect=new Rect(x1,y1,x2,y2,color);rect.draw(g);}else if("oval".equals(command)){Oval oval=new Oval(x1,y1,x2,y2,color);oval.draw(g);}}//拖拽public void mouseDragged(MouseEvent e){x2=e.getX();y2=e.getY();Line line=new Line(x1,y1,x2,y2,color);line.draw(g);x1=x2;y1=y2;}}