2017-04-02 77 views
1

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

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

回答

0

您发布的代码不能编译,所以现在有办法显示矩形。
int y定义在main中,并且在paintComponent中未被识别。
使它类变量:static int y;和初始化它在mainy = myY.nextInt();

+0

谢谢,赞赏。 – user62