import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; public class ImagePanel extends JPanel { private static final int INIT_WIDTH = 320; private static final int INIT_HEIGHT = 240; private static final double INIT_ZOOM = 1.0; private static final int INIT_ROTATION = 0; private double zoom = INIT_ZOOM; /* 0: no rotation, 1: 90 degrees, etc. */ private int rotation = INIT_ROTATION; private String whatever = null; private BufferedImage img = null; private AffineTransform trans = new AffineTransform(); public ImagePanel () { setOpaque(true); setBackground(Color.black); setPreferredSize(new Dimension(INIT_WIDTH, INIT_HEIGHT)); } private void setupTrans () { if (img != null) { /* double centerX = (double)img.getWidth() / 2; double centerY = (double)img.getHeight() / 2; */ double centerX = (double)getRotatedImageWidth() / 2; double centerY = (double)getRotatedImageHeight() / 2; // do zoom trans.setToScale(zoom, zoom); // move center back to center trans.translate(centerX, centerY); // rotate trans.rotate(rotation * Math.PI / 2); // move center of image to (0,0) for rotation trans.translate(-centerX, -centerY); setPreferredSize(getTransImageSize()); //System.out.println(getTransImageSize()); } revalidate(); repaint(); } public Dimension getTransImageSize () { Point p = (Point)trans.deltaTransform(new Point(img.getWidth(), img.getHeight()), new Point()); return new Dimension(Math.abs(p.x), Math.abs(p.y)); } protected boolean isRotated () { return rotation % 2 != 0; } protected int getRotatedImageWidth () { return isRotated() ? img.getHeight() : img.getWidth(); } protected int getRotatedImageHeight () { return isRotated() ? img.getWidth() : img.getHeight(); } public void setImage (BufferedImage img) { this.img = img; setupTrans(); } public double getZoom () { return zoom; } public void setZoom (double f) { //System.out.println("setZoom(" + f + ")"); if (f > 0) zoom = f; setupTrans(); } public void zoomTo (int w, int h) { System.out.println("zoomTo("+w+","+h+")"); if (img != null) { double xZoom = (double)w / getRotatedImageWidth(); double yZoom = (double)h / getRotatedImageHeight(); System.out.println(xZoom + ", " + yZoom); setZoom(Math.min(xZoom, yZoom)); } } public int getRotation () { return rotation; } /** Rotation is in units of 90 degrees. */ public void setRotation (int rotation) { this.rotation = rotation; setupTrans(); } public void setWhatever (String whatever) { this.whatever = whatever; repaint(); } public String getWhatever () { return whatever; } public void paintComponent (Graphics g) { Graphics2D g2 = (Graphics2D)g; super.paintComponent(g); if (img != null) { g2.drawImage(img, trans, this); if (whatever != null) { g.setColor(Color.black); g.drawString(whatever, 4*getWidth()/5, getHeight()-10); } } else { g.setColor(Color.white); g.drawString("[No image]", getWidth()/3, getHeight()/2); } } }