0

How can we draw the shapes in Java like we do in paint?

For example if I want to draw the rectangle this command will draw it:

g2.fill3DRect(mt, mf, 45, 45, true); 

But how can I increase the or decrease the size of an object or shape during run-time using mouse like we did in paint?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mushahid Hussain
  • 4,052
  • 11
  • 43
  • 62
  • Side note. People typically recommend overriding `paint()` or `paintComponent()` & using that `Graphics` object to paint to. Here are 2 examples ([1](http://stackoverflow.com/a/10055672/418556), [2](http://stackoverflow.com/a/10055306/418556)) that instead use a `BufferedImage`. We can grab the graphics object direct from the image, in order to do 'custom painting'. – Andrew Thompson Apr 07 '12 at 17:07

2 Answers2

1

Use a mouse listener to get the position of the mouse after it has been pressed. i.e.

g2.fill3DRect(mt, mf, mouse.getX(), mouse.getY(), true); 

But clear the screen by drawing a rectangle over the entire screen before each draw so that there's not a million rectangles at the same time. This is the most basic example of course. Look into double buffering and practice.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
ghostbust555
  • 2,040
  • 16
  • 29
0

Implement a shape object that holds the attributes of the shape.

Your Panel should maintain a List of shapes that it draws when it needs to. Also one shape can be attached to the mouse.

Then register a mouselistener to your panel that will:

  • update your shape and redraw the panel if you move the mouse.
  • creates a new shape when you mouseDown
  • releases the shape when you mouseUp
kutschkem
  • 7,826
  • 3
  • 21
  • 56