Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 向JPanel添加椭圆形_Java_Swing_User Interface_Jpanel - Fatal编程技术网

Java 向JPanel添加椭圆形

Java 向JPanel添加椭圆形,java,swing,user-interface,jpanel,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.setS

这是我的简单代码。我真的不知道如何将绘制的椭圆形添加到
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();
    }
}

代码的基本结构是错误的。缓冲区类不应创建帧。缓冲区类应该只用于绘制。代码应该类似于:

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()
方法来设置自定义组件的大小。有关更多信息和更好的示例,请阅读上的Swing教程