Java JComponent.getGraphics() 始终返回 null

标签 java image swing graphics bufferedimage

我正在尝试一个充当按钮但使用图像进行显示的对象。我的问题是,当调用 getGraphics() 时,它返回 null。我到处找也没找到原因?

我的构造函数的代码是......

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);

}

我希望您能给我帮助或指出正确的方向。

最佳答案

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

关于Java JComponent.getGraphics() 始终返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15592651/

相关文章:

java - 导入 java com.google.* 库

java - Spring 启动: Use @Autowired within a Quartz Job

python - 如何使用 pylab 查看 RGB 图像

php - 如何将图像作为流提供

java - 如何在组件绘制时创建 "please wait"Swing 对话框

java - 将 JComboBox 添加到 jTable,每行包含特定数据

java - 方差实现应用于计算标准差?

java - Intellij IDE 在哪里存储一个项目的工件设置

java - 在 java 中将像素值从灰度设置为 0 和 1 时丢失图像部分

java - JTree 文件过滤器和文件夹过滤器