Graphics2D、Rectangle2D、Ellipse2D、Line2D的简单应用,原理为创建相应的图形对象,并设置图形的大小及相关设置,通过Graphics2D对象的draw方法将图形对象保存与JPanel面板中,通过Graphics2D对象的setPaint(setColor)方法可以设置相应的填充颜色
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
/**
*@version 1.0 2011-10-20
*@author Yanghai
*/
public class DrawFillTest
{
public static void main(String [] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DrawFillFrame frame=new DrawFillFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFillFrame extends JFrame
{
public DrawFillFrame()
{
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
setTitle("DrawFillTest");
DrawFillComponent component=new DrawFillComponent();
add(component);//将panel添加到frame中
}
public final int DEFAULT_WIDTH=400;
public final int DEFAULT_HEIGHT=400;
}
class DrawFillComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2=(Graphics2D) g;//将Graphics对象转换为Graphics2D对象
double leftX=100;
double topY=100;
double width=200;
double heigth=150;
/*
int leftX=100;
int topY=100;
int width=200;
int heigth=150;
Rectangle rect=new Rectangle.Double(leftX,topY,width,heigth);
g2.drawRect(rect);
*/
Rectangle2D rect=new Rectangle2D.Double(leftX,topY,width,heigth);
g2.draw(rect);
g2.setColor(Color.green);
g2.fillRect((int)leftX,(int)topY,(int)width,(int)heigth);
//g2.drawArc((int)leftX,(int)topY,(int)width,(int)heigth,0,180);
//g2.drawOval((int)leftX,(int)topY,(int)width,(int)heigth);
Ellipse2D ellipse=new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
g2.setPaint(Color.red);
g2.fillOval((int)leftX,(int)topY,(int)width,(int)heigth);
Line2D line=new Line2D.Double(leftX,topY,leftX+width,topY+heigth);
g2.draw(line);
double centerX=rect.getCenterX();//定义圆心坐标
double centerY=rect.getCenterY();
int r=150;
Ellipse2D circle=new Ellipse2D.Double();
circle.setFrameFromCenter(centerX,centerY,centerX+r,centerY+r);
//设置圆形的绘制框架(4个参数表示中心点坐标和角点坐标)
g2.draw(circle);
g2.setColor(new Color(0,128,128));
g2.fillArc((int)centerX-r,(int)centerY-r,300,300,0,90);
}
}
此段代码主要练习了如何构建矩形、椭圆、圆、直线以及相应的填充图形的一些知识。
编译效果如下: