import javax.swing.*;
import java.awt.*;
import java.io.*;
import javax.imageio.*;public class Test
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
NotFrame frame=new NotFrame();
//frame.setBackground(Color.CYAN);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}class NotPanel extends JPanel
{

public void paintComponent(Graphics g)
{
String file="c:\\Sunset.jpg";
Image img;    //为什么不能在这里声明Image类的对象img??????????
try
{
img=ImageIO.read(new File(file));
}
catch(IOException e)
{
e.printStackTrace();
}

g.drawImage(img, 50, 50, 200,200,null);


}
        private Image img;     //只能在这里声明Image类的对象img}class NotFrame extends JFrame
{
public NotFrame()
{
setTitle("Not");
setSize(W,H);
setLocation(200,200);
setBackground(SystemColor.window);
NotPanel panel=new NotPanel();

add(panel);
}
public static final int W=450;
public static final int H=450;
}我的问题就是:为什么不在paintComponent()方法里直接声明一个Image类的对象引用img(报错为:img没有初始化),而只能在方法外面去声明img这个实例域???

解决方案 »

  1.   


    没有初始化就把它初始化成null不就行了吗?method中的变量在编译期间不会自动初始化,而class的变量会在编译期间初始化的~
      

  2.   

    1. image定义要放在函数public void paintComponent(Graphics g) 的外边,
        如果你放在函数里面,就变成局部变量,下面的g.drawImage(img, 50, 50, 200,200,null); 就调用不到了改了一下你的代码,我运行正确的:
    import javax.swing.*; 
    import java.awt.*; 
    import java.io.*; 
    import javax.imageio.*;   public class Test 
      { 
         public static void main(String[] args) 
         { 
             EventQueue.invokeLater(new Runnable()
             { 
               public void run() 
              { 
         NotFrame frame=new NotFrame(); 
         //frame.setBackground(Color.CYAN); 
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
         frame.setVisible(true); 
               } 
              } );
         } 
      }   class NotPanel extends JPanel  

    Image img =null; 
    public void paintComponent(Graphics g) 

    String file="C:\\JJ\\girl.jpg";   // c:\\Sunset.jpg
       //为什么不能在这里声明Image类的对象img?????????? 
    try 

       img=ImageIO.read(new File(file)); 

    catch(IOException e) 

        e.printStackTrace(); 
    } g.drawImage(img, 50, 50, 200,200,null); 

            //private Image img;    //只能在这里声明Image类的对象img

    class NotFrame extends JFrame 

    public NotFrame() 

    setTitle("Not"); 
    setSize(W,H); 
    setLocation(200,200); 
    setBackground(SystemColor.window); 
    NotPanel panel=new NotPanel(); add(panel); 

    public static final int W=450; 
    public static final int H=450; 
    }     
      

  3.   

    image定义要放在函数public void paintComponent(Graphics g) 的外边, 
        如果你放在函数里面,就变成局部变量,
      

  4.   

    img变量和g.drawImage(img, 50, 50, 200,200,null)同处在paintComponent()方法中,怎么会调用不到???
      

  5.   

    谢谢,按你说的我调试成功了,不过我还有疑问.
    我的这句话难道不是初始化吗?如下:
    img=ImageIO.read(new File(file));