Program to create shapes and show them on console

2019-05-14 06:30发布

I was given small assignment as below . Can you please throw some light on how to implement this

Write a simple structured program and simple oo program that implements display shape function. Your program should simply print out (to console ) the number if shapes and then ask each shape to display itself which will also cause a line of output to be generated to the console , one for each shape . It is perfectly OK for your main program to create a collection of shapes before on to sorting that collection and displaying the shapes. Your program should support circles , triangles and squares but should use polymorphism so that the main program doesn't know the type of shape it is dealing with but instead treats shapes uniformly

I had created a program to create shapes like below but i'm not sure on how to create the shapes as mentioned and store them in collection and iterate to display these shapes on console. I was told not to use the database for storing shapes

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;

public class DrawShapes extends JApplet {

    public void paint(Graphics g) {
        g.setColor(Color.RED);
// drawing string
        g.drawString("Hello World!", 100, 100);
// drawing rectangle
        g.draw3DRect(120, 120, 120, 120, true);
        g.setColor(Color.blue);
        g.fill3DRect(120, 120, 120, 120, true);
// drawing circle
        g.drawOval(240, 240, 120, 120);
        g.setColor(Color.CYAN);
        g.fillOval(240, 240, 120, 120);
// drawing square
        g.drawRect(350, 350, 250, 100);
        g.setColor(Color.magenta);
        g.fillRect(350, 350, 250, 100);
// drawing trinale
    }
}

1条回答
何必那么认真
2楼-- · 2019-05-14 07:12

Just an idea how to do it. Notice, that the drawing is hidden from the shapes collection.

interface Drawable {
  public void draw(Graphics g);
}

class DrawableSquare implements Drawable{
  public DrawableSquare(int x, int y, int width) { ... }
  public void draw(Graphics g) 
  {
    g.fillRect(x, y, width, width);
  }
}

class Screen {
  Collection<Drawable> drawables;

  public void paint(Graphics g) {
     for (Drawable dr: drawables) {
       dr.draw(g);
     }
  }
}
查看更多
登录 后发表回答