图片上代码 IMG是局部变量就能正常打印出图片。是成员变量就不能打印。跪求高手指点其中原因。附上源码
package main;
import ui.GameJFrame;
public class Main {
public static void main(String[] args){
GameJFrame Demo = new GameJFrame();
}
}
package ui;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class GameJPanel extends JPanel{
//public Image IMG = new ImageIcon("graphics/background/Fish.jpg").getImage();
public GameJPanel(){
}
public void paint(Graphics g){
Image IMG = new ImageIcon("graphics/background/Fish.jpg").getImage();
System.out.println("1");
g.drawImage(IMG, 0,0, null);
System.out.println("1");
}
}
package ui;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class GameJFrame extends JFrame{
public GameJFrame(){
//设置标题
this.setTitle("行星防御理事会");
//设置窗口大小
this.setSize(1200,600);
//设置窗口可见
this.setVisible(true);
/*
* 通过获得基础工具包来获得屏幕的维度(Dimension),并计算出窗口在
* 屏幕的位置
* */
Toolkit toolKit = Toolkit.getDefaultToolkit();
Dimension screen = toolKit.getScreenSize();
int x = (screen.width-this.getWidth())/2;
int y = (screen.height-this.getHeight())/2;
this.setLocation(x, y);
/*
* 创建一个的panel(面板)
* */
this.setContentPane(new GameJPanel());
}
------解决思路----------------------
是挺奇怪的,如果采用成员变量,有时候第一次是看不到图片,最小化之后再点开就有图片了。这种情况可能与成员变量的初始化时机和paint方法处理机制有关系。