日期:2014-05-20  浏览次数:20806 次

简单问题:为什么在JAPNEL上画背景图,图片闪了一下就消失了
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class shizhong extends JPanel
{  private static  Graphics g;
public shizhong() throws IOException //throws IOException
     {
  }

public static void main(String args[]) throws IOException
{
shizhong s=new shizhong();
s.shizz();
JFrame  jj=new JFrame();

jj.getContentPane().add(s,BorderLayout.CENTER);

jj.setSize(300,300);


jj.setVisible(true);
}
public void shizz() throws IOException
{
g=getGraphics();;
   
}

public void paintComponent(Graphics g)
{

File file=new File("image/shizhong.png");
  
 

   BufferedImage bi = null;
try {
bi = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();

Image im=(Image)bi;
 
 g=this.getGraphics();
g.drawImage(im,0,0,null);
}
}







------解决方案--------------------
说实话,你的程序如果能运行才是神奇!帮你改了一下!
1.永远不要在paintComponent里面加载任何图片资源,绝对禁止!
2.永远不要自己尝试获取Swing 2D图形设备对象!而是直接使用!
package com.gloomyfish.swing;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestJPanel extends JPanel {
/**
 * 
 */
private static final long serialVersionUID = 1L;
// private static Graphics g; very bad way!!!
private BufferedImage bi;
public TestJPanel() throws IOException // throws IOException
{

File file = new File("D:\\share_folder\\snow2006.jpg");
bi = null;
try {
bi = ImageIO.read(file);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public static void main(String args[]) throws IOException {
TestJPanel s = new TestJPanel();
JFrame jj = new JFrame();

jj.getContentPane().add(s, BorderLayout.CENTER);

jj.setSize(300, 300);

jj.setVisible(true);
}

public void paintComponent(Graphics g) {
if(bi != null)
{
g.drawImage(bi, 0, 0, null);
}
}
}