Search code examples
javaswingjava-2dpaintcomponentpaint

Painting to objects on top of each other


I am trying to paint one Oval over another oval. Here i use a select statement to draw in the paint component method.

import java.awt.*;

public class test extends JPanel{

public static final int OVAL = 1;
public static final int SOLID = 2;

private int type = LINE;

public test(int type){

    this.type = type;
}
public void piantComponent(Graphics g){
   super.paintComponent(g);

   switch(type)
   {
      case OVAL:
      g.setColor(Color.YELLOW);
      g.drawOval(0,0,150,150);
      break;

      case SOLID:
      g.setColor(Color.BLUE);
      g.fillOval(0,0,50,50);
      break;

   }
 }


}

Now in my main method i want to display a solid blue oval (SOLID) inside of a yellow oval (OVAL).

  import...;
  public class Main{
      public static void main (String [] args){
             JFrame window = new JFrame();
             window.add(new test(test.OVAL));
             window.add(new test(test.SOLID));
             window.setSize(300,300);
             window.setVisible(true);

      }

  }

This does not do what I want it to do at all. This only displays a oval and not a oval and a solid. I think that i am overloading the window to only display the oval. I have tried to display with a layout manager(gridlayout) but that does not display the two paintings over each other it displays the two paintings next to each other.

How do i fix this without loosing the switch statement.


Solution

  • window.add(new test(test.OVAL));
    window.add(new test(test.SOLID));
    

    Your problem has to do with ZOrder. To simplify, Swing paints components in the reverse order they are found on the panel. So in your case the SOLID gets painted BEFORE the OVAL. Since the OVAL is larger in size it covers the SOLID.

    You can force Swing to paint the components in the more intuitive order by doing:

    window.add(0, new test(test.OVAL));
    window.add(0, new test(test.SOLID));
    

    Now the last component added will also be painted last.

    However a better design is to create separate Oval and Solid classes so you can specify size, location and color independently. Then you can add as many components to your panel as you want.