本文介绍了Java JComponent.getGraphics()总是返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一个用作按钮的对象,但使用图像进行显示。我的问题是,当调用 getGraphics()时,它会返回 null 。我一直在寻找所有的地方,并找不到原因?

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.

推荐答案

您不应该调用 getGraphics()在一个组件上。相反,您应该重写 paintComponent(Graphics)方法,并使用作为参数传递的Graphics对象在此方法中绘画。

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.

这篇关于Java JComponent.getGraphics()总是返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 09:57