Graphics对象强制转换为Graphics2D对象后才能在屏幕上画图或文本
想法问一下,上次有许多朋友说的,父类对象不可以直接强制转换为子类对象
如A类、 B类 ,B extends A的
A a=new A();
B b=new B();
b=(B)a; //把父类对象强制转换为子类对象, 编译无错,执行时出错。
但是为什么书的
Graphics对象强制转换为Graphics2D对象后才能在屏幕上画图或文本?
Graphics2D类是Graphics类的子类,用来绘制2D图形,这句话的意思是把Graphics类的对象g,强制转换成Graphics2D类的对象g2d。
import java.awt.*;
import java.applet.*;
import java.awt.geom.*;
import java.util.*;
public class RandomShapes extends Applet {
private Shape shape;
public void init() {
shape = new Rectangle2D.Double(-1.0,-1.0,1.0,1.0);
}
public void paint(Graphics g)
{
Graphics2D g2d=(Graphics2D)g;//★★★这句话是什么意思,为什么有这样的用法?
AffineTransform identity = new AffineTransform();
Random rand = new Random();
int width = getSize().width;
int height = getSize().height;
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, width, height);
for(int n = 0; n < 300;n++)
{
g2d.setTransform(identity);
g2d.translate(rand.nextInt()%width, rand.nextInt()%height);
g2d.rotate(Math.toRadians(360*rand.nextDouble()));
g2d.scale(60*rand.nextDouble(),60*rand.nextDouble());
g2d.setColor(new Color(rand.nextInt()));
g2d.fill(shape);
}
}
}