2013-03-23 159 views
0

我试图充当一个按钮,但使用的图像显示的对象。我的问题是,当致电getGraphics()它返回null。我一直在寻找整个地方,找不到原因?的Java JComponent.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); 

} 

我喜欢它,你可以给我帮助或指向它的正确方向。

+1

的getGraphics返回用于呈现组件中最后一个graphcs。如果评论从未呈现过,它将返回null。不建议使用这种方法来处理任何事情。因为它只返回用于呈现组件的最后一个图形上下文,所以当组件重新绘制时,它的任何更改都将被重写,相反,您应该重写paintComponent方法并在其中执行所有自定义绘画。 – MadProgrammer 2013-03-23 22:17:18

回答

3

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

+0

因此应该像... @Override public void paintComponent(Graphics g){ g.drawImage(button,0,0,this); } 但是,当我需要更改图像时,我该如何调用它? – handspiker2 2013-03-23 22:22:05

+0

当您需要更改图像时,请调用'repaint()'。 Swing将调用'paintComponent()'方法,该方法将绘制新图像。 – 2013-03-23 22:29:15

1

getGraphics将在构造函数中返回null,因为组件在创建时不可见。而对于Swing中的自定义绘画,则可改写paintComponent(g)方法。有Graphics句柄将始终正确初始化。

这里是一个example

更多阅读Performing Custom Painting