Java 可视化第三小结
绘制 2D 图形需要 Graphics2D 类对象,这个类是 Graphics 类的子类,所以只要在paintComponent 方法里将进行一次 类型转换 即刻。
代码如下:
class DrawComponent extends JComponent
{
public DrawComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
...
}
}
而基本图形则有以下几种:
矩形:Rectangle2D
椭圆:Ellipse2D
线:Line2D
基本绘制图形的步骤:
在 Component 继承类中生成对象,并建立好图形,调用 g2.draw(shape x) 将其绘制在窗口上。
代码如下:
class DrawComponent extends JComponent
{
public DrawComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;
//绘制矩形
Rectangle2D rect = new Rectangle2D.double(x, y, width, height);
g2.draw(rect);
//绘制椭圆
Ellipse ellipse = new Ellipse.double();
ellipse.setFrame(rect);
g2.draw(ellipse);
}
}