Java 实现随机图形

要求

定义4个类,MyShape、MyLine、MyRectangle和MyOval,其中MyShape是其他三个类的父类。MyShape为抽象类,包括图形位置的四个坐标;一个无参的构造方法,将所有的坐标设置为0;一个带参的构造函数,将所有的坐标设置为相应值;每个坐标的设置和读取方法;abstract void draw(Graphics g)方法。MyLine类负责画直线,实现父类的draw方法;MyRectangle负责画矩形,实现父类的draw方法;MyOval负责画椭圆,实现父类的draw方法。编写一个应用程序,使用上面定义的类,随机选取位置和形状,绘制20个图形。示例输出如图所示。

代码

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

abstract class MyShape{
	int x = 0;
	int y = 0;
	int z = 0;
	int k = 0;

	public MyShape(){
		;
	}

	public abstract void draw(Graphics g);
}

class MyLine extends MyShape{
	Random rd = new Random();

	@Override
	public void draw(Graphics g){
		g.drawLine(x,y,z,k);
	}

	public MyLine(){
		int _x = rd.nextInt(200);
		int _y = rd.nextInt(200);
		int _z = rd.nextInt(200);
		int _k = rd.nextInt(200);

		x = _x;
		y = _y;
		z = _z;
		k = _k;

	}
}

class MyRectangle extends MyShape{
	Random rd = new Random();

	@Override
	public void draw(Graphics g){
		g.drawRect(x,y,z,k);
	}

	public MyRectangle(){
		int _x = rd.nextInt(200);
		int _y = rd.nextInt(200);
		int _z = rd.nextInt(200);
		int _k = rd.nextInt(200);

		x = _x;
		y = _y;
		z = _z;
		k = _k;
	}
}

class MyOval extends MyShape{
	Random rd = new Random();
	
	@Override
	public void draw(Graphics g){
		g.drawOval(x,y,z,k);
	}

	public MyOval(){
		int _x = rd.nextInt(200);
		int _y = rd.nextInt(200);
		int _z = rd.nextInt(200);
		int _k = rd.nextInt(200);

		x = _x;
		y = _y;
		z = _z;
		k = _k;
	}
}

class DrawComponent extends JComponent
{
	@Override
	public void paintComponent(Graphics g)
	{
		for(int i=0;i<20;i++) {
			if(i<6) {
				MyOval mo = new MyOval();
				mo.draw(g);
			}
			else if(i<12) {
				MyRectangle mr = new MyRectangle();
				mr.draw(g);
			}
			else {
				MyLine ml = new MyLine();
				ml.draw(g);
			}
		}
	}
}


class Game extends JFrame{
	Random rd = new Random();

	public Game(){
		this.add(new DrawComponent());
		this.setSize(600,600);
		this.setTitle("Graphics");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setVisible(true);
	}
}

public class Main1{
	public static void main(String [] args){
		new Game();
	}
}

代码分析

  • 使用抽象类
  • 覆写draw方法来绘画
  • 自定一个JComponent来调用各类的绘画方法

你可能感兴趣的:(java,java,GUI)