Java JComponent.getGraphics() always returns null

2019-08-28 04:35发布

问题:

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.

回答1:

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.



回答2:

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