将椭圆形添加到JPanel [英] Adding oval shape to JPanel

查看:108
本文介绍了将椭圆形添加到JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的简单代码。我真的不知道如何将绘制的椭圆添加到 JPanel 。之前我做了一些绘画,但我从未使用过构造函数,所以我没有想法。

Here's my simple code. I don't really know how to add a drawn oval to a JPanel. I did some paintings before, but I have never used the constructor so I don't have an idea.

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


推荐答案

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

The basic structure of your code is wrong. The Buffer class should not be creating a frame. The Buffer class should just be used for painting. The code should be something like:

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教程以获取更多信息,并获得更好的信息例如。

Make sure you invoke super.paintComponent() (without the "s"). You should also be overriding the getPreferredSize() method to set the size of your custom component. Read the Swing tutorial on Custom Painting for more information and a better example.

这篇关于将椭圆形添加到JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