`

instanceof关键字保存多种图形

阅读更多

instanceof关键字在我们平常敲代码时并不是经常用到,但是它在某些方面还是很重要的。比如说到画板保存着一块,我们若要同时绘制多种图形,想要把他们保存下来,这时instanceof的作用就体现了。

instanceof的用法其实很简单,例如:A instanceof B,如果instanceof左边的对象A含有右边B的类,那么这时返回的是boolean类型的值。所以instanceof经常是用于条件的判定。这很简单,但是可能会有点模糊,看看代码

List<Shape> shapeList = new ArrayList<Shape>();//队列来保存数据。

绘制以下三种图形时分别用shapelist来保存图形对象。

public void mouseReleased(MouseEvent e) {
			int x2 = e.getX();
			int y2 = e.getY();
				g.drawLine(x1, y1, x2, y2);
			Line line = new Line();
			line.setX1(x1);
			line.setY1(y1);
			line.setX2(x2);
			line.setY2(y2);
			shapeList.add(line);
		}

 

	public void mouseClicked(MouseEvent e) {
			int x = e.getX();
			int y = e.getY();
			int width = 40;
			int height = 40;
				g.fillRect(x, y, width, height);
			Rect rect = new Rect();
			rect.setX(x);
			rect.setY(y);
			rect.setWidth(width);
			rect.setHeight(height);
			shapeList.add(rect);
		}

 

public void mousePressed(MouseEvent e) {
			x1 = e.getX();
			y1 = e.getY();
			int width = 30;
			int height = 30;
				g.drawOval(x1, y1, width, height);
			Oval oval = new Oval();
			oval.setX1(x1);
			oval.setY1(y1);
			oval.setWidth(width);
			oval.setHeight(height);
			shapeList.add(oval);
		}

 

//保存时:

if("保存".equals(command)){
           File file = new Fil("C:\\Users\\Administrator\\Desktop\\java2.dat");
try {
//文件输出流对象
FileOutputStream fos = new FileOutputStream(file);
DataOutputStream dos = new DataOutputStream(fos);

for(int i=0;i<shapeList.size();i++){				
Shape shape = shapeList.get(i);	//获取队列中的对象					
if(shape instanceof Line){//如果是直线
							Line line = (Line)shape;
							dos.writeInt(1);
							dos.writeInt(line.getX1());
							dos.writeInt(line.getY1());
							dos.writeInt(line.getX2());
							dos.writeInt(line.getY2());
}
if(shape instanceof Rect){//如果是矩形
							Rect rect = (Rect)shape;
							dos.writeInt(2);
							dos.writeInt(rect.getX());
							dos.writeInt(rect.getY());
							dos.writeInt(rect.getWidth());
							dos.writeInt(rect.getHeight());
}
if(shape instanceof Oval){//如果是椭圆
							Oval oval = (Oval)shape;
							dos.writeInt(3);
							dos.writeInt(oval.getX1());
							dos.writeInt(oval.getY1());
							dos.writeInt(oval.getWidth());
							dos.writeInt(oval.getHeight());
}
}
fos.close();
} catch (Exception e1) {
	e1.printStackTrace();
}
}

 这里我用了三个例子,直线、矩形和椭圆。我这样做的前提是,我已经建好了Line、Rect和Oval(其属性get\set均有)三个对象同时去继承Shape类,而在Shape类当中,我们不必要去写任何的代码,当然也可以根据情况来适当去写一些。这里用了instanceof之后,可以很直接的将已经在画板上画好的的图形按照不同的类型来保存,这样的过程更加清晰明了。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics