2014-01-30 107 views
0

所以我一直试图在最后两个小时让程序在框架中绘制一个简单的矩形,但是当我运行程序时没有任何东西会显示在框架中。我已经浏览了教科书和旧笔记本,我的程序中的所有内容似乎都很好,但没有显示任何内容。帮帮我? 这是创建框架的类,应该绘制矩形。矩形将不会在JFrame中显示

import javax.swing.JFrame; 
public class FrameViewer { 


    public static void main(String[] args) { 

    //creates an empty frame. 
        JFrame frame = new JFrame(); 
      frame.setSize(300,400); 
      frame.setTitle("Empty Frame"); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    //draws the rectangle within the frame. 
      RectangleComponent component = new RectangleComponent(); 
      frame.add(component); 
      frame.setVisible(true); 
} 

}

这里是RectangleComponent

  import javax.swing.JComponent; 
     import java.awt.Graphics; 
     import java.awt.Graphics2D; 
     import java.awt.Rectangle; 

     public class RectangleComponent extends JComponent{ 
      public void paintCOmponent(Graphics g){ 
       Graphics2D g2 = (Graphics2D) g; 
       Rectangle box = new Rectangle(5,10,20,30); 
       g2.draw(box); 

} 

}

回答

4

Java是大小写敏感的,而不是

paintCOmponent 

你想

paintComponent 

您应该使用@Override注释来标记您认为自己重写的方法,因为它会突出显示类似的问题。

的方法也应该保持protected,因为没有任何理由应该从类的外部调用

你也可能想看看Initial Threads