2012-11-10 4 views
1

사실, 이미 단추의 이미지를 변경하는 방법을 알고 있지만 문제는 크기와 관련이 있습니다.JButton 이미지를 변경하고 크기를 유지

새 아이콘이 변경되었지만 크기를 유지하려고하지만이 변경 사항에 대한 조언을하시기 바랍니다.

이미지를 변경하기 전에 단추의 크기를 가져 오려고했지만 크기가 캐시되지 않고 시각적으로 변경되지 않았습니다.

+1

버튼에 맞게 이미지의 크기를 조정해야합니까, 아니면 버튼의 크기를 조정해야합니까? 가장 좋은 충고는 어느 것도하지 말고 동일한 크기의 아이콘 집합을 배포하는 것입니다. BTW - 아이콘은 종횡비가 동일합니까? –

답변

3

버튼이 고정 크기 인 아이콘을 사용하기 때문입니다. 자바에서이 작업을 수행하려면, 당신은 당신의 이미지 아이콘 개체에서

  • .getImage()해야하거나 다른 곳
  • 는 (새로운 BufferedImage
  • BufferedImage로, 이미지의 축소 버전을 그리기 확인 당신이 원하는 크기)로
  • ImageIcon 당신의 버튼에 보내기 새 이미지를 사용하여 새 ImageIcon을 확인

처음 세 단계는 까다 롭지 만 너무 나쁘지는 않습니다.

/** 
* Gets a scaled version of an image. 
* 
* @param original0 original Image 
* @param w0 int new width 
* @param h0 int new height 
* @return {@link java.awt.Image} 
*/ 
public Image getImage(Image original0, int w0, int h0) { 
    // Check for sizes less than 1 
    w0 = (w0 < 1) ? 1 : w0; 
    h0 = (h0 < 1) ? 1 : h0; 

    // The new scaled image (empty for now.) 
    // Uses BufferedImage to support scaling and rendering. 
    final BufferedImage scaled = new BufferedImage(w0, h0, BufferedImage.TYPE_INT_ARGB); 

    // Create a canvas to draw with, in the new image. 
    final Graphics2D g2d = scaled.createGraphics(); 

    // Try to prevent aliasing (if your image doesn't look good, read more about RenderingHints, they're not too hard) 
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); 

    // Use the canvas to draw the scaled version into the empty BufferedImage 
    g2d.drawImage(original0, 0, 0, w0, h0, 0, 0, original0.getWidth(null), original.getHeight(null), null); 

    // Drawing is finished, no need for canvas anymore 
    g2d.dispose(); 

    // Done! 
    return scaled; 
} 

그러나, 대신 외부 아이콘 파일의 크기를 조정 아마 더 나은, 그리고 응용 프로그램에 대한 추가 작업을 제공하지 : 여기 시작하는 방법입니다.

관련 문제