我正在尝试一个充当按钮但使用图像进行显示的对象。我的问题是,当调用 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/