用jpanel 做画布,调节大小,图片不显示。只知道每次调节JFrame大小,都会重新调用repaint方法,所以图片会一闪而过,怎么样调节大小后Jpanel的图像依然显示呢?代码如下:import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JPanel;
public class MyJPanel extends JPanel {

Image image;
public MyJPanel(){

}
public void paintComponent(Graphics g,Image image)   
    {   
            
if(image==null){

        }
else{
this.image=image;
super.paintComponent(g);   
g.drawImage(image, 0, 0,this.getWidth(),this.getHeight(),null);

}

    }   
}
主程序调用放方法:picArea.paintComponent(picArea.getGraphics(),icon.getImage());图片显示,可是每次调节窗口大小,jpanel变成空白。请问有解决的方法吗?

解决方案 »

  1.   

    问题解决了
    public void paintComponent(Graphics g,Image image)  
    {              
       if(image==null){     } 
       else{ 
          this.image=image; 
          super.paintComponent(g);  
          g.drawImage(image, 0, 0,this.getWidth(),this.getHeight(),null); 
       } 
    }  
    每次调节窗口大小调用此方法,必须重写此方法 
    paintComponent(Graphics g)
    新增setImage(Image image) 方法传入image参数,就可以了。
      

  2.   


    /**
     * 初始化图像面板:添加事件监听器
     */
    public ImagePanel(){

    mouseListener  = new ImagePanelMouseAction();
    montionListener = new ImagePanelMouseMotionAction();

    addMouseListener(mouseListener);
    addMouseMotionListener(montionListener);
    }

    /**
     * 覆盖父类的画图方法
     */
    public void paintComponent(Graphics g){
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();//获取屏幕尺寸
    int w = getSize().width;//获取窗体宽度
    int h = getSize().height;//获取窗体高度
    int x = (dim.width-w)/2;
    int y = (dim.height-h)/2;
    setLocation(x,y);//将窗体移到屏幕中间
    g.drawImage(img, 0,0,null);
    }

    /**
     * 设置图像
     * @param image
     */
    public void setImg(BufferedImage image){
    img = image;
    }