0

I am trying to an object that functions as a button but uses images for display. My problem is that when call getGraphics() it returns null. I have been searching allover the place and cannot find why?

My code for the constructor where it dies at is...

public class ImageButton extends javax.swing.JComponent implements java.awt.event.MouseListener {

private static BufferedImage DEFAULTBUTTON;
private BufferedImage button;
private Graphics g;


public ImageButton(){
    //Call the constructor for JComponent
    super();
    //Grab Graphics
    g = this.getGraphics();

    //Find the default images
    try{
    InputStream image;
    image = this.getClass().getClassLoader().getResourceAsStream("DefaultButton.png");
    DEFAULTBUTTON = ImageIO.read(image);

    System.out.println("Default image FINE");
    }catch(IOException e){
        System.out.println("Default image fail");
    }
    button = DEFAULTBUTTON;

    //Add listener for things like mouse_down, Mouse_up, and Clicked
    this.addMouseListener(this);

    //Draw the Default button
    g.drawImage(button, 0, 0, this);

}

I would LOVE it you could give me help or point it the right direction.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
handspiker2
  • 3
  • 1
  • 2
  • 1
    GetGraphics will return the last graphcs used to render the component. If the comment has never been rendered, the it will return null. It is not recommended to use this method for, well, just about anything. Because it only returns he last graphics context used to render the component, any changes to it will be overridden when the component is repainted, instead, you should override the paintComponent method and perform all custom painting there – MadProgrammer Mar 23 '13 at 22:17

2 Answers2

3

You shouldn't call getGraphics() on a component. Instead, you should override the paintComponent(Graphics) method, and do the painting in this method, using the Graphics object passed as argument.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • So should it be like ... @Override public void paintComponent(Graphics g){ g.drawImage(button, 0 , 0, this); } But how would I call it when I need to change the image? – handspiker2 Mar 23 '13 at 22:22
  • When you need to change the image, call `repaint()`. Swing will invoke the `paintComponent()` method, which will paint the new image. – JB Nizet Mar 23 '13 at 22:29
  • What if you need a Graphics for font metrics, for properly sizing a dialog before you display it onscreen? – Stevey Apr 22 '21 at 20:33
1

getGraphics will return null in the constructor as the component will not be visible at the time of creation. For custom painting in Swing override the paintComponent(g) method instead. There the Graphics handle will always be properly initialized.

Here is an example

For more read Performing Custom Painting

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276