Adding oval shape to JPanel

梦想的初衷 提交于 2019-12-02 03:27:27

问题


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

回答1:


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

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.



来源:https://stackoverflow.com/questions/17753492/adding-oval-shape-to-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!