package pipe.gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Observable;
import java.util.Observer;

import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JToggleButton;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.border.BevelBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import pipe.dataLayer.DataLayer;
import pipe.gui.widgets.FileBrowser;


public class GuiFrame extends JFrame implements Constants, ActionListener, Observer{

	// HAK
	
	private String frameTitle;  //Frame title
	private DataLayer appModel;
	private GuiFrame appGui;
	private GuiView appView;
	private int mode, prev_mode;				// *** mode WAS STATIC ***
	private int newNameCounter=1;
	private JTabbedPane appTab;
	private StatusBar statusBar;
	private JMenuBar menuBar;
		
	private FileAction createAction, openAction, closeAction, saveAction,saveAsAction, exitAction, printAction, exportPNGAction, exportPSAction;
	private GridAction toggleGrid;	
	private DeleteAction deleteAction;
	private TypeAction annotationAction, arcAction, placeAction, transAction, timedtransAction, tokenAction, selectAction, deleteTokenAction;
	private AnimateAction startAction, stepforwardAction, stepbackwardAction, randomAction, randomAnimateAction;
	

	public GuiFrame(String title) {
		// HAK-arrange for frameTitle to be initialized and the default file name to be appended to basic window title
		frameTitle = title;
    	setTitle(null);
		
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception exc) {
			System.err.println("Error loading L&F: " + exc);
		}
    
    this.setIconImage(new ImageIcon(CreateGui.imgPath+"icon.png").getImage());
    		
    Dimension screenSize=Toolkit.getDefaultToolkit().getScreenSize();
    this.setSize(screenSize.width*80/100,screenSize.height*80/100);
    this.setLocationRelativeTo(null);
    
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		
		// Build menus
		menuBar=new JMenuBar();
		
		JMenu fileMenu = new JMenu("File");
		fileMenu.setMnemonic('F');
    
		addMenuItem(fileMenu, createAction = new FileAction("New",    "Create a new Petri net","ctrl N"));
		addMenuItem(fileMenu, openAction   = new FileAction("Open",   "Open","ctrl O"));
    addMenuItem(fileMenu, closeAction  = new FileAction("Close",  "Close the current tab","ctrl F4"));
		fileMenu.addSeparator();
		addMenuItem(fileMenu, saveAction   = new FileAction("Save",   "Save","ctrl S"));
		addMenuItem(fileMenu, saveAsAction = new FileAction("Save as","Save as...","F12"));
    // Export menu
    JMenu exportMenu=new JMenu("Export");
    exportMenu.setIcon(new ImageIcon(CreateGui.imgPath+"Export.png"));
    addMenuItem(exportMenu, exportPNGAction  = new FileAction("PNG",  "Export the net to PNG format",""));
    addMenuItem(exportMenu, exportPSAction  = new FileAction("PostScript",  "Export the net to PostScript format",""));
    fileMenu.add(exportMenu);
    fileMenu.addSeparator();
    addMenuItem(fileMenu, printAction  = new FileAction("Print",  "Print","ctrl P"));
    fileMenu.addSeparator();
    // Example files menu
    try {
      File[] nets=new File(CreateGui.appPath+"Example nets").listFiles();
      if(nets.length>0) {
        JMenu exampleMenu=new JMenu("Example nets");
        exampleMenu.setIcon(new ImageIcon(CreateGui.imgPath+"Example.png"));
        for (int i = 0; i < nets.length; i++)
          if(nets[i].getName().toLowerCase().endsWith(".xml"))
            addMenuItem(exampleMenu,new ExampleFileAction(nets[i]));
        fileMenu.add(exampleMenu);
        fileMenu.addSeparator();
      }
    } catch (Exception e) {
      System.err.println("Error getting example files:"+e);
    }
		addMenuItem(fileMenu, exitAction   = new FileAction("Exit",   "Close the program","alt F4"));
		
    JMenu viewMenu = new JMenu("View");
    viewMenu.setMnemonic('V');
    addMenuItem(viewMenu, toggleGrid = new GridAction("Cycle grid", "Change the grid size", "G"));

