package com.tutego.insel.ui.image;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;

class ImageComponent extends JComponent
{
  private static final long serialVersionUID = 8055865896136562197L;

  private BufferedImage image;

  public void setImage( File file )
  {
    try
    {
      if ( (image = ImageIO.read( file )) != null )
      {
        setPreferredSize( new Dimension(image.getWidth(), image.getHeight()) );
        repaint();
      }
    }
    catch ( IOException e ) { e.printStackTrace(); }
  }

  @Override
  protected void paintComponent( Graphics g )
  {
    if ( image != null )
      g.drawImage( image, 0, 0, this );
  }
}

class FileOpenAction implements ActionListener
{
  private final ImageComponent viewComponent;

  public FileOpenAction( ImageComponent viewComponent )
  {
    this.viewComponent = viewComponent;
  }

  public void actionPerformed( ActionEvent e )
  {
    JFileChooser d = new JFileChooser();
    d.setFileFilter( new FileFilter()
    {
      @Override
      public boolean accept( File f )
      {
        return f.isDirectory() || f.getName().toLowerCase().endsWith( ".jpg" )
            || f.getName().toLowerCase().endsWith( ".gif" );
      }
  
      @Override
      public String getDescription()
      {
        return "*.jpg;*.gif";
      }
    } );

    d.showOpenDialog( null );
    File file = d.getSelectedFile();

    if ( file != null )
      viewComponent.setImage( file );
  }
}

public class ImageViewer
{
  public static void main( String[] args )
  {
    JFrame f = new JFrame( "Bildbetrachter" );

    ImageComponent viewComponent = new ImageComponent();
    f.add( new JScrollPane(viewComponent) );

    JMenuBar mbar = new JMenuBar();
    JMenu menu = new JMenu( "Datei" );
    JMenuItem item = new JMenuItem( "Öffnen" );
    item.setAccelerator(
        KeyStroke.getKeyStroke( KeyEvent.VK_O, InputEvent.CTRL_MASK ) );
    item.addActionListener( new FileOpenAction(viewComponent) );
    menu.add( item );
    mbar.add( menu );
    f.setJMenuBar( mbar );

    f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    f.setSize( 600, 400 );
    f.setVisible(  true );
  }
}
