我试图充当一个按钮,但使用的图像显示的对象。我的问题是,当致电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);
}
我喜欢它,你可以给我帮助或指向它的正确方向。
的getGraphics返回用于呈现组件中最后一个graphcs。如果评论从未呈现过,它将返回null。不建议使用这种方法来处理任何事情。因为它只返回用于呈现组件的最后一个图形上下文,所以当组件重新绘制时,它的任何更改都将被重写,相反,您应该重写paintComponent方法并在其中执行所有自定义绘画。 – MadProgrammer 2013-03-23 22:17:18