import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageMap extends JPanel {
BufferedImage image;
Rectangle left;
Rectangle right;
boolean showGrid = true;
public ImageMap(BufferedImage image) {
this.image = image;
addMouseListener(ml);
addComponentListener(cl);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(left == null) initRects();
g2.drawImage(image, left.x, left.y, this);
if(showGrid) {
g2.setPaint(Color.red);
g2.draw(left);
g2.draw(right);
}
}
public Dimension getPreferredSize() {
return new Dimension(image.getWidth(), image.getHeight());
}
private void initRects() {
int w = getWidth();
int h = getHeight();
int iw = image.getWidth();
int ih = image.getHeight();
int x = (w - iw)/2;
int y = (h - ih)/2;
left = new Rectangle(x, y, iw/2, ih);
right = new Rectangle(x+iw/2, y, iw/2, ih);
}
public static void main(String[] args) throws IOException {
String path = "images/owls.jpg";
BufferedImage image = ImageIO.read(new File(path));
ImageMap map = new ImageMap(image);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new JScrollPane(map));
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
private MouseListener ml = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
String s = "not over image";
if(left.contains(p))
s = "left";
if(right.contains(p))
s = "right";
System.out.println("s = " + s);
}
};
private ComponentListener cl = new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
left = null;
repaint();
}
};
}