写出一个random函数,随机产生执行接口shape的对象:包括矩形、椭圆,线等,位置随机,调用它10次,画出所有图形,
我看这道题目的意思就是执行shape接口,随机画出10个图形。已经写好的程序部分如下:
Use the following class as your main class:
import javax.swing.JFrame;
public class RandomShapeViewer
{
    public static void main(String[] args)
    {
        JFrame frame = new JFrame();
        final int FRAME_WIDTH = 300;
        final int FRAME_HEIGHT = 400;
        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.setTitle("RandomShapeViewer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        RandomShapesComponent component = new RandomShapesComponent();
        frame.add(component);
        frame.setVisible(true);
     }
}
Use the following class in your solution:
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class RandomShapesComponent extends JComponent
{
    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        RandomShapeGenerator r
         = new RandomShapeGenerator(getWidth(), getHeight());
        for (int i = 1; i <= 10; i++)
            g2.draw(r.randomShape());
    }
}
怎么产生随机图形呢,说是要实现shape interface啊

解决方案 »

  1.   

    如果你要画矩形、椭圆,你就让它们实现shape接口,然后再实现接口的子类里面产生图形,矩形类就产生矩形,椭圆类就产生椭圆
      

  2.   

    public interface shape{
        public void print();
    }public rectangle implements shape{
        public void print(){
          system.out.print("draw rectangle");
    }
    }public triangle implements shape{
        public void print(){
          system.out.print("draw triangle ");
    }
    }
    .
    .
    .
     public static void main(String[] args){
        Random rd=new Random();
        Shape shape=null;
        int num=rd.next(10);
        switch(num){
         case 1: new triangle ().print();
         case 2: new rectangle().print();
        .
        .
        .
    }
    }