//Titel:            Testbeispuiel für MDI-Fenster
//Version:          1.0
//Copyright:        HS-Harz, FB AI
//Autor:            Dipl.-Inf. Dipl.-Ing. Michael Wlhelm
//Firma:
//Beschreibung:

// Beispiel eines MDI-Fenster
import java.io.Reader;
import java.io.FileReader;
import java.io.IOException;

// Fürs einlesen des Editors
import javax.swing.text.*;


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 MyDesktop11 extends JFrame {

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

    // Variablen für die Menüs
  private JMenuBar menuBar1;   // MenüContainer
  private JMenu MainFile;      // Hauptmenü
  private JMenuItem MnNew;     // Menüeintrag
  private JMenuItem MnOpen;    // Menüeintrag
  private JMenuItem MnClose;   // Menüeintrag

  private JMenu MainEdit;         // HauptMenü
  private JMenuItem MnCut;        // Menüeintrag
  private JMenuItem MnCopy;       // Menüeintrag
  private JMenuItem MnInsert;     // Menüeintrag




   // Konstruktor
  public MyDesktop11() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void jbInit() throws Exception {

      // BorderLayout setzen
    this.getContentPane().setLayout( new BorderLayout() );

      // Variable DesktopPane einfügen
      // in ihr werden alle Clientfenster eingefügt
    this.getContentPane().add(_desktopPane, BorderLayout.CENTER);
    this.setSize( 600, 400);

    setMenus();
  }



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

      // DATEI
    MainFile = new JMenu("Datei");
    MnNew = new JMenuItem("Neu");
    MnOpen = new JMenuItem("Öffnen");
    MnClose = new JMenuItem("Schließen");

      // Event definieren
    MnNew.addActionListener(new ActionListener()  {
      public void actionPerformed(ActionEvent e) {
        MnNew_Click();
      }
    });
      // Short Key definieren  STRG+N
    MnNew.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
    MainFile.add(MnNew);

      // Event definieren
    MnOpen.addActionListener(new ActionListener()  {
      public void actionPerformed(ActionEvent e) {
        MnOpen_Click();
      }
    });
      // 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();


    // --------------------------
      // Event definieren
    MnClose.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        MnClose_actionPerformed(e);
      }
    });
    MainFile.add(MnClose);

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



    // Menü EDIT
    MainEdit = new JMenu("Bearbeiten");
    MnCut = new JMenuItem("Ausschneiden");
    MnCopy = new JMenuItem("Kopieren");
    MnInsert = new JMenuItem("Einfügen");

      // Event definieren
    MnCut.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        MnCut_actionPerformed(e);
      }
    });
    MainEdit.add(MnCut);

    MnCopy.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        MnCopy_actionPerformed(e);
      }
    });
    MainEdit.add(MnCopy);
    // MainFile.addSeparator();

    // --------------------------
      // Event definieren
    MnInsert.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        MnInsert_actionPerformed(e);
      }
    });
    MainEdit.add(MnInsert);
    menuBar1.add(MainEdit);

    // ----------------

    this.setJMenuBar(menuBar1);
  } // setMenus


     // Event definieren, CODE
  void MnNew_Click() {
                  // LeerString muss übergeben werden
                  // Damit erkennt das Frame, es gibt noch keinen
                  // Dateinamen
    MyInternalFrame frame = new MyInternalFrame("");
    frame.setBounds(0, 0, 450, 300);
    _desktopPane.add(frame, new Integer(1));
      // Neu
    _desktopPane.moveToFront(frame);
  }




     // Event definieren, CODE
     // 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("D:\\hs-harz\\Vorlesungen\\WS\\INF 3\\java\\MDI\\") );
   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 );
        // Grenzen
      frame.setBounds(0, 0, 450, 300);
      _desktopPane.add(frame, new Integer(1));

      // Neu
      _desktopPane.moveToFront(frame);

    }
  }  // MnOpen



   // wird aufgerufen beim Schließen des Hauptfensters
  void MnClose_actionPerformed(ActionEvent e) {
    System.exit(0);
  }


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

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

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



    // zum korrekten Beenden benötigt
  protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if(e.getID() == WindowEvent.WINDOW_CLOSING) {
      System.exit(0);
    }
  }

   // Hauptprogramm
  static public void main(String[] args) {
    try  {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    }
    catch(Exception e) {
    }
    MyDesktop11 desktop = new MyDesktop11();
    desktop.setVisible(true);
  }
  
}

// Clientfenster
class MyInternalFrame extends JInternalFrame {
  private JMenuBar menuBar1;   // MenüContainer
  private JMenu MainFile;      // Hauptmenü
  private JMenuItem MnSave;    // Menüeintrag
  private JMenuItem MnSaveAs;    // Menüeintrag
  private JMenuItem MnClose;   // Menüeintrag

  String _sFileName="";

  private String _Caption;

  private JTextArea _edit = new JTextArea();


  public MyInternalFrame(String sFileName) {
    _sFileName = sFileName;
    if (sFileName==null)
      _Caption = "noname";
    else
      _Caption = sFileName;

    try {
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  public void jbInit() throws Exception {
    this.setClosable(true);
    this.setIconifiable(true);
    this.setMaximizable(true);
    this.setResizable(true);
    this.getContentPane().setLayout( new BorderLayout() );
    this.setTitle(_Caption);

    setGUI();
  }

  private void setGUI() {
    menuBar1 = new JMenuBar();
      // DATEI
    MainFile = new JMenu("Datei");

    MnSave = new JMenuItem("Speichern");
    MnSaveAs = new JMenuItem("Speichern Als");

      // Event definieren
    MnSave.addActionListener(new ActionListener()  {
      public void actionPerformed(ActionEvent e) {
        MnSave_Click();
      }
    });
      // Short Key definieren  STRG+O
    MnSave.setAccelerator( KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
     // Menüeinträge zum MainFile hinzufügen
    MainFile.add(MnSave);

      // Event definieren
    MnSaveAs.addActionListener(new ActionListener()  {
      public void actionPerformed(ActionEvent e) {
        MnSaveAs_Click();
      }
    });
     // Menüeinträge zum MainFile hinzufügen
    MainFile.add(MnSaveAs);
    MainFile.addSeparator();

    // --------------------------
      // Event definieren
    MnClose = new JMenuItem("Schließen");
    MnClose.addActionListener(new ActionListener()  {

      public void actionPerformed(ActionEvent e) {
        MnClose_Click();
      }
    });
    MainFile.add(MnClose);

    menuBar1.add(MainFile);
    this.setJMenuBar(menuBar1);

    JScrollPane scroll = new JScrollPane( _edit );
    this.getContentPane().add(scroll, BorderLayout.CENTER );
    readText();
  }

  void readText() {
    if (_sFileName.length()==0) {
      System.out.println("Dateiname leer");
      return;
    }
		char[] buff = new char[4096];
		int nch;
    Document doc;
    doc = _edit.getDocument();
    
    try {
        Reader in = new FileReader(_sFileName);
        while ((nch = in.read(buff, 0, buff.length)) != -1) {
            doc.insertString(doc.getLength(), new String(buff, 0, nch), null);
        }
    }
    catch (IOException e) {
		System.err.println(e.toString());
	    }
	    catch (BadLocationException e) {
		System.err.println(e.getMessage());
	    }

  }


  public void SaveToFile() {
    // speichert eine Datei
  }

   void  MnClose_Click() {
     try {
       this.setClosed(true);
     }
     catch (Exception e) {
       // e.printStackTrace();
     }
   }



  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.addChoosableFileFilter(dbsFilter);

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


}  // 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

