//Titel:            Testbeispiel für MDI-Fenster

// Beispiel eines MDI-Fenster

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// Packages für Opendialog
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.*;
import java.util.Hashtable;
import java.util.Enumeration;

// Packages für Filter
import javax.swing.filechooser.*;
import java.io.File;
import java.util.Hashtable;
import java.util.Enumeration;




public class MDI02 extends JFrame implements ActionListener {

  // Container für die Clientfenster
  private JDesktopPane desktopPane = new JDesktopPane();

    // Variablen für die Menüs
  private JMenuItem mnNew;     // Menüeintrag
  private JMenuItem mnOpen;    // Menüeintrag
  private JMenuItem mnSave;    // Menüeintrag
  private JMenuItem mnSaveAs;    // Menüeintrag
  private JMenuItem mnClose;   // Menüeintrag

  private JMenuItem mnCut;        // Menüeintrag
  private JMenuItem mnCopy;       // Menüeintrag
  private JMenuItem mnInsert;     // Menüeintrag

  private JMenuItem mnPrevWindows; 
  private JMenuItem mnNextWindows; 
  private JMenuItem mnTile;        
  private JMenuItem mnTileVertical;        
  private JMenuItem mnTileHorizontal;        
  private JMenuItem mnCascade; 


  String sFileName="";


   // Konstruktor
  public MDI02() {
    this.setSize( 600, 400);
    setTitle( "MDI: 2. Beispiel");
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setGUI();
  }

  public void setGUI() {
      // BorderLayout setzen
    this.getContentPane().setLayout( new BorderLayout() );

      // Variable DesktopPane einfügen
      // in ihr werden alle Clientfenster eingefügt
    JScrollPane sc = new JScrollPane (desktopPane);
    this.getContentPane().add(sc, BorderLayout.CENTER);
    setMenus();
  }



