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这个实例域???
没有初始化就把它初始化成null不就行了吗?method中的变量在编译期间不会自动初始化,而class的变量会在编译期间初始化的~
如果你放在函数里面,就变成局部变量,下面的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;
}
如果你放在函数里面,就变成局部变量,
我的这句话难道不是初始化吗?如下:
img=ImageIO.read(new File(file));