Is it possible to make the user input the width and height of any shape?

时间:2015-11-18 21:02:24

标签: java swing jframe user-input

I am trying to write a code the asks the user: Which shape you want to draw?

and based on the choice, the user enters the parameters of the shape and it appears on the screen.

example: if user choose Rectangle, then they have to key in the height and width.

Is that possible to do ?

1 个答案:

答案 0 :(得分:1)

是的,这是可能的。

这是您使用扫描仪的方式:

How can I read input from the console using the Scanner class in Java?

上述网址内容简介:

Scanner sc = new Scanner(System.in);
int i = sc.nextInt();

System.out.println("Enter your username: ");
Scanner scanner = new Scanner(System.in);
String username = scanner.nextLine();

修改

这是一个应用上述概念并从用户获取半径并在框架上绘制圆圈的程序:

import java.awt.Frame;
import java.awt.Graphics;
import java.util.Scanner;

 public class Painting extends Frame{

 int num=0;

Painting(){
   super("Paint");
   setSize(300,300);
   setVisible(true);

   Scanner myScanner = new Scanner(System.in);
   System.out.println("Enter Radius");
   num = myScanner.nextInt();

  repaint();
      }

    public void paint(Graphics g){
        g.drawOval(50, 50, (2*num), (2*num));
     }

      public static void main(String[] args)
       {
          new Painting();
         }
        }