1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| public class ImagePanel extends JPanel {
private BufferedImage image;
public void setImage(BufferedImage image) {
this.image=image;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if ( image!=null ) {
final double width;
final double height;
if ( image.getWidth()>image.getHeight() ) {
final double scale = (getWidth()*1f)/image.getWidth();
width = getWidth();
height = image.getHeight()*scale;
}
else {
final double scale = (getHeight()*1f)/image.getHeight();
height = getHeight();
width = image.getWidth()*scale;
}
final double x = (getWidth()-width)/2;
final double y = (getHeight()-height)/2;
g.drawImage(image, (int)x, (int)y, (int)width, (int)height, this);
}
}
} |
Partager