Search code examples
javaimageswingjlabel

Is there a way to paint on a picture in Java?


I know there has to be one, but if I'm adding one Label (which should be my background), and then paint on it(not on all of the space), the background does not show up. I'm quite sure that this is because Java completely over paint it with the standard grey, but I don't know how to tell Java to don't do that. setOpaque true and false (both the same) only stop the renewing of the pixels which I don't want to paint again (after repaint).


Solution

  • Custom painting (on any component) is done by overriding the paintComponent(...) method.

    So you can extend your JLabel and add custom code:

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g); // this will paint the label and its Icon
    
        // add custom code here
    }
    

    Read the section from the Swing tutorial on Custom Painting for more information and examples.

    Or another option is to extend a JPanel and paint the Image and then do your custom painting. This way all the painting code is located in one method.

    Try both approaches to see which meets your exact requirements.