本文主要是介绍全局变量的声明,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
[b]当一个类中有几个方法中都用到了一个变量名时,把这个变量在这个类的属性部分声明为全局变量,这样在下边的函数方法中就把那个变量的类型去掉。[/b]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;
}
}
这篇关于全局变量的声明的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!