我想要得到JLabel的对象的graphics,但是使用getGraphcis()方法的时候,却提示我出现空值,我找到是Graphics g这个对象是空值,换句话说就是getGraphics()是空值,我很奇怪,我看见很多书上都是这么直接用的,而且api上面也写着可以使用这个方法呀,但是为什么会出现这样的问题呢,希望有兄弟帮我解答````
public class MyLabel extends JLabel{
ImageIcon icon;
int x=0,y=0;
Graphics g;
public MyLabel(){
this.g=getGraphics();
}
public void setIcon(ImageIcon ic){
super.setIcon(ic);
this.icon=ic;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if(icon!=null){
//System.out.println("paint");

//g.drawImage(icon.getImage(),this.x,this.y,icon.getIconWidth()+this.x,icon.getIconHeight()+this.y,this);

}
}
public void run(){
for(int i=0;i<50;i++){
this.x=10;
if(this.getGraphics()==null) System.out.println("wrong");
System.out.println(icon.getIconWidth());
System.out.println(icon.getIconHeight());
g.drawImage(icon.getImage(),this.x,this.y,icon.getIconWidth(),icon.getIconHeight(),this);
repaint();
//System.out.println("run:");
this.x=0;
g.drawImage(icon.getImage(),this.x,this.y,this);
repaint();
}
}
}

解决方案 »

  1.   

    getGraphics()只能在那个Componnet已经显示时才能返回非空的,否则都是返回空值
    你在构造函数写getGraphics();因为它还没显示,所以返回空
      

  2.   

    但是我在调用这个mylabel的类里这样写了public class OwnCellRenderer extends JPanel implements ListCellRenderer {
    private MyLabel label1;public OwnCellRenderer(ImageIcon[] icons) {
       label1=new MyLabel();.................if(label1.getGraphics()==null) System.out.println("null");
    }..........................
    }
    结果还是输出了null,也就是说这个label还是为空的