2013-07-19 79 views
2

这是我的简单代码。我真的不知道如何在JPanel上添加绘制的椭圆。我之前做过一些绘画,但我从未使用过构造函数,因此我没有任何想法。向JPanel添加椭圆形状

public class Buffer extends JPanel{ 
    public JFrame frame; 
    public JPanel panel; 

    public Buffer(){ 
     frame=new JFrame(); 
     panel=new JPanel(); 

     panel.setSize(500,500); 
     panel.setBackground(Color.red); 

     frame.setSize(500,500); 
     frame.setVisible(true); 
     frame.add(panel); 
    } 

    public void paintComponent(Graphics g){ 
     super.paintComponents(g); 
     g.fillOval(20,20,20,20); 
    } 

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

回答

2

你的代码的基本结构是错误的。 Buffer类不应该创建一个框架。 Buffer类只能用于绘画。代码应该是这样的:

public static void main(String args[]) 
{ 
    Buffer oval = new Buffer(); 
    oval.setBackground(Color.RED); 

    JFrame frame=new JFrame(); 
    frame.add(oval); 
    frame.setSize(500,500); 
    frame.setVisible(true); 
} 

确保您调用super.paintComponent()(不带“s”)。您还应该重写getPreferredSize()方法来设置自定义组件的大小。请阅读Custom Painting上的Swing教程以获取更多信息和更好的示例。