Program to create shapes and show them on console

别来无恙 提交于 2019-12-10 09:52:34

问题


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:


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);
     }
  }
}


来源:https://stackoverflow.com/questions/18657121/program-to-create-shapes-and-show-them-on-console

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!