如果使用Graphics g.fillOval(int,int,int,int)这里只是简单支持int类型的数据。意思就说会忽略到小数部分,如果你要画的圆都在0~1内那么所有的都会被画成一个点啦~当然你也不必要为此自己去写一个函数来实现这个功能。看看Graphics2D为我们带来了什么?
|
圆只是特殊的椭圆,我们设定好圆的中心以及a.b就可以完成圆的画法。更重要的是这里支持double类型的数据,以及不同的画法,fill()或者draw()。使用起来也非常方便~
下面给出Graphics2D中其他图形的方法
import java.awt.*; import java.awt.geom.*; import javax.swing.*; // 1. Graphics2D中绘制各种图形的方法 // 2. 矩形 椭圆 线 圆 // 3. GUI中组件 颜色 的设定 public class DrawTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable()//事件调度线程 { public void run() { DrawFrame fram=new DrawFrame(); fram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭 fram.setVisible(true);//可见 } }); } } class DrawFrame extends JFrame { public DrawFrame() { setTitle("DrawTest"); setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); //setBackground(Color.RED);//可用此方法设置组件背景色 DrawComponent component=new DrawComponent(); add(component); } public static final int DEFAULT_WIDTH=400; public static final int DEFAULT_HEIGHT=400; } class DrawComponent extends JComponent { public void paintComponent(Graphics g)//自动获取一个Graphics2D类对象 { Graphics2D g2=(Graphics2D)g; //画 矩形 double leftX=100;//左上点+宽高 double topY=100; double width=200; double height=150; Rectangle2D rect=new Rectangle2D.Double(leftX,topY,width, height); g2.draw(rect);//首先创建一实现了shape接口的类对象rect,然后调用Graphics2D的draw //另一方法--对角线 //Rectangle2D rect=new Rectangle2D.Double(); // rect.setFrameFromDiagonal(x1, y1, x2, y2); //亦有用中心的,rect.setFrameCenter //画 椭圆 Ellipse2D ellipse=new Ellipse2D.Double(); ellipse.setFrame(rect);//设置外接矩形 g2.setPaint(Color.BLUE); //设置当前绘制颜色,Graphics2D的对象 //Color.blue可用new Color(int redness,int greenness,int blueness) g2.draw(ellipse); //画 对角线 g2.draw(new Line2D.Double(leftX,topY,leftX+width,topY+height)); //画 圆(特殊的椭圆) double centerX=rect.getCenterX();//获取某形状的中心坐标 double centerY=rect.getCenterY(); double radius=50; Ellipse2D circle=new Ellipse2D.Double(); circle.setFrameFromCenter(centerX, centerY, centerX+radius, centerY+radius);//设置椭圆中点及a,b g2.fill(circle);//用当前颜色填充一图形 g2.setPaint(Color.BLUE)设置当前颜色 //g2.draw(circle); } } // Graphics2D中绘制各种图形的方法 // 主要方法: // Graphics2D g2=(Graphics2D)g; // g2.draw-------- // // 1. Rectangle2D rect=new Rectangle2D.Double(leftX,topY,width, height); // 2. Ellipse2D ellipse=new Ellipse2D.Double(); // ellipse.setFrame(rect);//设置外接矩形 // 3. g2.draw(new Line2D.Double(leftX,topY,leftX+width,topY+height)); // 4. Ellipse2D circle=new Ellipse2D.Double(); // circle.setFrameFromCenter(centerX, centerY, centerX+radius, centerY+radius); // 设置椭圆中点及a,b |