Search code examples
javaswingpaintcomponent

How to add multiple layers onto JPanel


I need some help with Java Swing components and its capabilities. I need to add a JPanel to a JFrame and paint an Ellipse2D on it. Onto the Ellipse2D I want to add another element, in my case it is a picture (right now I use an ImageIcon, maybe wrong). How can I achieve adding the Ellipse2D and the picture on the panel as shown in the image I attached?

The reason why I need the images separated is, because I need to change the filling color of the ellipse sometimes.

Thanks for any help.enter image description here


Solution

  • What you need is to create a custom JPanel implementation and override paintComponent method.

    Inside it, you just do:

    public void paintComponent(Graphics g) {
    
        super.paintComponent(g);
    
        // Draw ellipse here
    
        // Draw your image here. It will be drawn on top of the ellipse.
    
    }
    

    This way, you can hold the ellipse fill color in the CustomPanel class, and just call repaint() method after you change the color.