0

Is there a way to draw shapes in general as discrete entities like in photoshop every rectangle drawn is an object that can be deleted, moved, removed especially when the object removed I remove the object in the code and it's removed from the JPanel or canvas I draw on instead of drawing the same object with the canvas background which I think is inefficient way.

For example, when we draw a rectangle using Grahpics2D we use commands like.

     @Override
     public void  paintComponent(Graphics canvas){

       super.paintComponent(canvas);

       ((Graphics2D) canvas).drawRect(20,20,100,100);          
      }

Now this drawn rectangle is associated with the upper-left vertex position and width and height. It's not associated with Rectangle object so there is no way to refer to the rectangle after it's drawn.

Abdelrahman
  • 525
  • 1
  • 4
  • 13
  • If you're familiar with `MVC` the above code is like having only the `View` part. You'd need a `Model` (the `Rectangle` object) wired in there to keep track of the state of your drawing. However this question is too broad to answer here. – Kayaman Nov 12 '17 at 18:18
  • A basic `GraphPanel` is cited [here](https://stackoverflow.com/a/10129994/230513) – trashgod Nov 12 '17 at 18:21
  • Could you provide me with a link of similar question? @Kayaman – Abdelrahman Nov 12 '17 at 18:30
  • I doubt there is a similar question, at least one with an answer (as I said, it's too broad). Easier would be to use an existing framework like @trashgod suggested. – Kayaman Nov 12 '17 at 18:32

1 Answers1

1

Now this drawn rectangle is associated with the upper-left vertex position and width and height. It's not associated with Rectangle object so there is no way to refer to the rectangle after it's drawn.

Create an ArrayListe of Shape objects. A Shape object can be a Rectangle, Ellipse, Polygon etc. Then in your paintComponent(...) method you iterated through the ArrayList to paint each Shape.

So the ArrayList contains the reference to your Rectangle.

Check out the Draw on Component example found in Custom Painting Approaches

If you want to get really fancy then check out Playing With Shapes. You can make your shape a real component.

camickr
  • 321,443
  • 19
  • 166
  • 288