    // setzt die Menüs
  private void setMenus() {
    JMenuBar menuBar1 = new JMenuBar();   // MenüContainer

    JMenu mainFile = new JMenu("Datei");
    mnNew = new JMenuItem("Neu");
    mnOpen = new JMenuItem("Öffnen");
    mnSave = new JMenuItem("Speichern");
    mnSaveAs = new JMenuItem("Speichern Als");
    mnClose = new JMenuItem("Schließen");

    mnNew.addActionListener(this);
    mnOpen.addActionListener(this);
    mnSave.addActionListener(this);
    mnSaveAs.addActionListener(this);
    mnClose.addActionListener(this);

      // Short Key definieren  STRG+N
    mnNew.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
    mainFile.add(mnNew);

      // Short Key definieren  STRG+O
    mnOpen.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
     // Menüeinträge zum mainFile hinzufügen
    mainFile.add(mnOpen);

    mainFile.addSeparator();

      // Short Key definieren  STRG+O
    mnSave.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
    mainFile.add(mnSave);
    mainFile.add(mnSaveAs);
    mainFile.addSeparator();
    mainFile.add(mnClose);

      // Hauptmenü FILE in den MenüBar einfügen
    menuBar1.add(mainFile);


    JMenu mainEdit = new JMenu("Bearbeiten");
    mnCut = new JMenuItem("Ausschneiden");
    mnCopy = new JMenuItem("Kopieren");
    mnInsert = new JMenuItem("Einfügen");

    mnCut.addActionListener(this);
    mnCopy.addActionListener(this);
    mnInsert.addActionListener(this);

    mainEdit.add(mnCut);
    mainEdit.add(mnCopy);
    mainEdit.add(mnInsert);
    menuBar1.add(mainEdit);


    // ----------------
    // Menü Windows
    JMenu mainWindows = new JMenu("Fenster");
    mnPrevWindows = new JMenuItem("Vorheriges Fenster");
    mnNextWindows = new JMenuItem("Nächstes Fenster");
    mnCascade = new JMenuItem("Kaskade");
    mnCascade.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F6, 0));

    mnTile = new JMenuItem("Aufteilen");
    mnTile.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F7, 0));
    mnTileVertical = new JMenuItem("Aufteilen Vertikal");
    mnTileVertical.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F8, 0));

    mnTileHorizontal = new JMenuItem("Aufteilen Horizontal");
    mnTileHorizontal.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_F9, 0));

      // MenüEinträge definieren
    mainWindows.add(mnPrevWindows);
    mainWindows.add(mnNextWindows);
    mainWindows.addSeparator();
    mainWindows.add(mnCascade);
    mainWindows.add(mnTile);
    mainWindows.add(mnTileVertical);
    mainWindows.add(mnTileHorizontal);
    menuBar1.add(mainWindows);

      // Event definieren
    mnPrevWindows.addActionListener(this);
    mnNextWindows.addActionListener(this);
    mnCascade.addActionListener(this);
    mnTile.addActionListener(this);
    mnTileVertical.addActionListener(this);
    mnTileHorizontal.addActionListener(this);


    menuBar1.add(mainWindows);

    this.setJMenuBar(menuBar1);

    for (int i = 0; i < menuBar1.getComponentCount(); i++) {
      JMenu main = (JMenu) menuBar1.getComponent(i);
      main.setFont(new Font("Arial", Font.BOLD, 18));
      for (int j = 0; j < main.getItemCount(); j++) {
        Component c = main.getItem(j);
        if (c instanceof JMenuItem) {
          JMenuItem mn = (JMenuItem) c;
          mn.setFont(new Font("Arial", Font.BOLD, 18));
        }
      }
    }
  } // setMenus


  public void actionPerformed(ActionEvent e) {
       if (e.getSource() == mnNew ) {
           mnNew_click();
        }
       if (e.getSource() == mnOpen ) {
          mnOpen_click();
       }

       if (e.getSource() == mnSave ) {
          mnSave_click();
       }
       if (e.getSource() == mnSaveAs ) {
          mnSaveAs_click();
       }
       if (e.getSource() == mnClose ) {
          System.exit(0);
       }

       if (e.getSource() == mnCut ) {
          mnCut_click();
       }
       if (e.getSource() == mnCopy ) {
          mnCopy_click();
       }
       if (e.getSource() == mnInsert ) {
          mnInsert_click();
       }

       if (e.getSource() == mnPrevWindows ) {
          WindowLayout.mnPrevWindows(desktopPane);
       }
       if (e.getSource() == mnNextWindows ) {
         WindowLayout.mnNextWindows(desktopPane);
       }


      if (e.getSource() == mnCascade) {
         WindowLayout.mnCascade(desktopPane);
      }
      if (e.getSource() == mnTile) {
          WindowLayout.mnTile(desktopPane);
      }
      if (e.getSource() == mnTileVertical) {
         WindowLayout.mnTileHorizontal(desktopPane);
      }
      if (e.getSource() == mnTileHorizontal) {
         WindowLayout.mnTileVertical(desktopPane);    
      }



   }



     // Event definieren, CODE
  void mnNew_click() {
    MyInternalFrame frame = new MyInternalFrame(null, desktopPane.getAllFrames().length+1);
    int pos = desktopPane.getAllFrames().length+1;
    frame.setBounds(pos*10, pos*10, 450, 300);
    desktopPane.add(frame);
    desktopPane.moveToFront(frame);
  }




     // Beispiel zum Öffnen EINER Datei
  void mnOpen_click() {
   JFileChooser jFileChooser1 = new JFileChooser();
   String sFileName;

     // Filter definieren
   MyFileFilter javaFilter, txtFilter;

       // Eine Maske
	javaFilter = new MyFileFilter(
              "java", "Java-Texte");
       // Zwei Masken
     txtFilter = new MyFileFilter( new String[] {"dat", "txt"}, "Texte");

     // setzen der Optionen
   jFileChooser1.setMultiSelectionEnabled(false);
   jFileChooser1.setCurrentDirectory( 
    new File(  (String) System.getProperties().get("user.dir")  )   );
   jFileChooser1.addChoosableFileFilter(
          javaFilter);
   jFileChooser1.addChoosableFileFilter(
          txtFilter);

      // Aufruf des Dialogfensters
    if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) {
        // holen des Dateinamens
      sFileName = jFileChooser1.getSelectedFile().getPath();
        // Erzeugen des Clientframes
      MyInternalFrame frame = new MyInternalFrame( sFileName, desktopPane.getAllFrames().length+1 );
        // Grenzen
      int pos = desktopPane.getAllFrames().length+1;
      frame.setBounds(pos*10, pos*10, 450, 300);
      desktopPane.add(frame);

      desktopPane.moveToFront(frame);

    }
  }  // mnOpen


     // Beispiel zum Öffnen MEHRERE Datei
  void mnOpen2_click() {
   JFileChooser jFileChooser1;
   String sFileName;
   File [] files;  // Array für

   jFileChooser1 = new JFileChooser();
   jFileChooser1.setMultiSelectionEnabled(true);

   jFileChooser1.setCurrentDirectory(  new File(  (String) System.getProperties().get("user.dir")  )   );

     // Okay gedrückt ?
    if (JFileChooser.APPROVE_OPTION == jFileChooser1.showOpenDialog(this)) {
      files = jFileChooser1.getSelectedFiles();

      int k;
      k = files.length;
      for (int i=0; i<files.length; i++) {
        sFileName = files[i].getPath();
        MyInternalFrame frame = new MyInternalFrame( sFileName, desktopPane.getAllFrames().length+1 );
        int pos = desktopPane.getAllFrames().length+1;
        frame.setBounds(pos*10, pos*10, 450, 300);
        desktopPane.add(frame);
        desktopPane.moveToFront(frame);
      }
    }
  }  // mnOpen

  void mnSave_click() {
    if (sFileName.length()==0)
      mnSaveAs_click();
    else
      SaveToFile();
  }

  void mnSaveAs_click() {
   JFileChooser jFileChooser1 = new JFileChooser();
   String sFileName;

   MyFileFilter dbsFilter;

   dbsFilter = new MyFileFilter( new String[] {"std"}, "Studenten-Datenbank");

   jFileChooser1.setCurrentDirectory(  new File(  (String) System.getProperties().get("user.dir")  )   );
   jFileChooser1.addChoosableFileFilter(dbsFilter);

	// Ok-Schalter gedrückt ?
    if (JFileChooser.APPROVE_OPTION == jFileChooser1.showSaveDialog(this)) {
      sFileName = jFileChooser1.getSelectedFile().getPath();
      SaveToFile();
    }
  }

  public void SaveToFile() {
    // suche aktive Fenster
    // speichert eine Datei
   MyInternalFrame frame;
   JInternalFrame[] ff;  // Array of all internal Clientwindow
   ff = desktopPane.getAllFrames();
   if (ff.length>0) {
     frame = (MyInternalFrame) ff[0];
     System.out.println( frame.getTitle() );
   }
  }  // SaveToFile



   // -----------------
     // Event definieren, CODE
     // Hier sollte das aktuelle Clientfensters aufgerufen werden
  void mnCut_click() {
    System.out.println("Menüeintrag Cut");
  }

     // Event definieren, CODE
     // Hier sollte das aktuelle Clientfensters aufgerufen werden
  void mnCopy_click() {
    System.out.println("Menüeintrag Copy");
  }

     // Event definieren, CODE
     // Hier sollte das aktuelle Clientfensters aufgerufen werden
  void mnInsert_click() {
    System.out.println("Menüeintrag Insert");
  }



   // Hauptprogramm
  static public void main(String[] args) {
    MDI02 frame = new MDI02();
    frame.setVisible(true);
  }
  
}





