Java JComponent.getGraphics() always returns null

一笑奈何 提交于 2019-12-13 04:25:14

问题


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



来源:https://stackoverflow.com/questions/15592651/java-jcomponent-getgraphics-always-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!