package com.tutego.insel.ui.swing;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.io.FileReader;
import java.io.IOException;

import javax.swing.*;

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

    final JTextArea textArea = new JTextArea();
    f.add( new JScrollPane(textArea) );

    f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    f.setSize( 300, 200 );

    JMenuBar menuBar = new JMenuBar();
    JMenu fileMenu = new JMenu( "Datei" );
    menuBar.add( fileMenu );
    JMenu helpMenu = new JMenu( "Hilfe" );
    menuBar.add( helpMenu );
    f.setJMenuBar( menuBar );

    helpMenu.add( new JMenuItem("Über das Programm") );

    final Icon smallIcon = new ImageIcon(
                                  JMenuDemo.class.getResource("/images/fileopen16x16.png") );
    final Icon largeIcon = new ImageIcon(
                                  JMenuDemo.class.getResource("/images/fileopen22x22.png") );

    Action openAction = new AbstractAction() {
      { putValue( Action.NAME, "Öffnen" );
        putValue( Action.DISPLAYED_MNEMONIC_INDEX_KEY, 1 );
        putValue( Action.SMALL_ICON, smallIcon );
        putValue( Action.LARGE_ICON_KEY, largeIcon ); }
      public void actionPerformed( ActionEvent e ) {
        
        JFileChooser fileChooser = new JFileChooser();
        if ( fileChooser.showOpenDialog( null ) == JFileChooser.APPROVE_OPTION )
        {
          try {
            textArea.read( new FileReader(fileChooser.getSelectedFile()), null );
          }
          catch ( IOException ex ) {
            textArea.setText( ex.getMessage() );
          }
        }
      }
    };

    fileMenu.add( openAction );
    fileMenu.addSeparator();

    Action exitAction = new AbstractAction() {
      { putValue( Action.NAME, "Beenden" );
        putValue( Action.DISPLAYED_MNEMONIC_INDEX_KEY, 0 ); }
      public void actionPerformed( ActionEvent e ) {
        System.exit( 0 );
      }
    };
    fileMenu.add( exitAction );

    JToolBar toolbar = new JToolBar();
    toolbar.add( openAction );

    f.add( toolbar, BorderLayout.PAGE_START );
    
    f.setVisible( true );
  }
}
