I am trying to understand how draw graphics to the JPanel class but i have only been able to display one object at a time(unless i draw muiltiple shapes in my extended JPanel class but i dont want that!)

import java.awt.*;
import javax.swing.*;

/* Create a new graphics component that draws two rectangles 
public class DrawRectangle extends JPanel
private int width;
private int length;
private int y;
private int x;
   // overrides javax.swing.JComponent.paintComponent
   public void paintComponent(Graphics g)
      //Recover Graphics2D
      Graphics2D g2 = (Graphics2D) g;
      //Construct a rectangle then draw it
      Rectangle box = new Rectangle(x, y, width, length);
   public DrawRectangle(int x, int y, int Width, int Length)
	   this.x = x;
	   this.y = y;
	   this.width = Width;
	   this.length = Length;	   

public static void main(String[] args)
   JFrame frame = new JFrame();
   final int FRAME_WIDTH = 300;
   final int FRAME_HEIGHT = 400;
   frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
   frame.setTitle("Test Picture");
   DrawRectangle component1 = new 
         DrawRectangle(10, 10 , 10 , 10);
   DrawRectangle component2 = new 
         DrawRectangle(15, 15 , 50 , 50);
   frame.add(component1);  //is not displayed!
   frame.add(component2);  //component2 overwrites component1!!!
7 Years
Discussion Span
Last Post by mart@efun.ee

What you want to do is draw two rectangles onto a window. What you're doing is creating two JPanels (which is essentially two different windows, not one), both of which have rectangles drawn inside of them, but you're putting the second JPanel on top of the first one - which is why you cannot see the first one. An analogy would be that you take two pieces of paper, draw a rectangle on each piece of paper, and then you put the second piece of paper on top of the first. Yeah, you drew two rectangles, but you can only see one.

To solve this issue, I'd paint the rectangles onto the same JPanel. You can use an Object to keep track of which coordinates you want to paint, and then in paintComponent, you'd paint those coordinates. Or you could set the coordinates (x, y, width, and height) and paint them, then set them again and paint again.

Another approach that could possibly work (but I'm not sure if it will) is to make the JPanel non-opaque. http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html#isOpaque%28%29 .. to try that approach all you'd have to do is set the top JPanel jpanel.isOpaque(false).

Edited by BestJewSinceJC: n/a

Votes + Comments
Nice explanation!

How did you solve the problem?
Replys are informative and i can understand the problem but how do you solve it? How do you add 2 objects that extend JPanel to one JFrame?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.