    JMenu drawMenu = new JMenu("Draw");
    drawMenu.setMnemonic('D');
    addMenuItem(drawMenu, placeAction       = new TypeAction("Place",               PLACE,     "Add a place","P",true));
    addMenuItem(drawMenu, transAction       = new TypeAction("Immediate transition",IMMTRANS,  "Add an immediate transition","I",true));
    addMenuItem(drawMenu, timedtransAction  = new TypeAction("Timed transition",    TIMEDTRANS,"Add a timed transition","T",true));
	addMenuItem(drawMenu, arcAction         = new TypeAction("Arc",                 ARC,       "Add an arc","A",true));
	addMenuItem(drawMenu, annotationAction  = new TypeAction("Annotation", ANNOTATION, "Add an annotation","N",true));		
	drawMenu.addSeparator();
	addMenuItem(drawMenu, tokenAction       = new TypeAction("Add token",           ADDTOKEN,  "Add a token","ADD",true));
	addMenuItem(drawMenu, deleteTokenAction = new TypeAction("Delete token",        DELTOKEN,  "Delete a token","SUBTRACT",true));
	drawMenu.addSeparator();
	addMenuItem(drawMenu, selectAction      = new TypeAction("Select",              SELECT,    "Select components","S",true));
    addMenuItem(drawMenu, deleteAction      = new DeleteAction("Delete", "Delete selection","DELETE"));
	JMenu animateMenu = new JMenu("Animate");
	animateMenu.setMnemonic('A');
	addMenuItem(animateMenu, startAction        = new AnimateAction("Animation mode",START,"Toggle Animation Mode",true));
	animateMenu.addSeparator();
	addMenuItem(animateMenu, stepbackwardAction = new AnimateAction("Back",   STEPBACKWARD,"Step backward a firing"));
	addMenuItem(animateMenu, stepforwardAction  = new AnimateAction("Forward",STEPFORWARD, "Step forward a firing"));
	addMenuItem(animateMenu, randomAction       = new AnimateAction("Random", RANDOM,      "Randomly fire a transition"));
    addMenuItem(animateMenu, randomAnimateAction= new AnimateAction("Animate",ANIMATE,     "Randomly fire a number of transitions",true));
			
		
		JMenu helpMenu = new JMenu("Help");
		helpMenu.setMnemonic('H');
    HelpBox helpAction=new HelpBox("Help","View documentation","F1","index.htm");
    addMenuItem(helpMenu,helpAction);    
		JMenuItem aboutItem = helpMenu.add("About PIPE");
		aboutItem.addActionListener(this); // Help - About is implemented differently
    aboutItem.setIcon(new ImageIcon(CreateGui.imgPath+"About.png"));
		
		menuBar.add(fileMenu);
		menuBar.add(viewMenu);
		menuBar.add(drawMenu);
		menuBar.add(animateMenu);
		menuBar.add(helpMenu);
		setJMenuBar(menuBar);
		
		// Status bar...
		statusBar = new StatusBar();
		getContentPane().add(statusBar, BorderLayout.PAGE_END);
		
		// Create the toolbar
		JToolBar toolBar=new JToolBar();
		toolBar.setFloatable(false);//Inhibit toolbar floating

    addButton(toolBar,createAction);
    addButton(toolBar,openAction);
    addButton(toolBar,saveAction);
    addButton(toolBar,saveAsAction);
		//toolBar.add(printAction);
    addButton(toolBar,closeAction);
    toolBar.addSeparator();
    addButton(toolBar,printAction);
    toolBar.addSeparator();
    addButton(toolBar,placeAction);//Add Draw Menu Buttons
    addButton(toolBar,transAction);
    addButton(toolBar,timedtransAction);
    addButton(toolBar,arcAction);
    addButton(toolBar,annotationAction);
    addButton(toolBar,tokenAction);
    addButton(toolBar,deleteTokenAction);
    addButton(toolBar,selectAction);
		toolBar.addSeparator();
    addButton(toolBar,toggleGrid);
		toolBar.addSeparator();
    addButton(toolBar,startAction);
    addButton(toolBar,stepbackwardAction);
    addButton(toolBar,stepforwardAction);
    addButton(toolBar,randomAction);
    addButton(toolBar,randomAnimateAction);
    toolBar.addSeparator();
    addButton(toolBar,helpAction);
		
