我正在尝试制作一个矩形,用户可以获得一个大小

时间:2017-04-02 12:27:35

标签: java graphics

我是java新手,我想创建一个矩形,它使用带扫描仪的用户输入来获取矩形的大小。问题是它需要用户输入但不显示矩形。我相信这是因为我的y整数是一个静态函数,但我不知道如何解决这个问题。我搜索谷歌很长一段时间,但我找不到答案。有人可以帮帮我吗?谢谢。 :)

    import java.util.Scanner;
    import java.awt.*;
    import java.awt.event.ActionListener;

    import javax.swing.*;

    public class Shape extends JPanel implements ActionListener{

        Timer tm = new Timer(5, this);

        public static void main(String[] args){
             System.out.println("Place in the width of your vaccum cleaner here:");     
             Scanner myY = new Scanner(System.in);
             int y = myY.nextInt();

             JFrame jf = new JFrame("Title");
             jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             Shape s = new Shape();
             jf.add(s);
             jf.setSize(600, 400);
             jf.setVisible(true);
        }
        public void paintComponent(Graphics g){
             super.paintComponent(g);
             this.setBackground(Color.PINK);

             g.setColor(Color.BLACK);
             g.fillRect(0, 0, 40, y);

             tm.start();
        }
    }

1 个答案:

答案 0 :(得分:0)

您发布的代码无法编译,因此现在可以显示矩形。
int y中定义了mainpaintComponent无法识别static int y;
使它成为一个类变量:main并在y = myY.nextInt();中将其初始化为:Object Oriented Programming