Adding oval shape to JPanel

2020-04-18 05:58发布

问题:

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.