		for(int i=0;i<toolBar.getComponentCount();i++)
			toolBar.getComponent(i).setFocusable(false);
		
    
		getContentPane().add(toolBar,BorderLayout.PAGE_START);
		enableActions(true);
		addWindowListener(new WindowHandler());

    // Set selection mode at startup 
    selectAction.actionPerformed(null);
	}
	
  private void addButton(JToolBar toolBar,GuiAction action) {
    if (action.getValue("selected")!=null) toolBar.add(new ToggleButton(action));
    else toolBar.add(action);
  }

  /**
   * A JToggleButton that watches an Action for selection change
   * @author Maxim
   * 
   * Selection must be stored in the action using putValue("selected",Boolean);
   */
  class ToggleButton extends JToggleButton implements PropertyChangeListener {
    public ToggleButton(Action a) {
      super(a);
      if(a.getValue(Action.SMALL_ICON)!=null) setText(null); // toggle buttons like to have images *and* text, nasty
      a.addPropertyChangeListener(this);
    }
    public void propertyChange(PropertyChangeEvent evt) {
      if(evt.getPropertyName()=="selected") {
        Boolean b=(Boolean)evt.getNewValue();
        if(b!=null) setSelected(b.booleanValue());
      }
    }
  }
 	
	private JMenuItem addMenuItem(JMenu menu, Action action){
		JMenuItem item = menu.add(action);
		KeyStroke keystroke = (KeyStroke)action.getValue(Action.ACCELERATOR_KEY);
		if(keystroke != null)
			item.setAccelerator(keystroke);
		return item;
	}
	
	/* sets all buttons to enabled or disabled according to status. */
	public void enableActions(boolean status){
//		createAction.setEnabled(status);
//		openAction.setEnabled(status);
//		closeAction.setEnabled(status);
		saveAction.setEnabled(status);
		saveAsAction.setEnabled(status);
//		printAction.setEnabled(status);
//    exportPNGAction.setEnabled(status);
//    exportPSAction.setEnabled(status);
//		exitAction.setEnabled(status);
		placeAction.setEnabled(status);
    arcAction.setEnabled(status);
    annotationAction.setEnabled(status);
    transAction.setEnabled(status);
    timedtransAction.setEnabled(status);
		tokenAction.setEnabled(status);
		deleteAction.setEnabled(status);
		selectAction.setEnabled(status);
		deleteTokenAction.setEnabled(status);

//    toggleGrid.setEnabled(status);
    
    if(status) {
      startAction.setSelected(false);
      randomAnimateAction.setSelected(false);
    }
		randomAction.setEnabled(!status);
    randomAnimateAction.setEnabled(!status);
		stepbackwardAction.setEnabled(!status);
		stepforwardAction.setEnabled(!status);
  }
	
	public  StatusBar getStatusBar(){
		return statusBar;
	}
		
	
	//HAK set current objects in Frame
	public void setObjects(){
		appModel = CreateGui.getModel();
		appView = CreateGui.getView();
	}
	
	//set frame objects by array place
	public void setObjects(int place){
		appModel = CreateGui.getModel(place);
		appView = CreateGui.getView(place);
	}
	
	public void setObjectsNull(int index){
    CreateGui.removeTab(index);
	}
	
	// set tabbed pane properties and add change listener that updates tab with linked model and view
	public void setTab(){
		appTab =CreateGui.getTab();
		appTab.addChangeListener(new ChangeListener(){
			public void stateChanged(ChangeEvent e){
				int index = appTab.getSelectedIndex();

				setObjects(index);
        
        if(appView!=null) {
  				appView.setVisible(true);
	  			appView.repaint();
				
  				enableActions(true); //renables all non-animation buttons
  				CreateGui.getAnimator().restoreModel();
  				CreateGui.removeAnimationHistory();
  				
  				setTitle(appTab.getTitleAt(index));
        } else {
          setTitle(null);
        }
			}
		});
		appGui = CreateGui.getApp();
	}
	
	// Less sucky yet far, far simpler to code About dialogue
	public void actionPerformed(ActionEvent e){
    JOptionPane.showMessageDialog(this,
        "Imperial College DoC MSc Group Project\n" +
        "Original version (c) 2003 by Jamie Bloom, Clare Clark, Camilla Clifford, Alex Duncan, Haroun Khan and Manos Papantoniou\n" +
        "MLS(tm) Edition (c) 2004 by Tom Barnwell, Michael Camacho, Matthew Cook, Maxim Gready, Peter Kyme and Michail Tsouchlaris\n" +
        "http://petri-net.sf.net",
        "About PIPE",
        JOptionPane.INFORMATION_MESSAGE);
	}
	
	// HAK Method called by netModel object when it changes
	public void update(Observable o, Object obj){
    if(mode!=CREATING && !CreateGui.getView().animationmode) appView.netChanged = true;
	}
	
	
  private void saveOperation(boolean forceSaveAs){
    if(appView==null) return;
    File modelFile=CreateGui.getFile();
    if(!forceSaveAs && modelFile!=null) { // ordinary save
      if(!appView.netChanged) return;
      saveNet(modelFile);
    } else {                              // save as
      String path=null;
      if(modelFile!=null) path=modelFile.toString();
      else path=appTab.getTitleAt(appTab.getSelectedIndex());
      String filename=new FileBrowser(path).saveFile();
      if (filename!=null) saveNet(new File(filename));
    }
  }
  
	private void saveNet(File outFile){
		try{
			appModel.savePNML(outFile);
      CreateGui.setFile(outFile,appTab.getSelectedIndex());
			appView.netChanged = false;
			appTab.setTitleAt(appTab.getSelectedIndex(),outFile.getName());
      setTitle(outFile.getName());  // Change the window title
    } catch (Exception e) {
      System.err.println(e);
      JOptionPane.showMessageDialog(GuiFrame.this,
          e.toString(),
          "File Output Error",
          JOptionPane.ERROR_MESSAGE);
      return;
    }
	}
  /**
   * Creates a new tab with the selected file, or a new file if filename==null
   * @param filename Filename of net to load, or <b>null</b> to create a new, empty tab
   */ 
  public void createNewTab(String filename) {
    int freeSpace = CreateGui.getFreeSpace();
    String name="";
    setObjects(freeSpace);
    appModel.addObserver((Observer)appView); // Add the view as Observer
    appModel.addObserver((Observer)appGui);  // Add the app window as observer
    
    if(filename==null) {
      name = "New Petri net "+newNameCounter++ +".xml";
    } else 
      try {
        File inFile=new File(filename);
        appModel.loadPNML(inFile.getPath());
        CreateGui.setFile(inFile,freeSpace);
        name=inFile.getName();
      } catch(Exception e) {
        JOptionPane.showMessageDialog(GuiFrame.this,"Error loading file:\n"+filename+"\nGuru meditation:\n"+e.toString(),"File load error",
          JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        return;
      }
    appView.repaint();
    appView.netChanged = false;   // Status is unchanged
    
    JScrollPane scroller=new JScrollPane(appView);
    appView.updatePreferredSize();
    scroller.setBorder(new BevelBorder(BevelBorder.LOWERED)); // make it less bad on XP
    appTab.addTab(name,null,scroller,null);
    appTab.setSelectedIndex(freeSpace);
    
    setTitle(name);// Change the program caption
  }
 
	/**
   * If current net has modifications, asks if you want to save and does it if you want.
	 * @return true if handled, false if cancelled 
	 */
	public boolean checkForSave() {
		if(appView.netChanged) {
			int result=JOptionPane.showConfirmDialog(GuiFrame.this,"Current file has changed. Save current file?",
					"Confirm Save Current File",
					JOptionPane.YES_NO_CANCEL_OPTION,
					JOptionPane.WARNING_MESSAGE);
		switch(result) {
			case JOptionPane.YES_OPTION: saveOperation(false); break;
			case JOptionPane.CLOSED_OPTION:
			case JOptionPane.CANCEL_OPTION:
				return false;
		}
	}
	return true;
}

  //On application close,loop through all tabs and check if they have been saved
	public boolean checkForSaveAll(){
		for(int counter = 0;counter < appTab.getTabCount();counter++){
			appTab.setSelectedIndex(counter);
      if (checkForSave()==false) return false;
		}
		return true;
	}
	
  class GridAction extends GuiAction {
		GridAction (String name, String tooltip, String keystroke) {
			super(name, tooltip, keystroke);
		}
		
		public void actionPerformed(ActionEvent e) {
			Grid.increment();
			repaint();
		}
	}
 	
	class FileAction extends GuiAction {
		//constructor
		FileAction(String name, String tooltip, String keystroke) {
			super(name, tooltip, keystroke);
		}
		
		public void actionPerformed(ActionEvent e) {
			if(this==saveAction) saveOperation(false);            		 // code for Save operation
			else if(this==saveAsAction) saveOperation(true);           // code for Save As operations
			else if(this==openAction){                                 // code for Open operation
				File filePath=new FileBrowser(CreateGui.userPath).openFile();
				if ((filePath != null) && filePath.exists() && filePath.isFile() && filePath.canRead()) {
          CreateGui.userPath=filePath.getParent();
					createNewTab(filePath.toString());
				}
			}
			else if(this==createAction)createNewTab(null);              // Create a new tab
			else if((this==exitAction)&&checkForSaveAll()) {
				dispose();
				System.exit(0);
			}
			else if((this==closeAction)&&(appTab.getTabCount()>0)&&checkForSave()) {
				setObjectsNull(appTab.getSelectedIndex());
				appTab.remove(appTab.getSelectedIndex());
			}
      else if(this==exportPNGAction) Export.exportGuiView(appView,Export.PNG);
      else if(this==exportPSAction)  Export.exportGuiView(appView,Export.POSTSCRIPT);
      else if(this==printAction)     Export.exportGuiView(appView,Export.PRINTER);
		}
	}

  class ExampleFileAction extends GuiAction {
    private File file;
    ExampleFileAction(File file) {
      super(file.getName(), "Open example file \""+file.getName()+"\"", null);
      this.file=file;
      putValue(SMALL_ICON, new ImageIcon(CreateGui.imgPath+"Net.png"));
    }
    
    public void actionPerformed(ActionEvent e){
      createNewTab(file.getAbsolutePath());
    }
  }

  class DeleteAction extends GuiAction {
    DeleteAction(String name, String tooltip, String keystroke) {
      super(name, tooltip, keystroke);
    }
    
    public void actionPerformed(ActionEvent e){
      appView.getSelectionObject().deleteSelection();
    }
  }
 
	class TypeAction extends GuiAction {
    TypeAction(String name, int typeID, String tooltip,String keystroke){
      super(name, tooltip, keystroke);
      this.typeID = typeID;
    }
    TypeAction(String name, int typeID, String tooltip,String keystroke, boolean toggleable){
      super(name, tooltip, keystroke, toggleable);
      this.typeID = typeID;
    }
		public void actionPerformed(ActionEvent e){
      this.setSelected(true);
      // deselect other actions
      if(this!=placeAction) placeAction.setSelected(false);
      if(this!=transAction) transAction.setSelected(false);
      if(this!=timedtransAction) timedtransAction.setSelected(false);
      if(this!=  arcAction)   arcAction.setSelected(false);
      if(this!=tokenAction) tokenAction.setSelected(false);
      if(this!=deleteTokenAction) deleteTokenAction.setSelected(false);
      if(this!=selectAction) selectAction.setSelected(false);
      if(this!=annotationAction) annotationAction.setSelected(false);
      
		  if(appView==null) return;

			setMode(typeID);
			appView.getSelectionObject().disableSelection();
			
      statusBar.changeText(typeID);

      if((typeID!=ARC)&&(CreateGui.getView().createArc!=null)) {
        appView.createArc.delete();          
        appView.createArc=null;
        appView.repaint();
      }
     
      if(typeID==SELECT) {
				//disable drawing to eliminate possiblity of connecting arc to old coord of moved component
				statusBar.changeText(typeID);
				appView.getSelectionObject().enableSelection();
      }
		}
		
		private int typeID;
		private String imageFileName;
		private String selectedFileName;
	}
  
  
 
  class AnimateAction extends GuiAction {
    private int typeID;
    private AnimationHistory animBox ;

    AnimateAction(String name,int typeID,String tooltip){
      super(name,tooltip,null);
      this.typeID = typeID;
    }
    AnimateAction(String name,int typeID,String tooltip,boolean toggleable){
      super(name,tooltip,null,toggleable);
      this.typeID = typeID;
    }

    public void actionPerformed(ActionEvent e){
      if(appView==null) return;

      animBox = CreateGui.getAnimationHistory();

      switch(typeID){
      case START:
        if(CreateGui.getView().animationmode) restoreMode();
        else setMode(typeID);
        setAnimationMode(!CreateGui.getView().animationmode);
        break;

      case RANDOM:
        CreateGui.getAnimator().doRandomFiring();
        break;

      case STEPFORWARD:
        animBox.stepForward();
        CreateGui.getAnimator().stepForward();
        break;

      case STEPBACKWARD:
        animBox.stepBackwards();
        CreateGui.getAnimator().stepBack();
        break;
        
      case ANIMATE:
        Animator a=CreateGui.getAnimator();
        if(a.getNumberSequences()>0) {
          a.setNumberSequences(0); // stop animation
          setSelected(false);
        } else {
          stepbackwardAction.setEnabled(false);
          stepforwardAction.setEnabled(false);
          randomAction.setEnabled(false);
          setSelected(true);
          CreateGui.getAnimator().startRandomFiring();
        }
        break;

      default:
        return;
      }

    }
  }
  
  public void setRandomAnimationMode(boolean on) {
    stepbackwardAction.setEnabled(!on);
    stepforwardAction.setEnabled(!on);
    randomAction.setEnabled(!on);
    randomAnimateAction.setSelected(on);
  }

  private void setAnimationMode(boolean on) {
    randomAnimateAction.setSelected(false);
    CreateGui.getAnimator().setNumberSequences(0);
    startAction.setSelected(on);
    if (on) {
      statusBar.changeText(getStatusBar().textforAnimation);
      CreateGui.getView().changeAnimationMode(true);
      CreateGui.getAnimator().storeModel();
      CreateGui.currentPNMLData().setEnabledTransitions();
      CreateGui.getAnimator().highlightEnabledTransitions();
      CreateGui.addAnimationHistory();
      enableActions(false);//disables all non-animation buttons
    } else {
      statusBar.changeText(statusBar.textforDrawing);
      CreateGui.getView().changeAnimationMode(false);
      CreateGui.getAnimator().restoreModel();
      CreateGui.removeAnimationHistory();
      enableActions(true); //renables all non-animation buttons
    }
  }
  
		
	public void setMode(int _mode) {
		if (mode != _mode){				// Don't bother unless new mode is different.
			prev_mode = mode;
			mode = _mode;
		}
	}
		
	public int getMode() {
		return mode;
	}
	
	public void restoreMode() {
		mode = prev_mode;
	      placeAction.setSelected(mode == PLACE);
	      transAction.setSelected(mode == IMMTRANS);
	      timedtransAction.setSelected(mode == TIMEDTRANS);
	      arcAction.setSelected(mode == ARC);
	      tokenAction.setSelected(mode == ADDTOKEN);
	      deleteTokenAction.setSelected(mode == DELTOKEN);
	      selectAction.setSelected(mode == SELECT);
	      annotationAction.setSelected(mode == ANNOTATION);
	}
	
	public void disableGuiMenu() {
		menuBar.setEnabled(false);
		
	}
	
	public void enableGuiMenu() {
		menuBar.setEnabled(true);
	}
	
  public void setTitle(String title) {
    if(title==null) super.setTitle(frameTitle);
    else super.setTitle(frameTitle+": "+title);
  }
  
  public void initExit() {
    exitAction.actionPerformed(null);
  }
	
	class WindowHandler extends WindowAdapter{
		//Handler for window closing event
		public void windowClosing(WindowEvent e){
	    initExit();
		}
	}
	
}
