2011-01-13 56 views
0

我試圖調整一個圖像我已經繪製到ImagePanel(擴展JPanel),它似乎並沒有工作。我從互聯網上得到了一些覆蓋組件paint()方法的示例代碼,我想這可能是問題,這是我的代碼。Java Swing:調整JPanel的大小與圖像

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    if (img != null) { // Scale it by width int scaledWidth = (int)((img.getWidth() * getHeight()/img.getHeight())); 
     // If the image is not off the screen horizontally... 
     if (scaledWidth < getWidth()) { 
      // Center the left and right destination x coordinates. 

      int leftOffset = getWidth()/2 - scaledWidth/2; 
      int rightOffset = getWidth()/2 + scaledWidth/2; 
      g.drawImage(img, leftOffset, 0, rightOffset, getHeight(), 0, 0, img.getWidth(), img.getHeight(), null); 
     } 
     // Otherwise, the image width is too much, even scaled 
     // So we need to center it the other direction 
     else { 
      int scaledHeight = (img.getHeight() * getWidth())/img.getWidth(); 

      int topOffset = getHeight()/2 - scaledHeight/2; 
      int bottomOffset = getHeight()/2 + scaledHeight/2; 

      g.drawImage(img, 0, topOffset, getWidth(), bottomOffset, 0, 0, img.getWidth(), img.getHeight(), null); 
     } 
    } 
} 

,我從調用它...

public void resetImage(double width, double height) { 
    BufferedImage scaledImage = new BufferedImage((int)width, (int)height,BufferedImage.TYPE_INT_ARGB); 
    // Paint scaled version of image to new image 
    Graphics2D graphics2D = scaledImage.createGraphics(); 
    graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR); 

    this.setSize((int)img.getWidth(), (int)img.getHeight()); 
    graphics2D.drawImage(this.img, 0, 0, (int)width, (int)height, null); graphics2D.dispose(); 
} 

(其中寬度和高度,在此blurp是新的寬度和高度加以應用。

感謝。

+1

什麼不起作用?你期望發生什麼?給我們更多的好處 - 我們不會重新創建你的環境來幫助你。 – I82Much 2011-01-13 21:34:44

回答

1

您確定要調用方法paintComponent嗎?嘗試撥打ImagePanel.repaint()結束時resetImage