public class ImagePanel extends JPanel
{
private BufferedImage img;
private int originalImageWidth;
private int originalImageHeight;
private float proportion;
private int gapSizeT = 0;
private int gapSizeR = 0;
private int gapSizeB = 0;
private int gapSizeL = 0;
public ImagePanel(BufferedImage img)
{
super();
setImage(img);
}
public ImagePanel()
{
super();
}
public void setImage(BufferedImage img)
{
this.img = img;
originalImageWidth = img.getWidth();
originalImageHeight = img.getHeight();
proportion = (float) originalImageHeight / (float) originalImageWidth;
this.repaint();
}
public BufferedImage getImage()
{
return img;
}
public void setGapSize(int gapSizeT, int gapSizeR, int gapSizeB,
int gapSizeL)
{
this.gapSizeT = gapSizeT;
this.gapSizeB = gapSizeB;
this.gapSizeL = gapSizeL;
this.gapSizeR = gapSizeR;
repaint();
}
public int[] getGapSize()
{
int[] gapSizes = { gapSizeT, gapSizeR, gapSizeB, gapSizeL };
return gapSizes;
}
private Dimension adjustImageSize()
{
int width = originalImageWidth;
int height = originalImageHeight;
if (img.getWidth() > this.getWidth())
{
if (img.getHeight() > this.getHeight())
{
if ((float) this.getHeight() / (float) this.getWidth() < proportion)
{
height = this.getHeight() - (gapSizeT + gapSizeB);
width = (int) (height / (float) proportion);
} else
{
width = this.getWidth() - (gapSizeL + gapSizeR);
height = (int) (width * (float) proportion);
}
} else
{
width = this.getWidth();
height = (int) (width * (float) proportion);
}
} else
{
if (img.getHeight() > this.getHeight())
{
height = this.getHeight() - (gapSizeT + gapSizeB);
width = (int) (height / (float) proportion);
}
}
if (width < 0 || height < 0)
{
width = 0;
height = 0;
throw new IllegalStateException("gapSize is too large to display");
}
return new Dimension(width, height);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if (img != null)
{
Dimension d = adjustImageSize();
int x = (this.getWidth() - d.width) / 2 + (gapSizeL - gapSizeR);
int y = (this.getHeight() - d.height) / 2 + (gapSizeT - gapSizeB);
g.drawImage(img, x, y, d.width, d.height, null);
}
}
}