5

I want to use the 2D Java API to draw on a JLabel that already has an image on it and then save the resulting edited picture.

I can't find any tutorials on this specific subject, does anyone have any code or references that show how to do it?

Jonas
  • 121,568
  • 97
  • 310
  • 388
James MV
  • 8,569
  • 17
  • 65
  • 96
  • 1
    Drawing in a JPanel is similar to drawing in any JComponent such as a JPanel. You can search this forum for many examples, shoot, many by me including [example 1](http://stackoverflow.com/questions/6575578/convert-a-graphics2d-to-an-image-or-bufferedimage/6575620#6575620), [example 2](http://stackoverflow.com/questions/7081308/jpanel-custom-drawing-using-graphics/7081362#7081362), [example 3](http://stackoverflow.com/questions/6105393/changing-jpanel-graphics-g-color-drawing-line/6105437#6105437) – Hovercraft Full Of Eels Dec 11 '11 at 17:48
  • and [example 4](http://stackoverflow.com/questions/7365535/best-to-handle-2-overlaying-live-updated-panels/7366478#7366478) – Hovercraft Full Of Eels Dec 11 '11 at 17:51
  • Thanks I'll have a good read! – James MV Dec 11 '11 at 17:54
  • 1
    Implementing `Icon` is a related approach, shown [here](http://stackoverflow.com/a/3484251/230513) and [here](http://stackoverflow.com/a/3072979/230513). – trashgod Dec 11 '11 at 17:59
  • Please let me know if anything is confusing or if you're still stuck. You'll likely get some good direct answers here soon. – Hovercraft Full Of Eels Dec 11 '11 at 17:59
  • @trashgod: great posts and great suggestions. I've upvoted the one that I hadn't upvoted previously. – Hovercraft Full Of Eels Dec 11 '11 at 18:01

2 Answers2

5

override the paintComponent method of the JLabel. It should first call super.paintComponent, so you get whatever the JLabel contains, then add your own drawing code after that. Should look somewhat like this:

public void paintComponent(Graphics g){
    super.paintComponent(g)
    g.drawWhatever ...
}
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
3

One approach would be to render the existing image and drawing into a BufferedImage, as shown in this example that overlays text on a logo. Once the image is complete, use ImageIO.write() to save it in the desired format.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045