// Clientfenster
class MyInternalFrame extends JInternalFrame {
  private String _sFileName;
  private String _Caption;
  private int _nr;


  public MyInternalFrame(String sFileName, int nr) {
    _sFileName = sFileName;
    if (sFileName==null)
      _Caption = "noname";
    else
      _Caption = sFileName;
    _nr = nr;
    setGUI();
    setVisible(true);
  }

  public void setGUI() {
    this.setClosable(true);
    this.setIconifiable(true);
    this.setMaximizable(true);
    this.setResizable(true);
    this.getContentPane().setLayout( new BorderLayout() );
    this.setTitle(_nr+": "+_Caption);
  }

}  // MyInternalFrame




// Klasse für die Filter eines FileChoosers
// muss nicht geändert werden
class MyFileFilter extends FileFilter {

    private static String TYPE_UNKNOWN = "Type Unknown";
    private static String HIDDEN_FILE = "Hidden File";

    private Hashtable filters = null;
    private String description = null;
    private String fullDescription = null;
    private boolean useExtensionsInDescription = true;

    /**
     * Creates a file filter. If no filters are added, then all
     * files are accepted.
     *
     * @see #addExtension
     */
    public MyFileFilter() {
     	this((String) null, (String) null);
    }

    /**
     * Creates a file filter that accepts files with the given extension.
     * Example: new ExampleFileFilter("jpg");
     *
     * @see #addExtension
     */
    public MyFileFilter(String extension) {
     	this(extension,null);
    }

