JAVA實現圖形類,並將其畫出。

import javax.swing.*;
import java.awt.*;
public abstract class Shape 
{
	public int x,y;
	public Color c;
	public Graphics g;
	public abstract double area();
	public abstract void draw(Graphics g);
	public Shape()
	{
	}
	public static void main(String[] args) 
	{
          MyFrame frame = new MyFrame();
          frame.setVisible(true);
	}
	public static class MyFrame extends JFrame 
	{
	        public static final String TITLE = "圖形繪製";
	        public static final int WIDTH = 250;
	        public static final int HEIGHT = 300;
	        public MyFrame() 
	        {
	            super();
	            setTitle(TITLE);
	            setSize(WIDTH, HEIGHT);
	            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	            setLocationRelativeTo(null);
	            MyPanel panel = new MyPanel(this);
	            setContentPane(panel);
	        }
	    }
	  public static class MyPanel extends JPanel 
	  {
	        private MyFrame frame;
	        public MyPanel(MyFrame frame) 
	        {
	            super();
	            this.frame = frame;
	        }
	        @Override
	        public void paint(Graphics g) 
	        {
	            super.paint(g);
	            Square s=new Square(20,40,80,80);
	            Rectangle r=new Rectangle(50,20,80,170);
	            Circle C=new Circle(70,20,8);
	            s.draw(g);
	            r.draw(g);
	            C.draw(g);
	        }
}
	
}
class Square extends Shape
{
	public int x,y;
	public int a,b;
	public Square(int px,int py,int a,int b)
	{
		x=px;
		y=py;
		this.a=a;
		this.b=b;
	}
	public double area()
	{
		return a*b;
	}
	public void draw(Graphics g)
	{
		g.setColor(Color.red); 
		g.drawRect(x,y,a,b);
	}
}
class Rectangle extends Square
{
	public int x,y;
	public int a,b;
	public Rectangle(int x,int y,int a,int b)
	{
		super(x,y,a,b);
		//paint(g);
	}
	public double area()
	{
		return a*b;
	}
	public void draw(Graphics g)
	{
		
		super.draw(g);
	}
}
class Circle extends Shape
{
	public int r;
	public int x,y;
	public Circle(int r,int x,int y)
	{
		this.r=r;
		this.x=x;
		this.y=y;
		//paint(g);
	}
	public double area()
	{
		return Math.PI*r*r;
	}
	public void draw(Graphics g)
	{
		g.setColor(Color.blue); 
		g.drawArc(x,y,r,r,0,360);
		
	}
}

 抽象類試驗。

定義一組具有繼承關係的類。Shape(形狀)類是一個抽象類,包含 4
個數據成員(座標 x,y,顏色 c,圖形對象 g(Graphics 類對象)),一個構造方法和兩
個抽象方法(求面積area()和draw方法) 。Square(正方形)由Shape派生,Rectangle
(矩形)由 Square 派生,Circle 由 Shape 派生。 
對上述類進行測試。 


請嘗試按照利用座標和顏色使用圖形對象的方法進行圖形對象的繪製和麪積輸出。
                                                                                                                                                                            JAVA上機實驗四

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章