Search code examples
javaswingjpanelpaintcomponent

Paint new things on JPanel


Ok, so I have a JPanel with the paintComponent method overrided.

it's simple, looks like this:

public class Panel1 extends JPanel {

   public void paintComponent (Graphics g) {
      super.paintComponent (g);
      g.fillOval (0, 0, getWidth (), getHeight ());
   }
}

Now, I add this JPanel as an attribute to another JPanel class, like:

public class Panel2 extends JPanel {

   Panel1 panel;

   public Panel2 (Panel1 panel) {
      this.panel = panel;
   }

   protected void paintComponent (Graphics g) {
      super.paintComponent (g);
      panel.paint (g); //This isn't working.
//          panel.paintComponent (g); //Tried this too

      g.drawOval (100, 100, getWidth () - 200, getHeight () - 200);
   }
}

What I want is Panel2 to be painted exactly the same as Panel1 (without hard-coding it) and maybe add other stuff (like a triangle or sth, I don't know).

Is this even possible? I looked into it but didn't find any way to do it. Thanks in advance for your help!!

The MAIN in case it helps:

public class Main {

   public static void main (String[] args) {
      JFrame frame = new JFrame ();
      frame.setSize (500, 500);

      frame.add (new Panel2 (new Panel1 ()));

      frame.setVisible (true);
   }
}

EDIT: just in case, I don't want to do it with inheritance; that's why I add it as an attribute, but if there is other way just let me now.


Solution

  • You could try to make paintComponent of Panel1 public and then call it in paintComponent of Panel2:

    protected void paintComponent (Graphics g) {
        panel1.paintComponent(g);
    }
    

    You could also create a method inside your Panel1 class that handles the painting for you

    public void yourPainting(Graphics g){
        //whatever you want to paint
    }
    

    and then call this method in the paintComponent methods of both your Panel1 and your Panel2