class ImagePanel extends JPanel
{
    private String strPicName;
    
    public ImagePanel(String strName)
    {
        strPicName = strName;
    }
    
    public void paintComponent(Graphics g)
    {
        loadPic(strPicName,g);
    }
    
      public void loadPic(String picName,Graphics g)
     {
          ImageIcon img=new ImageIcon(picName);
          int pWidth=this.getWidth();
          int pHeight=this.getHeight();
          int mWidth=img.getIconWidth() ;
          int mHeight=img.getIconHeight() ;
          int x,y;
          int width,height;
          if((mWidth<=pWidth)&&(mHeight<=pHeight)){
             x=(pWidth-mWidth)/2;    y=(pHeight-mHeight)/2;
             width=mWidth;   height=mHeight;
          }else {
             width=pWidth;   height=pHeight;
            float widthScale=(float)pWidth/(float)mWidth;
            float heightScale=(float)pHeight/(float)mHeight;
            if(widthScale<heightScale)
                height=(int)(mHeight*widthScale);
            else
                width=(int)(mWidth*heightScale);
             x=(pWidth-width)/2;
             y=(pHeight-height)/2;
          }
         //statusBar.setText("文件:"+ this +"    大小:"+mWidth+"X"+mHeight);
         g.clearRect(0,0,pWidth,pHeight);
         g.drawImage(img.getImage(),x,y,width,height,this);
    }
}

解决方案 »

  1.   

    final ImagePanel panel = new ImagePanel("G:\\Shooter\\icon.gif");
            getContentPane().add(panel,new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 150, -1, -1));
            
            JButton btnTest = new JButton("Load");
            btnTest.addActionListener(new ActionListener()
            {
                public void actionPerformed(ActionEvent event)
                {
                    panel.setPicName("G:\\Shooter\\blue-ball.gif");
                    repaint();
                }
            });
            
            getContentPane().add(btnTest,new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 150, -1, -1));