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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
import javax.imageio.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class JImagePanel extends JPanel {
private static final long serialVersionUID = 2724980460740151616L;
private Image _image;
private int _x;
private int _y;
private boolean _autoSize;
private boolean _keepAspect;
public JImagePanel(File file, int x, int y, boolean autoSize, boolean keepAspect) throws IOException {
super();
setImage(ImageIO.read(file));
setX(x);
setY(y);
setAutoSize(autoSize);
setKeepAspect(keepAspect);
}
public JImagePanel(File file, int x, int y, boolean autoSize) throws IOException {
this(file, x, y, true, false);
}
public JImagePanel(File file, int x, int y) throws IOException {
this(file, x, y, true);
}
public JImagePanel(File file) throws IOException {
this(file, 0, 0, true);
}
public JImagePanel(Image image, int x, int y, boolean autoSize, boolean keepAspect) {
super();
setImage(image);
setX(x);
setY(y);
setAutoSize(autoSize);
setKeepAspect(keepAspect);
}
public JImagePanel(Image image, int x, int y, boolean autoSize) {
this(image, x, y, true, false);
}
public JImagePanel(Image image, int x, int y) {
this(image, x, y, true);
}
public JImagePanel(Image image) {
this(image, 0, 0, true);
}
public JImagePanel() {
super();
setX(0);
setY(0);
setImage(null);
setAutoSize(false);
}
public void setImage(Image image) {
_image = image;
}
public void setX(int x) {
_x = x;
}
public void setY(int y) {
_y = y;
}
public void setAutoSize(boolean autoSize) {
_autoSize = autoSize;
}
public void setKeepAspect(boolean keepAspect) {
_keepAspect = keepAspect;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (_image != null) {
if (!_autoSize) {
g.drawImage(_image, _x, _y, _image.getWidth(null), _image.getHeight(null), null);
}
else {
Graphics2D g2d = (Graphics2D) g;
Double scaleWidth = new Double(getWidth()) / new Double(_image.getWidth(null));
Double scaleHeight = new Double(getHeight()) / new Double(_image.getHeight(null));
if (_keepAspect) {
if (scaleWidth > scaleHeight) {
scaleWidth = scaleHeight;
}
else {
scaleHeight = scaleWidth;
}
}
g2d.scale(scaleWidth, scaleHeight);
g2d.drawImage(_image, _x, _y, null);
}
}
}
} |