集册 Java实例教程 显示类的形状

显示类的形状

欢马劈雪     最近更新时间:2020-01-02 10:19:05

597
显示类的形状

import javax.swing.JFrame;

import javax.swing.JOptionPane;

import java.awt.Graphics; //handle the display//来 自 N o w  J a v a  .   c o m

import javax.swing.JPanel;


class Shapes extends JPanel

{

   private int choice; // user's choice of which shape to draw

   

   // constructor sets the user's choice

   public Shapes(int userChoice)

   {

      choice = userChoice;
      /* 
       来自 
      *N o  w  J a v a . c o m - 时  代  Java*/

   } 

   

   // draws a cascade of shapes starting from the top-left corner

   public void paintComponent(Graphics g)

   {

      super.paintComponent(g);

      

      for (int i = 0; i < 10; i++)

      {

         // pick the shape based on the user's choice

         switch (choice)

         {

            case 1: // draw rectangles

               g.drawRect(10 + i * 10, 10 + i * 10, 

                  50 + i * 10, 50 + i * 10);

               break;

            case 2: // draw ovals

               g.drawOval(10 + i * 10, 10 + i * 10, 

                  50 + i * 10, 50 + i * 10);

               break;

         } 

      } 

   } 

}


public class Main

{

   public static void main(String[] args)

   {

      // obtain user's choice

      String input = JOptionPane.showInputDialog(

         "Enter 1 to draw rectangle\n" +

         "Enter 2 to draw ovals");

      

      int choice = Integer.parseInt(input); // convert input to int

      

      
展开阅读全文