    /**
     * Creates a file filter that accepts the given file type.
     * Example: new ExampleFileFilter("jpg", "JPEG Image Images");
     *
     * Note that the "." before the extension is not needed. If
     * provided, it will be ignored.
     *
     * @see #addExtension
     */
    public MyFileFilter(String extension, String description) {
     	this(new String[] {extension}, description);
    }

    /**
     * Creates a file filter from the given string array.
     * Example: new ExampleFileFilter(String {"gif", "jpg"});
     *
     * Note that the "." before the extension is not needed adn
     * will be ignored.
     *
     * @see #addExtension
     */
    public MyFileFilter(String[] filters) {
     	this(filters, null);
    }

    /**
     * Creates a file filter from the given string array and description.
     * Example: new ExampleFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
     *
     * Note that the "." before the extension is not needed and will be ignored.
     *
     * @see #addExtension
     */
    public MyFileFilter(String[] filters, String description) {
      this.filters = new Hashtable(filters.length);
      for (int i = 0; i < filters.length; i++) {
          // add filters one by one
          addExtension(filters[i]);
      }
      setDescription(description);
    }

    /**
     * Return true if this file should be shown in the directory pane,
     * false if it shouldn't.
     *
     * Files that begin with "." are ignored.
     *
     * @see #getExtension
     * @see FileFilter#accepts
     */
    public boolean accept(File f) {
      if(f != null) {
          if(f.isDirectory()) {
        return true;
          }
          String extension = getExtension(f);
          if(extension != null &&
          filters.get(getExtension(f))
                  != null) {
        return true;
          };
      }
      return false;
    }

    /**
     * Return the extension portion of the file's name .
     *
     * @see #getExtension
     * @see FileFilter#accept
     */
     public String getExtension(File f) {
        if(f != null) {
            String filename = f.getName();
            int i = filename.lastIndexOf('.');
            if(i>0 && i<filename.length()-1) {
          return filename.substring(i+1).toLowerCase();
            };
        }
        return null;
    }

    /**
     * Adds a filetype "dot" extension to filter against.
     *
     * For example: the following code will create a filter that filters
     * out all files except those that end in ".jpg" and ".tif":
     *
     *   ExampleFileFilter filter = new ExampleFileFilter();
     *   filter.addExtension("jpg");
     *   filter.addExtension("tif");
     *
     * Note that the "." before the extension is not needed and will be ignored.
     */
    public void addExtension(String extension) {
      if(filters == null) {
          filters = new Hashtable(5);
      }
      filters.put(extension.toLowerCase(), this);
      fullDescription = null;
    }


    /**
     * Returns the human readable description of this filter. For
     * example: "JPEG and GIF Image Files (*.jpg, *.gif)"
     *
     * @see setDescription
     * @see setExtensionListInDescription
     * @see isExtensionListInDescription
     * @see FileFilter#getDescription
     */
    public String getDescription() {
      if(fullDescription == null) {
          if(description == null || isExtensionListInDescription()) {
        if(description != null) {
            fullDescription = description;
        }
        fullDescription += " (";
        // build the description from the extension list
        Enumeration extensions = filters.keys();
        if(extensions != null) {
            fullDescription += "." + (String) extensions.nextElement();
            while (extensions.hasMoreElements()) {
          fullDescription += ", " + (String) extensions.nextElement();
            }
        }
        fullDescription += ")";
          } else {
        fullDescription = description;
          }
      }
      return fullDescription;
    }

    /**
     * Sets the human readable description of this filter. For
     * example: filter.setDescription("Gif and JPG Images");
     *
     * @see setDescription
     * @see setExtensionListInDescription
     * @see isExtensionListInDescription
     */
    public void setDescription(String description) {
   	  this.description = description;
    	fullDescription = null;
    }

    /**
     * Determines whether the extension list (.jpg, .gif, etc) should
     * show up in the human readable description.
     *
     * Only relevent if a description was provided in the constructor
     * or using setDescription();
     *
     * @see getDescription
     * @see setDescription
     * @see isExtensionListInDescription
     */
    public void setExtensionListInDescription(boolean b) {
      useExtensionsInDescription = b;
      fullDescription = null;
    }

    /**
     * Returns whether the extension list (.jpg, .gif, etc) should
     * show up in the human readable description.
     *
     * Only relevent if a description was provided in the constructor
     * or using setDescription();
     *
     * @see getDescription
     * @see setDescription
     * @see setExtensionListInDescription
     */
    public boolean isExtensionListInDescription() {
     	return useExtensionsInDescription;
    }
}  // MyFilter

