-1

I coded a program where you can insert coordinates and the size of an sqaure and draw it on a JPanel. I used:

panel.getGraphics().drawRect(x,y,h,b);

Now I want to add an color-chooser like that:

color Farbe = JColorChooser.showDialog(null, "Color-Chooser", null);

So now how do I draw the Square with color? I tried this but it doesn't work:

panel.getGraphics().drawRect(x,y,h,b, Farbe);
Sébastien Le Callonnec
  • 26,254
  • 8
  • 67
  • 80
XPY64K
  • 34
  • 3

1 Answers1

1

panel.getGraphics() is NOT how custom painting should be performed.

See Painting in AWT and Swing and Performing Custom Painting for more details

Start by creating a custom component that extends from something JPanel, override it's paintComponent method (and make sure you call super.paintComponent before you do any custom painting).

Place you "drawing" logic within it. This panel should provide a setter and getter which allows external classes to change the color of the rectangle been draw, this way, when paintComponent is called, you can change the color of the Graphics context accordingly.

Also, take a look at 2D Graphics for more details about how painting is done

Don't forget to call repaint when the color is changed to encourage the panel to be repainted

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • While I agree with this answer, it doesn't really answer the question. Please add that `drawRect` doesn't have a colour parameter and that the OP needs to call `setColor`. – 11684 May 15 '15 at 07:59
  • @11684 `drawRect` is a method of the `Graphics` object, through which you would also change the color – MadProgrammer May 15 '15 at 09:24
  • Change colour through `drawRect()`?! Let me check the docs again. – 11684 May 15 '15 at 09:25
  • @11684 Not through `java.awt.Graphics`, you need to use one it's methods to change the color before you paint – MadProgrammer May 15 '15 at 09:27
  • Sorry, I don't understand your last comment. I checked the docs: as far as I can tell there is no `Color` parameter here: http://docs.oracle.com/javase/8/docs/api/java/awt/Graphics.html#drawRect-int-int-int-int- . Also, I don't see any overloads. – 11684 May 15 '15 at 09:28
  • @11684 That's right, you need to use one of the methods that `Graphics(2D)` provides to change the color of the graphics context BEFORE you try to painting to it. In three links I've linked to, there are numerous examples – MadProgrammer May 15 '15 at 09:29