if ("三角形".equals(name)) {
gr.drawLine(x1, y1, x3, y3);
gr.drawLine(x2, y2, x3, y3);
flag = 1;
Shapes shape = new Shapes();
shape.x1 = x1;
shape.y1 = y1;
shape.x2 = x2;
shape.y2 = y2;
shape.x3 = x3;
shape.y3 = y3;
shape.name = name;
//保存对象到数组中
shapeArr[index] = shape;
index++;
}
public class Shapes {
//属性:需要保存的图形数据
public int x1,y1,x2,y2,x3,y3;
public Color color;
public String name="";
//方法:根据保存的数据还原图形
public void drawShape(Graphics g){
g.setColor(color);
switch (name){
case "直线":
g.drawLine(x1,y1,x2,y2);
break;
case "矩形":
g.drawRect(x1,y1,x2,y2);
break;
case "三角形":
g.drawLine(x1,y1,x2,y2);
g.drawLine(x1,y1,x3,y3);
g.drawLine(x3,y3,x2,y2);
break;
case "多边形":
g.drawLine(x1,y1,x2,y2);
break;
}
}
}
方法 格式:public 返回值类型 方法名(参数类型 参数名,,){ 方法体...}
构造方法 格式:public 类名(参数类型 参数名,,){ 方法体...}
区别:1.构造方法没有返回值类型 2.构造方法名必须是类名
作用:1.创建对象 2.同时给多个属性初始化
每个类都有一个默认的无参构造方法,当自己定义构造方法,那么默认的无参构造方法就会被替代
//this 表示本类对象
//super 表示当前类的父类对象
public Shapes(String name,int x1,int y1,int x2,int y2,int x3,int y3){
this.name = name;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
}
方法重载:同一个方法通过参数选择实现不同的功能
1.方法名重名 2.参数类型(个数,顺序)不一样
public Shapes(String name,int x1,int y1,int x2,int y2){
this.name = name;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
}

被折叠的 条评论
为什么被折叠?



