import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.geom.Line2D;

import javax.swing.*;

public class SplitImagePanel extends JPanel {
  private BufferedImage image;
  private BufferedImage trImage;
  private int splitX;
  
  public SplitImagePanel(String path) {
    setImage(path);
    init();
  }
  
  public SplitImagePanel(BufferedImage image) {
    setImage(image);
    init();
  }

  public void setImage(String path) {
    Image im = (new ImageIcon(path)).getImage();
		image = new BufferedImage(
        im.getWidth(null), im.getHeight(null),
        BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    g2.drawImage(im, null, null);
  }

  public void setImage(BufferedImage image) { this.image = image; }

  public void setSecondImage(BufferedImage image) {
    trImage = image;
    repaint();
  }
  
  public BufferedImage getImage() { return image; }
  public BufferedImage getTrImage() { return trImage; }
  
  private void init() {
    setBackground(Color.white);
    addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent me) {
        splitX = me.getX();
        repaint();
      }
    });
    addMouseMotionListener(new MouseMotionAdapter() {
      public void mouseDragged(MouseEvent me) {
        splitX = me.getX();
        repaint();
      }
    });
  }
  
  public void paintComponent(Graphics g) {
		super.paintComponent(g);
    Graphics2D g2 = (Graphics2D)g;
    int width = getPreferredSize().width;
    int height = getPreferredSize().height;
    
		g2.clearRect(0, 0, width, height);
    g2.setClip(splitX, 0, width - splitX, height);
    
    g2.drawImage(getImage(), 0, 0, null);
    
    if (splitX == 0 || trImage == null) return;
    
    g2.setClip(0, 0, splitX, height);
    g2.drawImage(trImage, 0, 0, null);
    
    Line2D splitLine = new Line2D.Float(splitX, 0, splitX, height);
    g2.setClip(null);
    g2.setColor(Color.white);
    g2.draw(splitLine);
  }

  public Dimension getPreferredSize() {
    int width = getImage().getWidth();
    int height = getImage().getHeight();
    if (trImage != null) {
      width = Math.max(width, trImage.getWidth());
      height = Math.max(height, trImage.getHeight());
    }
    return new Dimension(width, height);
  }
}
