为JPanel添加椭圆形状

时间:2013-07-19 18:54:02

标签: java swing user-interface 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();
    }
}

1 个答案:

答案 0 :(得分: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教程,了解更多信息和更好的示例。

相关问题