18 Commits 2d1a04fd09 ... 6bb8d6f273

Author SHA1 Message Date
  I. Dix 6bb8d6f273 #76: added table update after (table-update and sim-run) 6 years ago
  I. Dix ce080c7f1d #76: trigger table update after SimMan-run (one case missing, see TODO) and vice versa 6 years ago
  I. Dix f108f947fa refactoring, resolving warnings 7 years ago
  I. Dix 78ab278797 #76: fixed bugs, added support for flexible producers 7 years ago
  I. Dix 5476ea84f0 #76: fixed bugs, added support for multiple elements, refactored methods of HolonElement to clarify code 7 years ago
  I. Dix cf3d796533 #76: addded usage of flexible devices, global option whether flexibility should be done, updating the HolonElement-table after a change (Caution: the last only for single selection) 7 years ago
  I. Dix ae9ede5e61 #76: changed behaviour of element-table for single selection, meaning of totalEnergy and behaviour when switching flexibility 7 years ago
  I. Dix 0b7bfeb528 #76: changed functionality of flexibility in HolonElements 7 years ago
  I. Dix c8393d0839 #76: added stub method for turning on flexible devices, added functionality for HolonElements that turns off active-status if flexibility-status is turned on 7 years ago
  I. Dix 8b0b2e417f #76: added wasted energy to statistics panel 7 years ago
  I. Dix 84dff9a37b #76: fixed bug for computation of wasted energy 7 years ago
  I. Dix 388ed38881 Code Refactoring 7 years ago
  I. Dix 20dc6dd275 #76: introducing concept of over-supplied holon objects (+visualization by color) 7 years ago
  I. Dix e3e6d21dde fixes #80 (net get recalculated, if a producer is removed) 7 years ago
  I. Dix 945f18a702 more code cleaning in SimulationManager and HolonObject 7 years ago
  I. Dix 3f9b19ad50 more code cleaning 7 years ago
  I. Dix 1aa2e534b9 some more code cleaning 7 years ago
  I. Dix dc395a682c some code cleaning concerning mainly MyCanvas and UpperNodeCanvas 7 years ago
34 changed files with 6216 additions and 6797 deletions
  1. 29 31
      src/classes/AbstractCpsObject.java
  2. 247 257
      src/classes/CpsEdge.java
  3. 116 91
      src/classes/HolonElement.java
  4. 103 33
      src/classes/HolonObject.java
  5. 45 0
      src/classes/SubNet.java
  6. 3 2
      src/classes/TrackedDataSet.java
  7. 5 4
      src/exampleAlgorithms/RepairAllEdges.java
  8. 5 7
      src/interfaces/GraphListener.java
  9. 25 25
      src/tests/PraktikumHolonsTestClasses.java
  10. 428 474
      src/ui/controller/ClipboardController.java
  11. 5 26
      src/ui/controller/Control.java
  12. 18 25
      src/ui/controller/HolonCanvasController.java
  13. 502 578
      src/ui/controller/LoadController.java
  14. 30 92
      src/ui/controller/NodeController.java
  15. 44 122
      src/ui/controller/SaveController.java
  16. 647 591
      src/ui/controller/SimulationManager.java
  17. 14 22
      src/ui/controller/UpdateController.java
  18. 941 997
      src/ui/model/Model.java
  19. 372 0
      src/ui/view/AbstractCanvas.java
  20. 51 73
      src/ui/view/AddElementPopUp.java
  21. 88 124
      src/ui/view/AddObjectPopUp.java
  22. 9 21
      src/ui/view/DisplayedInformationPopUp.java
  23. 9 19
      src/ui/view/EditEdgesPopUp.java
  24. 146 113
      src/ui/view/GUI.java
  25. 41 81
      src/ui/view/HolonCanvas.java
  26. 15 20
      src/ui/view/Main.java
  27. 89 365
      src/ui/view/MyCanvas.java
  28. 104 59
      src/ui/view/StatisticGraph.java
  29. 28 34
      src/ui/view/StatisticGraphPanel.java
  30. 37 35
      src/ui/view/StatisticPanel.java
  31. 11 22
      src/ui/view/StatisticsTab.java
  32. 21 46
      src/ui/view/TimePanel.java
  33. 796 827
      src/ui/view/UnitGraph.java
  34. 1192 1581
      src/ui/view/UpperNodeCanvas.java

+ 29 - 31
src/classes/AbstractCpsObject.java

@@ -1,10 +1,10 @@
 package classes;
 
-import java.awt.Color;
-import java.util.ArrayList;
-
 import com.google.gson.annotations.Expose;
 
+import java.awt.*;
+import java.util.ArrayList;
+
 /**
  * The abstract class "CpsObject" represents any possible object in the system
  * (except Edges). The representation of any object contains following
@@ -55,8 +55,8 @@ public abstract class AbstractCpsObject {
 		setObjName(objName);
 		setName(objName);
 		setImage("/Images/Dummy_House.png");
-		tags = new ArrayList<Integer>();
-		pseudoTags = new ArrayList<Integer>();
+		tags = new ArrayList<>();
+		pseudoTags = new ArrayList<>();
 	}
 
 	/**
@@ -70,7 +70,7 @@ public abstract class AbstractCpsObject {
 	public AbstractCpsObject(AbstractCpsObject obj) {
 		setObjName(obj.getObjName());
 		setName(obj.getObjName());
-		setConnections(new ArrayList<CpsEdge>());
+		setConnections(new ArrayList<>());
 		setPosition(new Position());
 		setId(IdCounter.nextId());
 		setImage(obj.getImage());
@@ -192,17 +192,7 @@ public abstract class AbstractCpsObject {
 
 	/**
 	 * Set the position of the Object in the canvas.
-	 * 
-	 * @param pos
-	 *            Coordinates
-	 */
-	public void setPosition(Position pos) {
-		this.position = pos;
-	}
-
-	/**
-	 * Set the position of the Object in the canvas.
-	 * 
+	 *
 	 * @param x
 	 *            X-Coord
 	 * @param y
@@ -214,13 +204,22 @@ public abstract class AbstractCpsObject {
 
 	/**
 	 * Get the actual position of the Object.
-	 * 
+	 *
 	 * @return Position Position of this Object
 	 */
 	public Position getPosition() {
 		return position;
 	}
 
+	/**
+	 * Set the position of the Object in the canvas.
+	 *
+	 * @param pos Coordinates
+	 */
+	public void setPosition(Position pos) {
+		this.position = pos;
+	}
+
 	/**
 	 * For save purpose.
 	 * 
@@ -290,8 +289,8 @@ public abstract class AbstractCpsObject {
 	 * Rest the tags to Null.
 	 */
 	public void resetTags() {
-		this.tags = new ArrayList<Integer>();
-		this.pseudoTags = new ArrayList<Integer>();
+		this.tags = new ArrayList<>();
+		this.pseudoTags = new ArrayList<>();
 	}
 
 	/**
@@ -304,25 +303,24 @@ public abstract class AbstractCpsObject {
 		this.tags = tags;
 	}
 
-	/**
-	 * For internal purpose (energy flow).
-	 * 
-	 * @param tags
-	 *            for internal purpose
-	 */
-	public void setPseudoTags(ArrayList<Integer> tags) {
-		this.pseudoTags = tags;
-	}
-
 	/**
 	 * Get the pseudo tags.
-	 * 
+	 *
 	 * @return ArrayList
 	 */
 	public ArrayList<Integer> getPseudoTags() {
 		return this.pseudoTags;
 	}
 
+	/**
+	 * For internal purpose (energy flow).
+	 *
+	 * @param tags for internal purpose
+	 */
+	public void setPseudoTags(ArrayList<Integer> tags) {
+		this.pseudoTags = tags;
+	}
+
 	/**
 	 * add a pseudo tag.
 	 * 

+ 247 - 257
src/classes/CpsEdge.java

@@ -1,288 +1,278 @@
 package classes;
 
-import java.util.ArrayList;
-
 import com.google.gson.annotations.Expose;
 
+import java.util.ArrayList;
+
 /**
  * The class "CpsEdge" represents the connections on the GUI. Each connection
  * contains a max. capacity, a flow, a status (isWorking), tags (for internal
  * use of electricity flow), source and destination
- * 
- * @author Gruppe14
  *
+ * @author Gruppe14
  */
 public class CpsEdge {
 
-	// Max. capacity of the Edge, if flow is greater than the status --> is
-	// Working would be false
-	@Expose
-	float maxCapacity;
-	// Current flow of electricity (through the edge)
-	@Expose
-	float flow;
-	/*
-	 * Represents the actual status of the Edge (true = flows electricity; false
-	 * = no flow of electricity) State represents the real status of the edge If
-	 * it breaks --> stay ruin no matter the actual scenario The only way to
-	 * repair it is through manual change (setStateEdge)
-	 */
-	@Expose
-	boolean isWorking;
-	
-	/*
-	 * 0 = not connected to an upper node
-	 * 1 = connected to an uppder node & connected inside
-	 * 2 = connected to an upper node but not inside 
-	 * Is false when not
-	 */
-	@Expose
-	int isConnected;
-	// for internal use --> flow of electricity (simulation state)
-	
-	ArrayList<Integer> tags;
-	// for internal use --> flow of electricity (simulation state)
-	ArrayList<Integer> pseudoTags;
-	// Source
-	AbstractCpsObject a;
-	// Destination
-	AbstractCpsObject b;
+    public static final int CON_UPPER_NODE = 0;
+    public static final int CON_UPPER_NODE_AND_INSIDE = 1;
+    public static final int CON_UPPER_NODE_NOT_INSIDE = 2;
+
+    public static final float CAPACITY_INFINITE = -1;
+    public static final float CAPACITY_TO_UPPER_NODE = -2;
+    // Max. capacity of the Edge, if flow is greater than the status --> is
+    // Working would be false
+    @Expose
+    float maxCapacity;
+    // for internal use --> flow of electricity (simulation state)
+    // Current flow of electricity (through the edge)
+    @Expose
+    float flow;
+    /*
+     * Represents the actual status of the Edge (true = flows electricity; false
+     * = no flow of electricity) State represents the real status of the edge If
+     * it breaks --> stay ruin no matter the actual scenario The only way to
+     * repair it is through manual change (setStateEdge)
+     */
+    @Expose
+    boolean isWorking;
+    /*
+     * 0 = not connected to an upper node
+     * 1 = connected to an uppder node & connected inside
+     * 2 = connected to an upper node but not inside
+     * Is false when not
+     */
+    @Expose
+    int isConnected;
+    ArrayList<Integer> tags;
+    // for internal use --> flow of electricity (simulation state)
+    ArrayList<Integer> pseudoTags;
+    // Source
+    AbstractCpsObject a;
+    // Destination
+    AbstractCpsObject b;
+
+    /**
+     * Constructor without max. capacity (by default as 100)
+     *
+     * @param a Source
+     * @param b Destination
+     */
+    public CpsEdge(AbstractCpsObject a, AbstractCpsObject b) {
+        setA(a);
+        setB(b);
+        this.a.addConnection(this);
+        this.b.addConnection(this);
+        this.maxCapacity = 100;
+        flow = 0;
+        isWorking = true;
+        pseudoTags = new ArrayList<>();
+    }
+
+    /**
+     * Constructor with a user-defined max. capacity
+     *
+     * @param a      Source
+     * @param b      Destination
+     * @param maxCap Maximum Capacity
+     */
+    public CpsEdge(AbstractCpsObject a, AbstractCpsObject b, float maxCap) {
+        setA(a);
+        setB(b);
+        this.a.addConnection(this);
+        this.b.addConnection(this);
+        this.maxCapacity = maxCap;
+        flow = 0;
+        isWorking = true;
+        isConnected = CON_UPPER_NODE;
+        pseudoTags = new ArrayList<>();
+    }
+
+    /**
+     * Getter for the max. capacity
+     *
+     * @return the capacity
+     */
+    public float getCapacity() {
+        return maxCapacity;
+    }
+
+    /**
+     * Setter for the max. capacity
+     *
+     * @param cap the Capacity to set
+     */
+    public void setCapacity(float cap) {
+        this.maxCapacity = cap;
+    }
+
+    /**
+     * Getter fot the current flow.
+     *
+     * @return the flow
+     */
+    public float getFlow() {
+        return flow;
+    }
+
+    /**
+     * Set the flow into a new one.
+     *
+     * @param flow the flow to set
+     */
+    public void setFlow(float flow) {
+        this.flow = flow;
+        /**
+         * if (flow <= maxCapacity || flow == -1) { isWorking = true; } else {
+         * isWorking = false; state = false;
+         **/
+    }
 
-	/**
-	 * Constructor without max. capacity (by default as 100)
-	 * 
-	 * @param a
-	 *            Source
-	 * @param b
-	 *            Destination
-	 */
-	public CpsEdge(AbstractCpsObject a, AbstractCpsObject b) {
-		setA(a);
-		setB(b);
-		this.a.addConnection(this);
-		this.b.addConnection(this);
-		this.maxCapacity = 100;
-		flow = 0;
-		isWorking = true;
-		pseudoTags = new ArrayList<Integer>();
-	}
+    /**
+     * Calculates the state of the edge (see description of isWorking).
+     */
+    public void calculateState() {
+        if (flow > maxCapacity
+                && maxCapacity != CAPACITY_INFINITE
+                && maxCapacity != CAPACITY_TO_UPPER_NODE) {
+            isWorking = false;
+            flow = 0;
+        }
+    }
 
-	/**
-	 * Constructor with a user-defined max. capacity
-	 * 
-	 * @param a
-	 *            Source
-	 * @param b
-	 *            Destination
-	 * @param maxCap
-	 *            Maximum Capacity
-	 */
-	public CpsEdge(AbstractCpsObject a, AbstractCpsObject b, float maxCap) {
-		setA(a);
-		setB(b);
-		this.a.addConnection(this);
-		this.b.addConnection(this);
-		this.maxCapacity = maxCap;
-		flow = 0;
-		isWorking = true;
-		isConnected = 0;
-		pseudoTags = new ArrayList<Integer>();
-	}
+    /**
+     * Getter for the Source.
+     *
+     * @return the a
+     */
+    public AbstractCpsObject getA() {
+        return a;
+    }
 
-	/**
-	 * Getter for the max. capacity
-	 * 
-	 * @return the capacity
-	 */
-	public float getCapacity() {
-		return maxCapacity;
-	}
+    /**
+     * Set the Source to a new one.
+     *
+     * @param a the a to set
+     */
+    public void setA(AbstractCpsObject a) {
+        this.a = a;
+    }
 
-	/**
-	 * Setter for the max. capacity
-	 * 
-	 * @param cap
-	 *            the Capacity to set
-	 */
-	public void setCapacity(float cap) {
-		this.maxCapacity = cap;
-	}
+    /**
+     * Getter for the destination.
+     *
+     * @return the b
+     */
+    public AbstractCpsObject getB() {
+        return b;
+    }
 
-	/**
-	 * Getter fot the current flow.
-	 * 
-	 * @return the flow
-	 */
-	public float getFlow() {
-		return flow;
-	}
+    /**
+     * Set the Destination to a new one.
+     *
+     * @param b the b to set
+     */
+    public void setB(AbstractCpsObject b) {
+        this.b = b;
+    }
 
-	/**
-	 * Set the flow into a new one.
-	 * 
-	 * @param flow
-	 *            the flow to set
-	 */
-	public void setFlow(float flow) {
-		this.flow = flow;
-		/**
-		 * if (flow <= maxCapacity || flow == -1) { isWorking = true; } else {
-		 * isWorking = false; state = false;
-		 **/
-	}
+    /**
+     * Getter for the status.
+     *
+     * @return the state
+     */
+    public boolean isWorking() {
+        return isWorking;
+    }
 
-	/**
-	 * Calculates the state of the edge (see description of isWorking).
-	 * 
-	 * @param simMode
-	 *            Simulation Mode
-	 */
+    /**
+     * Set the state manually to a new one.
+     *
+     * @param state the state
+     */
+    public void setWorkingState(boolean state) {
+        isWorking = state;
+    }
 
-	public void calculateState() {
-		if (flow > maxCapacity && maxCapacity != -1 && maxCapacity != -2) {
-			isWorking = false;
-			flow = 0;
-		}
-	}
+    /**
+     * Getter for the ArrayList of tags.
+     *
+     * @return tags tags for this edge
+     */
+    public ArrayList<Integer> getTags() {
+        return tags;
+    }
 
-	/**
-	 * Getter for the Source.
-	 * 
-	 * @return the a
-	 */
-	public AbstractCpsObject getA() {
-		return a;
-	}
+    /**
+     * set the tags into a new set of tags.
+     *
+     * @param tags tags for this edge
+     */
+    public void setTags(ArrayList<Integer> tags) {
+        this.tags = tags;
+    }
 
-	/**
-	 * Set the Source to a new one.
-	 * 
-	 * @param a
-	 *            the a to set
-	 */
-	public void setA(AbstractCpsObject a) {
-		this.a = a;
-	}
+    /**
+     * Add a new tag to the ArrayList.
+     *
+     * @param tag tag for the ArrayList
+     */
+    public void addTag(int tag) {
+        if (!tags.contains(tag)) {
+            tags.add(tag);
+        }
+    }
 
-	/**
-	 * Getter for the destination.
-	 * 
-	 * @return the b
-	 */
-	public AbstractCpsObject getB() {
-		return b;
-	}
+    /**
+     * checks whether list contains all given tags
+     *
+     * @param toCheck tags that are checked
+     * @param list    list to be checked
+     * @return true if all tags in toCheck are contained in list, false otherwise
+     */
+    public boolean containsTags(ArrayList<Integer> list, ArrayList<Integer> toCheck) {
+        if (toCheck.size() == 0) {
+            return true;
+        } else {
+            for (Integer i : toCheck) {
+                if (!(list.contains(i))) {
+                    return false;
+                }
+            }
+            return true;
+        }
+    }
 
-	/**
-	 * Set the Destination to a new one.
-	 * 
-	 * @param b
-	 *            the b to set
-	 */
-	public void setB(AbstractCpsObject b) {
-		this.b = b;
-	}
+    public void addPseudoTag(int tag) {
+        if (!pseudoTags.contains(tag)) {
+            pseudoTags.add(tag);
+        }
+    }
 
-	/**
-	 * Set the state manually to a new one.
-	 * 
-	 * @param state
-	 *            the state
-	 */
-	public void setState(boolean state) {
-		isWorking = state;
-	}
+    public void setPseudoTag(ArrayList<Integer> list) {
+        pseudoTags = list;
+    }
 
-	/**
-	 * Getter for the status.
-	 * 
-	 * @return the state
-	 */
-	public boolean getState() {
-		return isWorking;
-	}
+    public ArrayList<Integer> getPseudoTags() {
+        return pseudoTags;
+    }
 
-	/**
-	 * set the tags into a new set of tags.
-	 * 
-	 * @param tags
-	 *            tags for this edge
-	 */
-	public void setTags(ArrayList<Integer> tags) {
-		this.tags = tags;
-	}
+    public void recalculateTags() {
+        for (Integer i : pseudoTags) {
+            if (!tags.contains(i)) {
+                tags.add(i);
+            }
+        }
+    }
 
-	/**
-	 * Getter for the ArrayList of tags.
-	 * 
-	 * @return tags tags for this edge
-	 */
-	public ArrayList<Integer> getTags() {
-		return tags;
-	}
+    public int getConnected() {
+        return isConnected;
+    }
 
-	/**
-	 * Add a new tag to the ArrayList.
-	 * 
-	 * @param tag tag for the ArrayList
-	 */
-	public void addTag(int tag) {
-		if(!tags.contains(tag)){
-			tags.add(tag);
-		}
-	}
-	
-	/**
-	 * checks wether tags contains all given tags
-	 * @param toCheck 
-	 * 				tags that are checked
-	 * @return
-	 * 		true if all are contained in tags, false otherwise
-	 */
-	public boolean containsTags(ArrayList<Integer> list, ArrayList<Integer> toCheck){
-		if(toCheck.size() == 0){
-			return true;
-		}else{
-			for(Integer i: toCheck){
-				if(!(list.contains(i))){
-					return false;
-				}
-			}
-			return true;
-		}
-	}
-	
-	public void addPseudoTag(int tag){
-		if(!pseudoTags.contains(tag)){
-			pseudoTags.add(tag);
-		}
-	}
-	
-	public void setPseudoTag(ArrayList<Integer> list){
-		pseudoTags = list;
-	}
-	
-	public ArrayList<Integer> getPseudoTags(){
-		return pseudoTags;
-	}
-	
-	public void recalculateTags(){
-		for(Integer i: pseudoTags){
-			if(!tags.contains(i)){
-				tags.add(i);
-			}
-		}
-	}
-	
-	public int getConnected(){
-		return isConnected;
-	}
-	
-	public void setConnected(int state){
-		isConnected = state;
-		if(state == 1){
-			maxCapacity = -2;
-		}
-	}
+    public void setConnected(int state) {
+        isConnected = state;
+        if (state == CON_UPPER_NODE_AND_INSIDE) {
+            maxCapacity = CAPACITY_TO_UPPER_NODE;
+        }
+    }
 
 }

+ 116 - 91
src/classes/HolonElement.java

@@ -7,59 +7,51 @@ import java.util.LinkedList;
 
 /**
  * The class "HolonElement" represents any possible element that can be added to
- * a CpsObject (such as TV (consumer) or any energy source/producer).
+ * a CpsObject (such as TV (consumer) or any energyPerElement source/producer).
  *
  * @author Gruppe14
  */
 public class HolonElement {
 
-    // Points on the UnitGraph
-    LinkedList<Point> graphPoints;
+    /* Points on the UnitGraph */
+    private LinkedList<Point> graphPoints;
     /* Name of the gadget */
     @Expose
     private String eleName;
     /* Quantity */
     @Expose
     private int amount;
-    /* Energy per gadget */
+    /* Currently used energy per element (- indicates consumation of energy, + indicates production of energy)*/
     @Expose
-    private float energy;
-    /* If the gadget is working xor not (true xor false) */
+    private float energyPerElement;
+    /* Whether the gadget is active or not (currently uses/produces the energy in energyPerElement) */
     @Expose
     private boolean active;
-    /* Total Energy */
+    /* Gives us whether this element is flexible and can flexibly use any part of the energy in flexibleEnergyAvailable */
     @Expose
-    private float totalEnergy;
-    /* +: for Consumers and -: Producers */
+    private boolean flexible;
+    /* Flexibility (meaning the actual */
+    @Expose
+    private float flexibleEnergyAvailable;
+    /* -: for Consumers and +: Producers */
     @Expose
     private char sign;
     /* Place where the Object is Stored */
     @Expose
     private Pair<String, String> saving;
-    /*
-     * ID
-     */
+    /* ID */
     @Expose
     private int id;
-    /*
-     * Flexibility
-     */
-    @Expose
-    private float flexibility;
-    /*
-     * Active the flexibility field
-     */
-    @Expose
-    private boolean activeFlex;
     /*
      * Energy at each point of the graph with 100 predefined points. At the
-     * beginning, it starts with all values at energy
+     * beginning, it starts with all values at energyPerElement.
+     * If switched to flexible, this represents the maximum of usable energy
      */
-    private float[] energyAt;
+    private float[] availableEnergyPerElementAt;
 
     /**
      * Create a new HolonElement with a user-defined name, amount of the same
-     * element and energy per element.
+     * element and energyPerElement.
      *
      * @param eleName String
      * @param amount  int
@@ -68,14 +60,14 @@ public class HolonElement {
     public HolonElement(String eleName, int amount, float energy) {
         setEleName(eleName);
         setAmount(amount);
-        setEnergy(energy);
+        setEnergyPerElement(energy);
         setActive(true);
         setSign(energy);
-        setEnergyAt(energy);
+        setAvailableEnergyPerElementAt(energy);
         setGraphPoints(new LinkedList<>());
         setId(IdCounterElem.nextId());
-        setFlexibility(0);
-        setActiveFlex(false);
+        setFlexibleEnergyAvailable(0);
+        setFlexible(false);
     }
 
     /**
@@ -84,14 +76,14 @@ public class HolonElement {
     public HolonElement(String eleName, int amount, float energy, int id) {
         setEleName(eleName);
         setAmount(amount);
-        setEnergy(energy);
+        setEnergyPerElement(energy);
         setActive(true);
         setSign(energy);
-        setEnergyAt(energy);
+        setAvailableEnergyPerElementAt(energy);
         setGraphPoints(new LinkedList<>());
         setId(id);
-        setFlexibility(0);
-        setActiveFlex(false);
+        setFlexibleEnergyAvailable(0);
+        setFlexible(false);
     }
 
     /**
@@ -102,12 +94,12 @@ public class HolonElement {
     public HolonElement(HolonElement element) {
         setEleName(element.getEleName());
         setAmount(element.getAmount());
-        setEnergy(element.getEnergy());
-        setActive(element.getActive());
-        setSign(element.getEnergy());
-        setEnergyAt(element.getEnergy());
-        for (int i = 0; i < energyAt.length; i++) {
-            energyAt[i] = element.getEnergyAt()[i];
+        setEnergyPerElement(element.getEnergyPerElement());
+        setActive(element.isActive());
+        setSign(element.getEnergyPerElement());
+        setAvailableEnergyPerElementAt(element.getEnergyPerElement());
+        for (int i = 0; i < availableEnergyPerElementAt.length; i++) {
+            availableEnergyPerElementAt[i] = element.getAvailableEnergyPerElementAt()[i];
         }
         setGraphPoints(new LinkedList<>());
         for (Point p : element.getGraphPoints()) {
@@ -115,39 +107,46 @@ public class HolonElement {
         }
         setSaving(null);
         setId(IdCounterElem.nextId());
-        setFlexibility(0);
-        setActiveFlex(false);
+        setFlexibleEnergyAvailable(0);
+        setFlexible(false);
     }
 
     /**
-     * Get the Array of energy (100 values).
+     * Get the Array of energyPerElement (100 values).
      *
-     * @return energyAt Array of Floats
+     * @return availableEnergyPerElementAt Array of Floats
      */
-    public float[] getEnergyAt() {
-        return energyAt;
+    public float[] getAvailableEnergyPerElementAt() {
+        return availableEnergyPerElementAt;
     }
 
     /**
-     * Set energy to any value to the whole array.
+     * Set energyPerElement to any value to the whole array.
      *
      * @param energy the value
      */
-    public void setEnergyAt(float energy) {
-        this.energyAt = new float[100];
-        for (int i = 0; i < energyAt.length; i++) {
-            this.energyAt[i] = energy;
+    public void setAvailableEnergyPerElementAt(float energy) {
+        this.availableEnergyPerElementAt = new float[100];
+        for (int i = 0; i < availableEnergyPerElementAt.length; i++) {
+            this.availableEnergyPerElementAt[i] = energy;
         }
     }
 
     /**
-     * Set energy to any value at a given position.
+     * Get the energyPerElement currently available
+     */
+    public float getAvailableEnergyAt(int timestep) {
+        return this.availableEnergyPerElementAt[timestep];
+    }
+
+    /**
+     * Set energyPerElement to any value at a given position.
      *
      * @param pos    int
-     * @param energy float
+     * @param energyPerElement float
      */
-    public void setEnergyAt(int pos, float energy) {
-        this.energyAt[pos] = energy;
+    public void setAvailableEnergyPerElementAt(int pos, float energyPerElement) {
+        this.availableEnergyPerElementAt[pos] = energyPerElement;
     }
 
     /**
@@ -187,21 +186,22 @@ public class HolonElement {
     }
 
     /**
-     * Get the energy value of the selected Element.
+     * Get the energyPerElement value of the selected Element.
      *
-     * @return the energy
+     * @return the energyPerElement
      */
-    public float getEnergy() {
-        return energy;
+    public float getEnergyPerElement() {
+        return energyPerElement;
     }
 
     /**
-     * Set the energy value of the selected Element.
+     * Set the energyPerElement value of the selected Element.
      *
-     * @param energy the energy to set
+     * @param energyPerElement the energyPerElement to set
      */
-    public void setEnergy(float energy) {
-        this.energy = energy;
+    public void setEnergyPerElement(float energyPerElement) {
+        this.energyPerElement = energyPerElement;
+        setSign(energyPerElement);
     }
 
     /**
@@ -209,7 +209,7 @@ public class HolonElement {
      *
      * @return the active
      */
-    public boolean getActive() {
+    public boolean isActive() {
         return active;
     }
 
@@ -225,33 +225,27 @@ public class HolonElement {
     /**
      * Multiply the amount of gadgets, given by the user, and the
      * consumption/production. If the switch isWorking is turned off for on
-     * gadget, the energy of this gadget have to be subtracted.
+     * gadget, the energyPerElement of this gadget have to be subtracted.
      *
      * @return totalEnergy (actual)
      */
-    public float getTotalEnergy() {
-        if (activeFlex) {
-            totalEnergy = ((float) amount) * (energy + flexibility);
-        } else {
-            totalEnergy = ((float) amount) * energy;
-        }
+    public float getOverallEnergy() {
+        float totalEnergy = ((float) amount) * energyPerElement;
         return totalEnergy;
     }
 
     /**
-     * Get the energy value at a selected time x.
+     * Get the energyPerElement value at a selected time x.
      *
      * @param x int
-     * @return energy value
+     * @return energyPerElement value
      */
-    public float getTotalEnergyAtTimeStep(int x) {
-        float result;
-        if (activeFlex) {
-            result = ((float) amount) * (energyAt[x] + flexibility);
+    public float getOverallEnergyAtTimeStep(int x) {
+        if (flexible) {
+            return ((float) amount) * energyPerElement;
         } else {
-            result = ((float) amount) * energyAt[x];
+            return ((float) amount) * availableEnergyPerElementAt[x];
         }
-        return result;
     }
 
     /**
@@ -294,31 +288,46 @@ public class HolonElement {
     }
 
     /**
-     * Get the flexibility of an element
+     * Get the flexibleEnergyAvailable of an element
      */
-    public float getFlexibility() {
-        return this.flexibility;
+    public float getFlexibleEnergyAvailablePerElement() {
+        return this.flexibleEnergyAvailable;
     }
 
     /**
-     * Set the flexibility of an element
+     * Set the flexibleEnergyAvailable of an element
      */
-    public void setFlexibility(float f) {
-        this.flexibility = f;
+    public void setFlexibleEnergyAvailable(float f) {
+        this.flexibleEnergyAvailable = f;
     }
 
     /**
-     * Get the flexibility of an element
+     * Get the flexibleEnergyAvailable of an element
      */
-    public boolean getActiveFlex() {
-        return this.activeFlex;
+    public boolean isFlexible() {
+        return this.flexible;
     }
 
     /**
-     * Set the flexibility of an element
-     */
-    public void setActiveFlex(boolean b) {
-        this.activeFlex = b;
+     * Set the flexibleEnergyAvailable of an element, ~switches energyPerElement and flexible energyPerElement
+     */
+    public void setFlexible(boolean b) {
+        // if flexibleEnergyAvailable was set to true
+        if (b && !this.flexible) {
+            this.flexible = b;
+            // move energyPerElement to flexibleEnergyAvailable (becomes the possible-to-use energyPerElement)
+            if (getEnergyPerElement() != 0) {
+                setFlexibleEnergyAvailable(getEnergyPerElement());
+                setEnergyPerElement(0);
+            }
+        } else if (!b && this.flexible) {
+            this.flexible = b;
+            // move the energyPerElement to actually used energyPerElement and set flexible amount to 0
+            if (getFlexibleEnergyAvailablePerElement() != 0) {
+                setEnergyPerElement(getFlexibleEnergyAvailablePerElement());
+            }
+            setFlexibleEnergyAvailable(0);
+        }
     }
 
     /**
@@ -352,4 +361,20 @@ public class HolonElement {
     public void setSaving(Pair<String, String> saving) {
         this.saving = saving;
     }
+
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append("[HolonElement: ");
+        sb.append("id=").append(id)
+                .append(", eleName=").append(eleName)
+                .append(", amount=").append(amount)
+                .append(", active=").append(active)
+                .append(", flexible=").append(flexible)
+                .append(", energyPerElement used=").append(energyPerElement)
+                .append(", flexible energyPerElement available=").append(flexibleEnergyAvailable);
+        sb.append("]");
+
+        return sb.toString();
+    }
 }

+ 103 - 33
src/classes/HolonObject.java

@@ -14,14 +14,16 @@ import java.util.ArrayList;
  */
 public class HolonObject extends AbstractCpsObject {
     /*
-     * 0 = no energy, 1 = not supplied, 2 = supplied, 3 producer, 4 Partially
-     * Supplied
+     * the constants showing a HolonObject's current state
+     * (whether it needs no energy, whether it is not supplied, fully supplied,
+     * a producer, partially supplied or over-supplied)
      */
     public final static int NO_ENERGY = 0;
     public final static int NOT_SUPPLIED = 1;
     public final static int SUPPLIED = 2;
     public final static int PRODUCER = 3;
     public final static int PARTIALLY_SUPPLIED = 4;
+    public final static int OVER_SUPPLIED = 5;
     /*
      * Color of the actual state (red = no supplied, yellow = partially supplied
      * and green = supplied)
@@ -70,16 +72,16 @@ public class HolonObject extends AbstractCpsObject {
     }
 
     /**
-     * sets the State, wether object is a producer, zero Energy, supplied or
-     * not.
+     * sets the State, whether object is a producer, zero Energy, supplied,
+     * partially or over-supplied
      */
     public void setState() {
         if (getCurrentEnergy() > 0) {
-            setState(3);
+            setState(PRODUCER);
             stateColor = Color.lightGray;
         } else {
             if (getCurrentEnergy() == 0) {
-                setState(0);
+                setState(NO_ENERGY);
                 stateColor = Color.WHITE;
             } else {
                 if (checkIfPartiallySupplied(0)) {
@@ -128,8 +130,8 @@ public class HolonObject extends AbstractCpsObject {
     public float getCurrentEnergy() {
         float temp = 0;
         for (HolonElement e : getElements()) {
-            if (e.getActive()) {
-                temp = temp + e.getTotalEnergy();
+            if (e.isActive()) {
+                temp += e.getOverallEnergy();
             }
         }
         currentEnergy = temp;
@@ -145,8 +147,27 @@ public class HolonObject extends AbstractCpsObject {
     public float getCurrentEnergyAtTimeStep(int x) {
         float temp = 0;
         for (HolonElement e : getElements()) {
-            if (e.getActive()) {
-                temp = temp + e.getTotalEnergyAtTimeStep(x);
+            if (e.isActive()) {
+                temp += e.getOverallEnergyAtTimeStep(x);
+            }
+        }
+        currentEnergy = temp;
+        return currentEnergy;
+    }
+
+    /**
+     * Getter for the current energy at a given timestep.
+     *
+     * @param x timestep
+     * @return corresponding energy
+     */
+    public float getCurrentEnergyAtTimeStepWithoutFlexiblesAndResetFlexibles(int x) {
+        float temp = 0;
+        for (HolonElement e : getElements()) {
+            if (e.isActive() && !e.isFlexible()) {
+                temp += e.getOverallEnergyAtTimeStep(x);
+            } else if (e.isFlexible()) {
+                e.setEnergyPerElement(0);
             }
         }
         currentEnergy = temp;
@@ -211,24 +232,31 @@ public class HolonObject extends AbstractCpsObject {
     public void setState(int state) {
         this.state = state;
         switch (state) {
-            case 0:
+            case NO_ENERGY:
                 stateColor = Color.WHITE;
                 break;
 
-            case 1:
+            case NOT_SUPPLIED:
                 stateColor = new Color(230, 120, 100);
                 break;
 
-            case 2:
+            case SUPPLIED:
                 stateColor = Color.GREEN;
                 break;
 
-            case 3:
+            case PRODUCER:
                 stateColor = Color.lightGray;
                 break;
 
-            case 4:
+            case PARTIALLY_SUPPLIED:
                 stateColor = Color.YELLOW;
+                break;
+
+            case OVER_SUPPLIED:
+                // find different purple-tones at
+                // http://www.rapidtables.com/web/color/purple-color.htm
+                stateColor = new Color(138, 43, 226);
+                break;
         }
     }
 
@@ -274,17 +302,18 @@ public class HolonObject extends AbstractCpsObject {
         if (getElements().size() == 0) {
             return false;
         }
-        float minConsum = getElements().get(0).getTotalEnergyAtTimeStep(x);
+        float minConsum = getElements().get(0).getOverallEnergyAtTimeStep(x);
         float prod = 0;
         for (HolonElement e : getElements()) {
-            if (e.getActive()) {
-                if (e.getTotalEnergyAtTimeStep(x) > 0) {
-                    prod = prod + e.getTotalEnergyAtTimeStep(x);
+            if (e.isActive()) {
+                float overallEnergy = e.getOverallEnergyAtTimeStep(x);
+                if (overallEnergy > 0) {
+                    prod = prod + overallEnergy;
                 }
-                if (minConsum < 0 && (e.getTotalEnergyAtTimeStep(x) > minConsum && e.getTotalEnergyAtTimeStep(x) < 0)) {
-                    minConsum = e.getTotalEnergyAtTimeStep(x);
-                } else if (minConsum >= 0 && e.getTotalEnergyAtTimeStep(x) < minConsum) {
-                    minConsum = e.getTotalEnergyAtTimeStep(x);
+                if (minConsum < 0 && (overallEnergy > minConsum && overallEnergy < 0)) {
+                    minConsum = overallEnergy;
+                } else if (minConsum >= 0 && overallEnergy < minConsum) {
+                    minConsum = overallEnergy;
                 }
             }
         }
@@ -362,8 +391,8 @@ public class HolonObject extends AbstractCpsObject {
     public void updateTotalFlex() {
         float tempFlex = 0;
         for (HolonElement e : getElements()) {
-            if (e.getActiveFlex()) {
-                tempFlex += e.getFlexibility() * e.getAmount();
+            if (e.isFlexible()) {
+                tempFlex += e.getFlexibleEnergyAvailablePerElement() * e.getAmount();
             }
         }
         this.totalFlex = tempFlex;
@@ -375,8 +404,8 @@ public class HolonObject extends AbstractCpsObject {
     public float getFlexProd() {
         float tempFlex = 0;
         for (HolonElement e : getElements()) {
-            if (e.getFlexibility() > 0) {
-                tempFlex += e.getFlexibility();
+            if (e.getFlexibleEnergyAvailablePerElement() > 0) {
+                tempFlex += e.getFlexibleEnergyAvailablePerElement() * e.getAmount();
             }
         }
         return tempFlex;
@@ -388,8 +417,8 @@ public class HolonObject extends AbstractCpsObject {
     public float getFlexCons() {
         float tempFlex = 0;
         for (HolonElement e : getElements()) {
-            if (e.getFlexibility() < 0) {
-                tempFlex += e.getFlexibility();
+            if (e.getFlexibleEnergyAvailablePerElement() < 0) {
+                tempFlex += e.getFlexibleEnergyAvailablePerElement() * e.getAmount();
             }
         }
         return tempFlex;
@@ -408,11 +437,11 @@ public class HolonObject extends AbstractCpsObject {
             float valueProd = 0;
             float valueCons = 0;
             for (HolonElement e : getElements()) {
-                if (e.getActive() && e.getSign() == '+') {
-                    valueProd = valueProd + e.getTotalEnergyAtTimeStep(i);
+                if (e.isActive() && e.getSign() == '+') {
+                    valueProd = valueProd + e.getOverallEnergyAtTimeStep(i);
                 }
-                if (e.getActive() && e.getSign() == '-') {
-                    valueCons = valueCons + e.getTotalEnergyAtTimeStep(i);
+                if (e.isActive() && e.getSign() == '-') {
+                    valueCons = valueCons + e.getOverallEnergyAtTimeStep(i);
                 }
             }
             tempProd[i] = valueProd;
@@ -421,4 +450,45 @@ public class HolonObject extends AbstractCpsObject {
         this.trackingProd = tempProd;
         this.trackingCons = tempCons;
     }
+
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+
+        sb.append("[HolonObject: ");
+        sb.append("id=").append(id)
+                .append(", name=").append(name)
+                .append(", state=");
+        switch (state) {
+            case NO_ENERGY:
+                sb.append("NO_ENERGY");
+                break;
+            case NOT_SUPPLIED:
+                sb.append("NOT_SUPPLIED");
+                break;
+            case SUPPLIED:
+                sb.append("SUPPLIED");
+                break;
+            case PRODUCER:
+                sb.append("PRODUCER");
+                break;
+            case PARTIALLY_SUPPLIED:
+                sb.append("PARTIALLY_SUPPLIED");
+                break;
+            case OVER_SUPPLIED:
+                sb.append("OVER_SUPPLIED");
+                break;
+        }
+        sb.append(", elements=[");
+        for (int i = 0; i < getElements().size(); i++) {
+            HolonElement el = getElements().get(i);
+            if (i != 0) {
+                sb.append(", ");
+            }
+            sb.append(el.getEleName());
+        }
+        sb.append("]]");
+
+        return sb.toString();
+    }
 }

+ 45 - 0
src/classes/SubNet.java

@@ -53,4 +53,49 @@ public class SubNet {
 	public ArrayList<HolonSwitch> getSwitches() {
 		return subNetSwitches;
 	}
+
+
+    public String toString(int timeStep) {
+        StringBuilder sb = new StringBuilder();
+
+        sb.append("  Objects:");
+        for (int j = 0; j < getObjects().size(); j++) {
+            HolonObject hl = getObjects().get(j);
+            sb.append("    " + hl.getName() + " " + hl.getId());
+        }
+        sb.append("  Edges:");
+        for (int j = 0; j < getEdges().size(); j++) {
+            CpsEdge edge = getEdges().get(j);
+            sb.append("     " + edge.getA().getName() + " connected To " + edge.getB().getName());
+        }
+        sb.append("  Switches:");
+        for (int j = 0; j < getSwitches().size(); j++) {
+            HolonSwitch sw = getSwitches().get(j);
+            sb.append("    " + sw.getName() + " " + sw.getId() + " State:" + sw.getActiveAt()[timeStep]);
+        }
+
+        return sb.toString();
+    }
+
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+
+        sb.append("  Objects:");
+        for (int j = 0; j < getObjects().size(); j++) {
+            HolonObject hl = getObjects().get(j);
+            sb.append("    " + hl.getName() + " " + hl.getId());
+        }
+        sb.append("  Edges:");
+        for (int j = 0; j < getEdges().size(); j++) {
+            CpsEdge edge = getEdges().get(j);
+            sb.append("     " + edge.getA().getName() + " connected To " + edge.getB().getName());
+        }
+        sb.append("  Switches:");
+        for (int j = 0; j < getSwitches().size(); j++) {
+            HolonSwitch sw = getSwitches().get(j);
+            sb.append("    " + sw.getName() + " " + sw.getId() + " State:" + sw.getActiveAt());
+        }
+
+        return sb.toString();
+    }
 }

+ 3 - 2
src/classes/TrackedDataSet.java

@@ -1,9 +1,9 @@
 package classes;
 
-import java.awt.Color;
-
 import com.google.gson.annotations.Expose;
 
+import java.awt.*;
+
 public class TrackedDataSet {
 
 	//Property Integers
@@ -31,6 +31,7 @@ public class TrackedDataSet {
 	public static final int AVG_AMOUNT_ACTIVE_ELEMENTS_IN_HOLONS = 21;
 	public static final int AVG_AMOUNT_INACTIVE_ELEMENTS_IN_HOLONS = 22;
 	public static final int AVG_PRODUCED_ENERGY_IN_HOLONS = 23;
+	public static final int WASTED_ENERGY = 24;
 	
 	//Variables of the Data Set
 	private AbstractCpsObject cps;

+ 5 - 4
src/exampleAlgorithms/RepairAllEdges.java

@@ -1,10 +1,11 @@
 package exampleAlgorithms;
 
 import api.CpsAlgorithm;
+import classes.AbstractCpsObject;
+import classes.CpsEdge;
+import classes.CpsUpperNode;
 import ui.controller.Control;
 import ui.model.Model;
-import ui.view.UpperNodeCanvas;
-import classes.*;
 
 public class RepairAllEdges implements CpsAlgorithm {
 
@@ -25,7 +26,7 @@ public class RepairAllEdges implements CpsAlgorithm {
 				repairAllEdgesInUpperNode((CpsUpperNode) obj);
 			}
 			for (CpsEdge e : obj.getConnections()) {
-				e.setState(true);
+				e.setWorkingState(true);
 			}
 		}
 	}
@@ -36,7 +37,7 @@ public class RepairAllEdges implements CpsAlgorithm {
 				repairAllEdgesInUpperNode((CpsUpperNode) obj);
 			}
 			for (CpsEdge e : obj.getConnections()) {
-				e.setState(true);
+				e.setWorkingState(true);
 			}
 		}
 	}

+ 5 - 7
src/interfaces/GraphListener.java

@@ -1,14 +1,12 @@
 package interfaces;
 
-import java.util.ArrayList;
-
 import classes.AbstractCpsObject;
 
+import java.util.ArrayList;
+
 public interface GraphListener {
-	
-	public void repaintTree();
-	
-	public void addTrackedObject(ArrayList<AbstractCpsObject> hlList);
-	
 
+    void repaintTree();
+
+    void addTrackedObject(ArrayList<AbstractCpsObject> hlList);
 }

+ 25 - 25
src/tests/PraktikumHolonsTestClasses.java

@@ -113,13 +113,13 @@ public class PraktikumHolonsTestClasses {
 //
 //		assertTrue("Manuel Mode is on", !test2.getManualMode());
 //		test2.switchState();
-//		assertTrue(test2.getState());
-//		assertTrue(test2.getState(1));
+//		assertTrue(test2.isWorking());
+//		assertTrue(test2.isWorking(1));
 //		test2.setManualMode(true);
 //		test2.switchState();
 //		test2.switchState();
-//		assertTrue(test2.getState());
-//		assertTrue(test2.getState(1));
+//		assertTrue(test2.isWorking());
+//		assertTrue(test2.isWorking(1));
 //		assertTrue("Manuel Mode is off", test2.getManualMode());
 //		assertTrue("ManuelActive is off", test2.getActiveManual());
 //		test2.switchState();
@@ -149,24 +149,24 @@ public class PraktikumHolonsTestClasses {
 		edge1.setCapacity(200);
 		assertTrue("Flow was not changed", edge1.getFlow() == 50);
 		assertTrue("Capacity not right", edge1.getCapacity() == 200);
-		assertTrue("line broken", edge2.getState());
-		edge2.calculateState();
-		assertTrue("line broken", edge2.getState());
-		edge2.setFlow(200);
-		edge2.calculateState();
-		assertTrue("line not broken", !edge2.getState());
-		edge1.setCapacity(-1);
-		edge1.calculateState();
+        assertTrue("line broken", edge2.isWorking());
+        edge2.calculateState();
+        assertTrue("line broken", edge2.isWorking());
+        edge2.setFlow(200);
+        edge2.calculateState();
+        assertTrue("line not broken", !edge2.isWorking());
+        edge1.setCapacity(-1);
+        edge1.calculateState();
 		edge1.setCapacity(500);
 		edge1.calculateState();
 		node1 = (CpsNode) edge1.getB();
 		node2 = (CpsNode) edge2.getA();
 		assertTrue("Not Same", node1 == node2);
-		assertTrue("State not right", edge1.getState());
-		edge1.setState(false);
-		assertTrue("State not right", !edge1.getState());
-		edge2.setTags(new ArrayList<>());
-		edge1.setTags(new ArrayList<>());
+        assertTrue("State not right", edge1.isWorking());
+        edge1.setWorkingState(false);
+        assertTrue("State not right", !edge1.isWorking());
+        edge2.setTags(new ArrayList<>());
+        edge1.setTags(new ArrayList<>());
 		assertTrue("Tags not Empty", edge2.getTags().isEmpty());
 		edge2.addTag(1);
 		assertTrue("Tags not Empty", edge1.getTags().isEmpty());
@@ -184,18 +184,18 @@ public class PraktikumHolonsTestClasses {
 		HolonElement ele2 = new HolonElement("Fridge", 1, -50);
 		HolonElement ele3 = new HolonElement(ele2);
 
-		assertTrue("Array not empty", ele1.getEnergyAt()[0] == -20);
-		assertTrue("Array not empty", ele1.getEnergyAt()[2] == -20);
-		ele1.setEnergyAt(2, -10);
-		assertTrue("Array not empty", ele1.getEnergyAt()[2] == -10);
-		assertTrue("Name not correct", ele1.getEleName().equals("TV"));
-		ele1.setEleName(ele2.getEleName());
+        assertTrue("Array not empty", ele1.getAvailableEnergyPerElementAt()[0] == -20);
+        assertTrue("Array not empty", ele1.getAvailableEnergyPerElementAt()[2] == -20);
+        ele1.setAvailableEnergyPerElementAt(2, -10);
+        assertTrue("Array not empty", ele1.getAvailableEnergyPerElementAt()[2] == -10);
+        assertTrue("Name not correct", ele1.getEleName().equals("TV"));
+        ele1.setEleName(ele2.getEleName());
 		assertTrue("Name not correct", ele1.getEleName().equals("Fridge"));
 		assertTrue("Amount not correct", ele2.getAmount() == 1);
 		ele2.setAmount(5);
 		assertTrue("Amount not correct", ele2.getAmount() == 5);
-		assertTrue("Total Energy not Correct", ele2.getTotalEnergy() == ele2.getAmount() * ele2.getEnergy());
-		assertTrue("Sign not correct", ele2.getSign() == '-');
+        assertTrue("Total Energy not Correct", ele2.getOverallEnergy() == ele2.getAmount() * ele2.getEnergyPerElement());
+        assertTrue("Sign not correct", ele2.getSign() == '-');
 //		ele3.setSav("CVS");
 //		assertTrue("SAV not correct", ele3.getSav().equals("CVS"));
 	}

+ 428 - 474
src/ui/controller/ClipboardController.java

@@ -1,486 +1,440 @@
 package ui.controller;
 
-import java.awt.Point;
-import java.awt.Toolkit;
-import java.awt.datatransfer.Clipboard;
-import java.awt.datatransfer.DataFlavor;
-import java.awt.datatransfer.StringSelection;
-import java.awt.datatransfer.Transferable;
-import java.awt.datatransfer.UnsupportedFlavorException;
-import java.io.IOException;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.stream.Collectors;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParseException;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonPrimitive;
-
-import classes.AbstractCpsObject;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounter;
-import classes.IdCounterElem;
-import classes.Position;
+import classes.*;
+import com.google.gson.*;
 import ui.controller.SaveController.EDGETYPE;
 import ui.controller.SaveController.GRAPHTYPE;
 import ui.controller.SaveController.NUMTYPE;
 import ui.controller.SaveController.TYPE;
 import ui.model.Model;
 
+import java.awt.*;
+import java.awt.datatransfer.*;
+import java.io.IOException;
+import java.util.*;
+import java.util.List;
+import java.util.stream.Collectors;
+
 public class ClipboardController {
 
-	private Model model;
-	private SaveController store;
-	private LoadController load;
-	private CanvasController cvsC;
-	private ObjectController objC;
-	private NodeController uppC;
-	private JsonParser parser;
-	private Clipboard clipboard;
-	private HashMap<Integer, Integer> objIDMap;
-	private HashMap<Integer, Integer> eleIDMap;
-	private String sav;
-	private Point point;
-
-	public ClipboardController(Model model, SaveController store, LoadController load, CanvasController cvs,
-			ObjectController obj, NodeController uppC, MultiPurposeController mp) {
-		this.model = model;
-		this.store = store;
-		this.load = load;
-		this.cvsC = cvs;
-		this.objC = obj;
-		this.uppC = uppC;
-		this.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
-		parser = new JsonParser();
-	}
-
-	/**
-	 * Copy marked Objects into Clipboard in Json Format
-	 * @param upperNode
-	 */
-	public void copy(CpsUpperNode upperNode) {
-
-		JsonObject file = new JsonObject();
-		ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
-		AbstractCpsObject u = null;
-
-		store.initNumeration();
-
-		file.add("SAV", new JsonPrimitive((upperNode == null ? "CVS" : "" + upperNode.getId())));
-		Position pos = uppC.calculatePos(model.getSelectedCpsObjects());
-		file.add("CENTER", model.getGson().toJsonTree(pos, Position.class));
-
-		for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
-			queue.add(abs);
-		}
-
-		while (!queue.isEmpty()) {
-
-			u = queue.pop();
-
-			String key = "CVSOBJECT" + store.getNumerator(NUMTYPE.OBJECT);
-			file.add(key, model.getGson().toJsonTree(u, AbstractCpsObject.class));
-			edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
-
-			if (u instanceof HolonObject)
-				store.elementsToJson(TYPE.CANVAS, file, u);
-
-			if (u instanceof HolonSwitch)
-				if (((HolonSwitch) u).getGraphPoints().size() != 0)
-					store.unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
-
-			if (u instanceof CpsUpperNode) {
-				for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
-					queue.add(adjacent);
-				}
-				edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
-				edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
-			}
-		}
-		if (upperNode == null)
-			edgeToJson(EDGETYPE.LAYER, file, 0, model.getEdgesOnCanvas());
-		else
-			edgeToJson(EDGETYPE.LAYER, file, upperNode.getId(), upperNode.getNodeEdges());
-
-		StringSelection selection = new StringSelection(model.getGson().toJson(file));
-		clipboard.setContents(selection, selection);
-
-	}
-
-	/**
-	 * Paste the Copied JsonTree into Canvas
-	 * @param upperNode
-	 */
-	public void paste(CpsUpperNode upperNode, Point p)
-			throws UnsupportedFlavorException, IOException, JsonParseException {
-
-		if (p == null)
-			return;
-
-		JsonObject json = new JsonObject();
-		Transferable content = clipboard.getContents(null);
-
-		if (content != null && content.isDataFlavorSupported(DataFlavor.stringFlavor)
-				&& !content.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
-
-			String str = (String) content.getTransferData(DataFlavor.stringFlavor);
-
-			if (parser.parse(str).isJsonObject())
-				json = (JsonObject) parser.parse(str);
-			else
-				throw new JsonParseException("Unknown Clipboard Information");
-
-		} else
-			return;
-
-		List<String> keys = load.getKeys(json);
-		List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
-				.collect(Collectors.toCollection(ArrayList::new));
-
-		HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
-		HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
-		model.getSelectedCpsObjects().clear();
-
-		objIDMap = new HashMap<>();
-		eleIDMap = new HashMap<>();
-		sav = json.get("SAV").getAsString();
-
-		Position old = model.getGson().getAdapter(Position.class).fromJsonTree(json.get("CENTER"));
-		point = new Point(old.x - p.x, old.y - p.y);
-
-		forwardObjects(keys, json, objDispatch, eleDispatch, upperNode);
-		// for selecting Cps
-		getObjectsInDepth();
-		forwardEdges(edges, json, objDispatch, upperNode);
-
-	}
-	
-	/**
-	 * Cuts the marked Objects out of Canvas and saves them into the Clipboard
-	 * @param upperNode
-	 */
-	public void cut(CpsUpperNode upperNode) {
-		copy(upperNode);
-		for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
-			if (upperNode == null)
-				cvsC.deleteObjectOnCanvas(abs);
-			else
-				uppC.deleteObjectInUpperNode(abs, upperNode);
-
-			if (abs instanceof CpsUpperNode)
-				cvsC.bfsNodeCleaner((CpsUpperNode) abs);
-		}
-
-	}
-
-	private void forwardEdges(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
-			CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		List<String> conn = new ArrayList<>();
-
-		for (String edge : keys) {
-			if (edge.contains("LAYEREDGE"))
-				loadEdge(EDGETYPE.LAYER, json.get(edge), objDispatch, upperNode);
-			if (edge.contains("CONNEDGE"))
-				conn.add(edge);
-			if (edge.contains("NODEEDGE"))
-				loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch, null);
-			if (edge.contains("OLDEDGE"))
-				loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch, null);
-		}
-
-		for (String edge : conn) {
-			loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch, null);
-		}
-
-	}
-
-	private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-
-		for (String key : keys) {
-			if (key.contains("CVSOBJECT"))
-				loadCanvasObject(json.get(key), objDispatch, upperNode);
-			if (key.contains("CVSELEMENT"))
-				loadCanvasElements(json.get(key), objDispatch, eleDispatch);
-			if (key.contains("SWUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
-			if (key.contains("ELEUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
-		}
-	}
-
-	private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
-		load.initObjects(temp);
-		objIDMapper(temp);
-		updatePosition(temp, upperNode);
-
-		// if its stored before on the canvas just put it there
-		if (temp.getSav().equals(sav)) {
-			if (upperNode == null)
-				cvsC.addObject(temp);
-			else
-				uppC.addObjectInUpperNode(temp, upperNode);
-			// mark the Pasted Objects
-			model.getSelectedCpsObjects().add(temp);
-		} else {
-			// else look up the table and put it into the right Uppernode
-			CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(objIDMap.get(Integer.parseInt(temp.getSav())));
-			uppC.addObjectInUpperNode(temp, temp2);
-		}
-
-		objDispatch.put(temp.getId(), temp);
-	}
-
-	private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-
-		HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
-		load.initElements(temp);
-		eleIDMapper(temp);
-		// id which Object it was stored before
-		int stored = objIDMap.get(object.get("ID").getAsInt());
-		// lookup that object
-		HolonObject temp2 = (HolonObject) objDispatch.get(stored);
-		// add it
-		objC.addElement(temp2, temp);
-		// store element also inside a table
-		eleDispatch.put(temp.getId(), temp);
-
-	}
-
-	private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		List<String> keys = load.getKeys(object);
-		String p = null;
-		int mid, x, y = 0;
-
-		LinkedList<Point> graphpoint = new LinkedList<>();
-		int sav = 0;
-		// foreach Point in the graph restore it
-		for (String k : keys) {
-			if (!k.equals("ID")) {
-				p = object.get(k).getAsString();
-				mid = p.indexOf(':');
-				x = Integer.parseInt(p.substring(0, mid));
-				y = Integer.parseInt(p.substring(mid + 1, p.length()));
-				graphpoint.add(new Point(x, y));
-			} else
-				// else its an ID
-				sav = object.get(k).getAsInt();
-
-		}
-
-		switch (type) {
-		case SWITCH:
-			sav = objIDMap.get(sav);
-			HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
-			sw.setGraphPoints(graphpoint);
-			break;
-		case ELEMENT:
-			sav = eleIDMap.get(sav);
-			HolonElement ele = eleDispatch.get(sav);
-			ele.setGraphPoints(graphpoint);
-			break;
-		default:
-			break;
-		}
-
-	}
-	
-	/**
-	 * 
-	 * @param type
-	 * @param jsonElement
-	 * @param objDispatch
-	 * @param upperNode
-	 */
-	private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
-		load.initCpsEdge(temp);
-		// look for A and B inside the Table
-		temp.setA(objDispatch.get(objIDMap.get(object.get("A").getAsInt())));
-		temp.setB(objDispatch.get(objIDMap.get(object.get("B").getAsInt())));
-
-		int sav = 0;
-
-		switch (type) {
-		case LAYER:
-			// if in canvas add it into the canvas but delete connection before
-			(upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).add(temp);
-			break;
-		case CONNECTION:
-			// if no duplicates in connection store them into the given A and B
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
-				temp.getA().getConnections().add(temp);
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
-				temp.getB().getConnections().add(temp);
-			break;
-		case NODE:
-			// put it into given nodeofnode
-			sav = objIDMap.get(object.get("ID").getAsInt());
-			((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
-			break;
-		case OLD:
-			// same as above
-			sav = objIDMap.get(object.get("ID").getAsInt());
-			((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
-			break;
-		default:
-			break;
-		}
-
-		if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
-			temp.getA().getConnections().add(temp);
-			temp.getB().getConnections().add(temp);
-		}
-
-	}
-
-	/**
-	 * Modified Method from LoadController. Slightly different
-	 * @param type
-	 * @param file
-	 * @param id
-	 * @param arr
-	 */
-	private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
-		// TODO Auto-generated method stub
-		String k = null;
-		boolean b = false;
-		JsonObject temp = new JsonObject();
-
-		for (CpsEdge edge : arr) {
-			if (model.getClipboradObjects().contains(edge.getA())
-					&& model.getClipboradObjects().contains(edge.getB())) {
-				// add properties and only the ids from a and b
-				temp.add("properties", model.getGson().toJsonTree(edge));
-				temp.add("A", new JsonPrimitive(edge.getA().getId()));
-				temp.add("B", new JsonPrimitive(edge.getB().getId()));
-
-				// Key and occasionally the id of Uppernode
-				switch (type) {
-				case LAYER:
-					temp.add("ID", new JsonPrimitive(id));
-					k = "LAYEREDGE" + store.getNumerator(NUMTYPE.EDGE);
-					break;
-				case CONNECTION:
-					k = "CONNEDGE" + store.getNumerator(NUMTYPE.CONNECTION);
-					break;
-				case NODE:
-					temp.add("ID", new JsonPrimitive(id));
-					k = "NODEEDGE" + store.getNumerator(NUMTYPE.NODEEDGE);
-					break;
-				case OLD:
-					temp.add("ID", new JsonPrimitive(id));
-					k = "OLDEDGE" + store.getNumerator(NUMTYPE.OLDEDGE);
-					break;
-				default:
-					break;
-				}
-				// lookup if the CVS, NODE or OLDEDGE are also connections
-				if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
-						&& !type.equals(EDGETYPE.CONNECTION))
-					b = true;
-				temp.add("connection", new JsonPrimitive(b));
-				file.add(k, model.getGson().toJsonTree(temp));
-				temp = new JsonObject();
-			}
-		}
-	}
-
-	/**
-	 * Adds all Objects in Depth into Clipboardobjects preemptive when objects are selected
-	 */
-	public void getObjectsInDepth() {
-		model.setClipboradObjects(new ArrayList<>());
-		for (AbstractCpsObject obj : model.getSelectedCpsObjects()) {
-			clipboadDepth(obj);
-		}
-	}
-
-	/**
-	 * Get all Objects inside the Currentobject and add them into ClipboardObjects
-	 * @param obj
-	 */
-	private void clipboadDepth(AbstractCpsObject obj) {
-		//modified backtracking Algorithm no True/False
-		if (!(obj instanceof CpsUpperNode)) {
-			model.getClipboradObjects().add(obj);
-			return;
-		} else {
-			model.getClipboradObjects().add(obj);
-			for (AbstractCpsObject abs : ((CpsUpperNode) obj).getNodes()) {
-				clipboadDepth(abs);
-			}
-			return;
-		}
-
-	}
-	
-	/**
-	 * Map the Copied Object ID into a new One
-	 * @param temp
-	 */
-	private void objIDMapper(AbstractCpsObject temp) {
-		// TODO Auto-generated method stub
-		int id = temp.getId();
-		temp.setId(IdCounter.nextId());
-		// oldID -> currentID
-		objIDMap.put(id, temp.getId());
-	}
-	/**
-	 * Map the Copied Element ID into a new One
-	 * @param temp
-	 */
-	private void eleIDMapper(HolonElement temp) {
-		// TODO Auto-generated method stub
-		int id = temp.getId();
-		temp.setId(IdCounterElem.nextId());
-		// oldID -> currentID
-		eleIDMap.put(id, temp.getId());
-
-	}
-
-	private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
-		int x = temp.getPosition().x - point.x;
-		int y = temp.getPosition().y - point.y;
-
-		if (y < 0)
-			y = 0 + model.getScaleDiv2() + 1;
-		if (upperNode != null) {
-			if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
-				x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
-		} else if (x < 0)
-			x = 0 + model.getScaleDiv2() + 1;
-		if (x > model.getCanvasX())
-			x = model.getCanvasX() - model.getScaleDiv2() - 1;
-		if (y > model.getCanvasX())
-			y = model.getCanvasY() - model.getScaleDiv2() - 1;
-
-		temp.setPosition(new Position(x, y));
-
-	}
+    private Model model;
+    private SaveController store;
+    private LoadController load;
+    private CanvasController cvsC;
+    private ObjectController objC;
+    private NodeController uppC;
+    private JsonParser parser;
+    private Clipboard clipboard;
+    private HashMap<Integer, Integer> objIDMap;
+    private HashMap<Integer, Integer> eleIDMap;
+    private String sav;
+    private Point point;
+
+    ClipboardController(Model model, SaveController store, LoadController load, CanvasController cvs,
+                        ObjectController obj, NodeController uppC, MultiPurposeController mp) {
+        this.model = model;
+        this.store = store;
+        this.load = load;
+        this.cvsC = cvs;
+        this.objC = obj;
+        this.uppC = uppC;
+        this.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+        parser = new JsonParser();
+    }
+
+    /**
+     * Copy marked Objects into Clipboard in Json Format
+     */
+    public void copy(CpsUpperNode upperNode) {
+
+        JsonObject file = new JsonObject();
+        ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
+        AbstractCpsObject u = null;
+
+        store.initNumeration();
+
+        file.add("SAV", new JsonPrimitive((upperNode == null ? "CVS" : "" + upperNode.getId())));
+        Position pos = uppC.calculatePos(model.getSelectedCpsObjects());
+        file.add("CENTER", model.getGson().toJsonTree(pos, Position.class));
+
+        for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
+            queue.add(abs);
+        }
+
+        while (!queue.isEmpty()) {
+
+            u = queue.pop();
+
+            String key = "CVSOBJECT" + store.getNumerator(NUMTYPE.OBJECT);
+            file.add(key, model.getGson().toJsonTree(u, AbstractCpsObject.class));
+            edgeToJson(EDGETYPE.CONNECTION, file, u.getId(), u.getConnections());
+
+            if (u instanceof HolonObject)
+                store.elementsToJson(TYPE.CANVAS, file, u);
+
+            if (u instanceof HolonSwitch)
+                if (((HolonSwitch) u).getGraphPoints().size() != 0)
+                    store.unitgraphToJson(GRAPHTYPE.SWITCH, file, u.getId(), ((HolonSwitch) u).getGraphPoints());
+
+            if (u instanceof CpsUpperNode) {
+                for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
+                    queue.add(adjacent);
+                }
+                edgeToJson(EDGETYPE.NODE, file, u.getId(), ((CpsUpperNode) u).getNodeEdges());
+                edgeToJson(EDGETYPE.OLD, file, u.getId(), ((CpsUpperNode) u).getOldEdges());
+            }
+        }
+        if (upperNode == null)
+            edgeToJson(EDGETYPE.LAYER, file, 0, model.getEdgesOnCanvas());
+        else
+            edgeToJson(EDGETYPE.LAYER, file, upperNode.getId(), upperNode.getNodeEdges());
+
+        StringSelection selection = new StringSelection(model.getGson().toJson(file));
+        clipboard.setContents(selection, selection);
+
+    }
+
+    /**
+     * Paste the Copied JsonTree into Canvas
+     */
+    void paste(CpsUpperNode upperNode, Point p)
+            throws UnsupportedFlavorException, IOException, JsonParseException {
+
+        if (p == null)
+            return;
+
+        JsonObject json;
+        Transferable content = clipboard.getContents(null);
+
+        if (content != null && content.isDataFlavorSupported(DataFlavor.stringFlavor)
+                && !content.isDataFlavorSupported(DataFlavor.allHtmlFlavor)) {
+
+            String str = (String) content.getTransferData(DataFlavor.stringFlavor);
+
+            if (parser.parse(str).isJsonObject())
+                json = (JsonObject) parser.parse(str);
+            else
+                throw new JsonParseException("Unknown Clipboard Information");
+
+        } else
+            return;
+
+        List<String> keys = load.getKeys(json);
+        List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
+                .collect(Collectors.toCollection(ArrayList::new));
+
+        HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
+        HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
+        model.getSelectedCpsObjects().clear();
+
+        objIDMap = new HashMap<>();
+        eleIDMap = new HashMap<>();
+        sav = json.get("SAV").getAsString();
+
+        Position old = model.getGson().getAdapter(Position.class).fromJsonTree(json.get("CENTER"));
+        point = new Point(old.x - p.x, old.y - p.y);
+
+        forwardObjects(keys, json, objDispatch, eleDispatch, upperNode);
+        // for selecting Cps
+        getObjectsInDepth();
+        forwardEdges(edges, json, objDispatch, upperNode);
+
+    }
+
+    /**
+     * Cuts the marked Objects out of Canvas and saves them into the Clipboard
+     */
+    void cut(CpsUpperNode upperNode) {
+        copy(upperNode);
+        for (AbstractCpsObject abs : model.getSelectedCpsObjects()) {
+            if (upperNode == null)
+                cvsC.deleteObjectOnCanvas(abs);
+            else
+                uppC.deleteObjectInUpperNode(abs, upperNode);
+
+            if (abs instanceof CpsUpperNode)
+                cvsC.bfsNodeCleaner((CpsUpperNode) abs);
+        }
+
+    }
+
+    private void forwardEdges(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
+                              CpsUpperNode upperNode) {
+        List<String> conn = new ArrayList<>();
+
+        for (String edge : keys) {
+            if (edge.contains("LAYEREDGE"))
+                loadEdge(EDGETYPE.LAYER, json.get(edge), objDispatch, upperNode);
+            if (edge.contains("CONNEDGE"))
+                conn.add(edge);
+            if (edge.contains("NODEEDGE"))
+                loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch, null);
+            if (edge.contains("OLDEDGE"))
+                loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch, null);
+        }
+
+        for (String edge : conn) {
+            loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch, null);
+        }
+
+    }
+
+    private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                HashMap<Integer, HolonElement> eleDispatch, CpsUpperNode upperNode) {
+
+        for (String key : keys) {
+            if (key.contains("CVSOBJECT"))
+                loadCanvasObject(json.get(key), objDispatch, upperNode);
+            if (key.contains("CVSELEMENT"))
+                loadCanvasElements(json.get(key), objDispatch, eleDispatch);
+            if (key.contains("SWUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
+            if (key.contains("ELEUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
+        }
+    }
+
+    private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                  CpsUpperNode upperNode) {
+        AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
+        load.initObjects(temp);
+        objIDMapper(temp);
+        updatePosition(temp, upperNode);
+
+        // if its stored before on the canvas just put it there
+        if (temp.getSav().equals(sav)) {
+            if (upperNode == null)
+                cvsC.addObject(temp);
+            else
+                uppC.addObjectInUpperNode(temp, upperNode);
+            // mark the Pasted Objects
+            model.getSelectedCpsObjects().add(temp);
+        } else {
+            // else look up the table and put it into the right Uppernode
+            CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(objIDMap.get(Integer.parseInt(temp.getSav())));
+            uppC.addObjectInUpperNode(temp, temp2);
+        }
+
+        objDispatch.put(temp.getId(), temp);
+    }
+
+    private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                    HashMap<Integer, HolonElement> eleDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+
+        HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
+        load.initElements(temp);
+        eleIDMapper(temp);
+        // id which Object it was stored before
+        int stored = objIDMap.get(object.get("ID").getAsInt());
+        // lookup that object
+        HolonObject temp2 = (HolonObject) objDispatch.get(stored);
+        // add it
+        objC.addElement(temp2, temp);
+        // store element also inside a table
+        eleDispatch.put(temp.getId(), temp);
+
+    }
+
+    private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                               HashMap<Integer, HolonElement> eleDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        List<String> keys = load.getKeys(object);
+        String p;
+        int mid, x, y;
+
+        LinkedList<Point> graphpoint = new LinkedList<>();
+        int sav = 0;
+        // foreach Point in the graph restore it
+        for (String k : keys) {
+            if (!k.equals("ID")) {
+                p = object.get(k).getAsString();
+                mid = p.indexOf(':');
+                x = Integer.parseInt(p.substring(0, mid));
+                y = Integer.parseInt(p.substring(mid + 1, p.length()));
+                graphpoint.add(new Point(x, y));
+            } else
+                // else its an ID
+                sav = object.get(k).getAsInt();
+
+        }
+
+        switch (type) {
+            case SWITCH:
+                sav = objIDMap.get(sav);
+                HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
+                sw.setGraphPoints(graphpoint);
+                break;
+            case ELEMENT:
+                sav = eleIDMap.get(sav);
+                HolonElement ele = eleDispatch.get(sav);
+                ele.setGraphPoints(graphpoint);
+                break;
+            default:
+                break;
+        }
+
+    }
+
+    /**
+     * loads an edge from json
+     */
+    private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                          CpsUpperNode upperNode) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
+        load.initCpsEdge(temp);
+        // look for A and B inside the Table
+        temp.setA(objDispatch.get(objIDMap.get(object.get("A").getAsInt())));
+        temp.setB(objDispatch.get(objIDMap.get(object.get("B").getAsInt())));
+
+        int sav;
+
+        switch (type) {
+            case LAYER:
+                // if in canvas add it into the canvas but delete connection before
+                (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges()).add(temp);
+                break;
+            case CONNECTION:
+                // if no duplicates in connection store them into the given A and B
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
+                    temp.getA().getConnections().add(temp);
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
+                    temp.getB().getConnections().add(temp);
+                break;
+            case NODE:
+                // put it into given nodeofnode
+                sav = objIDMap.get(object.get("ID").getAsInt());
+                ((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
+                break;
+            case OLD:
+                // same as above
+                sav = objIDMap.get(object.get("ID").getAsInt());
+                ((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
+                break;
+            default:
+                break;
+        }
+
+        if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
+            temp.getA().getConnections().add(temp);
+            temp.getB().getConnections().add(temp);
+        }
+
+    }
+
+    /**
+     * Modified Method from LoadController. Slightly different
+     */
+    private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
+        String k = null;
+        boolean b = false;
+        JsonObject temp = new JsonObject();
+
+        for (CpsEdge edge : arr) {
+            if (model.getClipboradObjects().contains(edge.getA())
+                    && model.getClipboradObjects().contains(edge.getB())) {
+                // add properties and only the ids from a and b
+                temp.add("properties", model.getGson().toJsonTree(edge));
+                temp.add("A", new JsonPrimitive(edge.getA().getId()));
+                temp.add("B", new JsonPrimitive(edge.getB().getId()));
+
+                // Key and occasionally the id of Uppernode
+                switch (type) {
+                    case LAYER:
+                        temp.add("ID", new JsonPrimitive(id));
+                        k = "LAYEREDGE" + store.getNumerator(NUMTYPE.EDGE);
+                        break;
+                    case CONNECTION:
+                        k = "CONNEDGE" + store.getNumerator(NUMTYPE.CONNECTION);
+                        break;
+                    case NODE:
+                        temp.add("ID", new JsonPrimitive(id));
+                        k = "NODEEDGE" + store.getNumerator(NUMTYPE.NODEEDGE);
+                        break;
+                    case OLD:
+                        temp.add("ID", new JsonPrimitive(id));
+                        k = "OLDEDGE" + store.getNumerator(NUMTYPE.OLDEDGE);
+                        break;
+                    default:
+                        break;
+                }
+                // lookup if the CVS, NODE or OLDEDGE are also connections
+                if (edge.getA().getConnections().contains(edge) && edge.getA().getConnections().contains(edge)
+                        && !type.equals(EDGETYPE.CONNECTION))
+                    b = true;
+                temp.add("connection", new JsonPrimitive(b));
+                file.add(k, model.getGson().toJsonTree(temp));
+                temp = new JsonObject();
+            }
+        }
+    }
+
+    /**
+     * Adds all Objects in Depth into Clipboardobjects preemptive when objects are selected
+     */
+    void getObjectsInDepth() {
+        model.setClipboradObjects(new ArrayList<>());
+        for (AbstractCpsObject obj : model.getSelectedCpsObjects()) {
+            clipboadDepth(obj);
+        }
+    }
+
+    /**
+     * Get all Objects inside the Currentobject and add them into ClipboardObjects
+     */
+    private void clipboadDepth(AbstractCpsObject obj) {
+        //modified backtracking Algorithm no True/False
+        if (!(obj instanceof CpsUpperNode)) {
+            model.getClipboradObjects().add(obj);
+        } else {
+            model.getClipboradObjects().add(obj);
+            for (AbstractCpsObject abs : ((CpsUpperNode) obj).getNodes()) {
+                clipboadDepth(abs);
+            }
+        }
+
+    }
+
+    /**
+     * Map the Copied Object ID into a new One
+     */
+    private void objIDMapper(AbstractCpsObject temp) {
+        int id = temp.getId();
+        temp.setId(IdCounter.nextId());
+        // oldID -> currentID
+        objIDMap.put(id, temp.getId());
+    }
+
+    /**
+     * Map the Copied Element ID into a new One
+     */
+    private void eleIDMapper(HolonElement temp) {
+        int id = temp.getId();
+        temp.setId(IdCounterElem.nextId());
+        // oldID -> currentID
+        eleIDMap.put(id, temp.getId());
+
+    }
+
+    private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
+        int x = temp.getPosition().x - point.x;
+        int y = temp.getPosition().y - point.y;
+
+        if (y < 0)
+            y = 0 + model.getScaleDiv2() + 1;
+        if (upperNode != null) {
+            if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
+                x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
+        } else if (x < 0)
+            x = 0 + model.getScaleDiv2() + 1;
+        if (x > model.getCanvasX())
+            x = model.getCanvasX() - model.getScaleDiv2() - 1;
+        if (y > model.getCanvasX())
+            y = model.getCanvasY() - model.getScaleDiv2() - 1;
+
+        temp.setPosition(new Position(x, y));
+
+    }
 
 }

+ 5 - 26
src/ui/controller/Control.java

@@ -79,7 +79,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -103,12 +102,12 @@ public class Control {
     public void deleteDirectory(File path) {
         if (path.exists()) {
             File[] files = path.listFiles();
-            for (int i = 0; i < files.length; i++) {
-                if (files[i].isDirectory()) {
-                    deleteDirectory(files[i]);
+            for (File file : files) {
+                if (file.isDirectory()) {
+                    deleteDirectory(file);
                 } else {
-                    if (files[i].getName().contains("" + rand))
-                        files[i].delete();
+                    if (file.getName().contains("" + rand))
+                        file.delete();
                 }
             }
             // path.delete();
@@ -277,7 +276,6 @@ public class Control {
             try {
                 autoSave();
             } catch (IOException e) {
-                // TODO Auto-generated catch block
                 e.printStackTrace();
             }
         }
@@ -298,7 +296,6 @@ public class Control {
             try {
                 autoSave();
             } catch (IOException e) {
-                // TODO Auto-generated catch block
                 e.printStackTrace();
             }
     }
@@ -313,7 +310,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -328,7 +324,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -369,7 +364,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -398,7 +392,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -641,7 +634,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -656,7 +648,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -698,7 +689,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -708,7 +698,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -724,7 +713,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -734,7 +722,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -744,7 +731,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -756,7 +742,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
 
@@ -767,7 +752,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -777,7 +761,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -787,7 +770,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -797,7 +779,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -861,7 +842,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }
@@ -871,7 +851,6 @@ public class Control {
         try {
             autoSave();
         } catch (IOException e) {
-            // TODO Auto-generated catch block
             e.printStackTrace();
         }
     }

+ 18 - 25
src/ui/controller/HolonCanvasController.java

@@ -1,18 +1,11 @@
 package ui.controller;
 
-import java.awt.Dimension;
-import java.util.ArrayList;
-
-import classes.AbstractCpsObject;
-import classes.Constants;
-import classes.CpsUpperNode;
-import classes.HolonBody;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.SubNet;
-import classes.Vector2d;
+import classes.*;
 import ui.model.Model;
 
+import java.awt.*;
+import java.util.ArrayList;
+
 public class HolonCanvasController {
 
 	// Ball objects
@@ -89,8 +82,8 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-					if (ele.getActive()) {
-						val += 1;
+                    if (ele.isActive()) {
+                        val += 1;
 					}
 				}
 			} else if (obj instanceof CpsUpperNode) {
@@ -107,10 +100,10 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-					if (ele.getEnergyAt()[tStep] > 0 && ele.getActive()) {
-						val += ele.getEnergyAt()[tStep] * ele.getAmount();
-					}
-				}
+                    if (ele.getAvailableEnergyPerElementAt()[tStep] > 0 && ele.isActive()) {
+                        val += ele.getAvailableEnergyPerElementAt()[tStep] * ele.getAmount();
+                    }
+                }
 				if (val > 0)
 					prod += 1;
 			} else if (obj instanceof CpsUpperNode) {
@@ -138,10 +131,10 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-					if (ele.getEnergyAt()[tStep] < 0 && ele.getActive()) {
-						val += ele.getEnergyAt()[tStep] * ele.getAmount();
-					}
-				}
+                    if (ele.getAvailableEnergyPerElementAt()[tStep] < 0 && ele.isActive()) {
+                        val += ele.getAvailableEnergyPerElementAt()[tStep] * ele.getAmount();
+                    }
+                }
 			} else if (obj instanceof CpsUpperNode) {
 				val += getTotalConsumption(((CpsUpperNode) obj).getNodes());
 			}
@@ -155,10 +148,10 @@ public class HolonCanvasController {
 		for (AbstractCpsObject obj : objects) {
 			if (obj instanceof HolonObject) {
 				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-					if (ele.getEnergyAt()[tStep] > 0 && ele.getActive()) {
-						val += ele.getEnergyAt()[tStep] * ele.getAmount();
-					}
-				}
+                    if (ele.getAvailableEnergyPerElementAt()[tStep] > 0 && ele.isActive()) {
+                        val += ele.getAvailableEnergyPerElementAt()[tStep] * ele.getAmount();
+                    }
+                }
 			} else if (obj instanceof CpsUpperNode) {
 				val += getTotalProduction(((CpsUpperNode) obj).getNodes());
 			}

+ 502 - 578
src/ui/controller/LoadController.java

@@ -1,595 +1,519 @@
 package ui.controller;
 
-import java.awt.Point;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
+import classes.*;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParser;
+import org.apache.commons.compress.archivers.ArchiveEntry;
+import org.apache.commons.compress.archivers.ArchiveException;
+import org.apache.commons.compress.archivers.ArchiveInputStream;
+import org.apache.commons.compress.archivers.ArchiveStreamFactory;
+import org.apache.commons.compress.utils.IOUtils;
+import ui.model.Model;
+
+import java.awt.*;
+import java.io.*;
 import java.nio.file.Files;
 import java.nio.file.StandardCopyOption;
 import java.util.ArrayList;
 import java.util.HashMap;
-import java.util.Hashtable;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.stream.Collectors;
-import java.util.zip.ZipException;
-import org.apache.commons.compress.archivers.ArchiveEntry;
-import org.apache.commons.compress.archivers.ArchiveException;
-import org.apache.commons.compress.archivers.ArchiveInputStream;
-import org.apache.commons.compress.archivers.ArchiveStreamFactory;
-import org.apache.commons.compress.utils.IOUtils;
-
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import classes.Category;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.AbstractCpsObject;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounter;
-import classes.IdCounterElem;
-import ui.model.Model;
 
 /**
  * Controller for the Loading.
- * 
+ *
  * @author Gruppe14
  */
 public class LoadController {
-	/**
-	 * enum Mode.
-	 */
-	public enum MODE {
-		COMPLETE, PARTIAL, CATEGORY
-	}
-
-	public enum EDGETYPE {
-		CANVAS, CONNECTION, NODE, OLD
-	}
-
-	public enum GRAPHTYPE {
-		SWITCH, ELEMENT
-	}
-
-	private Model model;
-	private CategoryController cgC;
-	private CanvasController cvsC;
-	private ObjectController objC;
-	private NodeController uppC;
-	private MultiPurposeController mpC;
-	private JsonParser parser;
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param model
-	 *            Model
-	 * @param cg
-	 *            CategoryController
-	 * @param cvs
-	 *            CanvasController
-	 * @param obj
-	 *            ObjectController
-	 * @param mp
-	 *            MultiPurposeController
-	 */
-	public LoadController(Model model, CategoryController cg, CanvasController cvs, ObjectController obj,
-			NodeController uppC, MultiPurposeController mp) {
-		this.model = model;
-		this.cgC = cg;
-		this.cvsC = cvs;
-		this.objC = obj;
-		this.uppC = uppC;
-		this.mpC = mp;
-		this.parser = new JsonParser();
-	}
-
-	/**
-	 * Reads the the JSON File and load the state into the Model.
-	 * 
-	 * @param path
-	 *            the Path
-	 * @throws IOException
-	 *             exception
-	 */
-	public void readSave(String path) throws IOException, ArchiveException, ZipException {
-
-		File src = new File(path);
-		File folder = readArchive(path, src);
-		folder.deleteOnExit();
-		String trim = folder.getPath().substring(0,
-				folder.getPath().lastIndexOf(folder.getName()) + folder.getName().length());
-
-		forwardFiles(folder, trim);
-
-	}
-
-	public void readJson(String path) throws IOException {
-		JsonObject json = (JsonObject) parser.parse(new FileReader(path));
-		// get all keys via stream
-		List<String> keys = getKeys(json);
-		List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
-				.collect(Collectors.toCollection(ArrayList::new));
-
-		HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
-		HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
-
-		initialize(keys, json);
-		forwardObjects(keys, json, objDispatch, eleDispatch);
-		forwardEdges(edges, json, objDispatch);
-
-	}
-
-	/**
-	 * Loads the Files from the Savefile
-	 * 
-	 * @param folder
-	 * @param trim
-	 * @throws IOException
-	 */
-	private void forwardFiles(File folder, String trim) throws IOException {
-		// TODO Auto-generated method stub
-		for (File file : folder.listFiles()) {
-			File dst = new File(
-					System.getProperty("user.home") + "/.config/HolonGUI/" + file.getPath().replace(trim, ""));
-
-			if (file.getName().contains(".json"))
-				readJson(file.getPath());
-			else if (file.isDirectory())
-				forwardFiles(file, trim);
-			else {
-				dst.getParentFile().mkdirs();
-				Files.copy(file.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
-			}
-
-		}
-	}
-
-	/**
-	 * distribute the Edges
-	 * 
-	 * @param edges
-	 * @param json
-	 * @param objDispatch
-	 */
-	private void forwardEdges(List<String> edges, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-
-		List<String> conn = new ArrayList<>();
-
-		for (String edge : edges) {
-			if (edge.contains("CVSEDGE"))
-				loadEdge(EDGETYPE.CANVAS, json.get(edge), objDispatch);
-			if (edge.contains("CONNEDGE"))
-				conn.add(edge);
-			if (edge.contains("NODE"))
-				loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch);
-			if (edge.contains("OLD"))
-				loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch);
-		}
-
-		for (String edge : conn) {
-			loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch);
-		}
-
-	}
-
-	/**
-	 * Distribute the given keys for right processing
-	 * 
-	 * @param keys
-	 * @param json
-	 * @param objDispatch
-	 * @param eleDispatch
-	 */
-	private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-		for (String key : keys) {
-			if (key.contains("CATEGORY"))
-				loadCategory(json.get(key));
-			if (key.contains("CGOBJECT"))
-				loadCategoryObject(json.get(key));
-			if (key.contains("CGELEMENT"))
-				loadCategoryElements(json.get(key));
-			if (key.contains("CVSOBJECT"))
-				loadCanvasObject(json.get(key), objDispatch);
-			if (key.contains("CVSELEMENT"))
-				loadCanvasElements(json.get(key), objDispatch, eleDispatch);
-			if (key.contains("SWUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
-			if (key.contains("ELEUNITGRAPH"))
-				loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
-			if (key.contains("TRACKED"))
-				loadTracked(json.get(key), objDispatch);
-			if (key.contains("STATSGRAPH"))
-				loadStatisticGraph(json.get(key), objDispatch);
-		}
-
-	}
-
-	/**
-	 * Init the Global Parameters
-	 * 
-	 * @param keys
-	 * @param json
-	 */
-	private void initialize(List<String> keys, JsonObject json) {
-
-		switch (MODE.valueOf(json.get("MODE").getAsString())) {
-		case COMPLETE:
-			model.setCvsObjIdx(new HashMap<Integer, Integer>());
-			model.setObjectsOnCanvas(new ArrayList<AbstractCpsObject>());
-			model.setEdgesOnCanvas(new ArrayList<CpsEdge>());
-			model.setTrackingObj(new ArrayList<>());
-			model.setStatisticData(new ArrayList<>());
-			model.setHashcodeMap(new HashMap<>());
-			model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
-			model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
-			IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
-			IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
-			break;
-		case PARTIAL:
-			model.setCvsObjIdx(new HashMap<Integer, Integer>());
-			model.setObjectsOnCanvas(new ArrayList<AbstractCpsObject>());
-			model.setEdgesOnCanvas(new ArrayList<CpsEdge>());
-			model.setHashcodeMap(new HashMap<>());
-			model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
-			model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
-			IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
-			IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
-			break;
-		case CATEGORY:
-			model.setCgIdx(new HashMap<String, Integer>());
-			model.setCategories(new ArrayList<Category>());
-
-		default:
-			break;
-		}
-
-	}
-
-	/**
-	 * Load a given Category
-	 * 
-	 * @param jsonElement
-	 */
-	private void loadCategory(JsonElement jsonElement) {
-		// TODO Auto-generated method stub
-		if (mpC.searchCat(jsonElement.getAsString()) == null)
-			cgC.addCategory(new Category(jsonElement.getAsString()));
-	}
-
-	/**
-	 * Load a given Object in Category by Deserialization
-	 * 
-	 * @param jsonElement
-	 */
-	private void loadCategoryObject(JsonElement jsonElement) {
-		// TODO Auto-generated method stub
-
-		AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
-		temp.setImage(checkOS(temp.getImage()));
-		initObjects(temp);
-		if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getObjName()) != null)
-			cgC.deleteObject(temp.getSav(), temp.getObjName());
-		cgC.addObject(mpC.searchCat(temp.getSav()), temp);
-
-	}
-
-	/**
-	 * Load a given Element in Category by Deserialization
-	 * 
-	 * @param jsonElement
-	 */
-	private void loadCategoryElements(JsonElement jsonElement) {
-		// TODO Auto-generated method stub
-		HolonElement temp = model.getGson().fromJson(jsonElement.getAsJsonObject().get("properties").getAsJsonObject(),
-				HolonElement.class);
-		initElements(temp);
-		objC.addElementIntoCategoryObject(temp.getSaving().getKey(), temp.getSaving().getValue(), temp);
-	}
-
-	/**
-	 * Load a given Object in Canvas by Deserialization
-	 * 
-	 * @param jsonElement
-	 * @param objDispatch
-	 */
-	private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
-		initObjects(temp);
-		temp.setImage(checkOS(temp.getImage()));
-		if (temp instanceof CpsUpperNode) {
-			model.getHashcodeMap().put(jsonElement.getAsJsonObject().get("hash").getAsInt(), (CpsUpperNode) temp);
-			((CpsUpperNode) temp).setLeftBorder(jsonElement.getAsJsonObject().get("properties").getAsJsonObject().get("leftBorder").getAsInt());
-		}
-		// if its stored before on the canvas just put it there
-		if (temp.getSav().equals("CVS")) {
-			cvsC.addObject(temp);
-
-		} else {
-			// else look up the table and put it into the right Uppernode
-			CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(Integer.parseInt(temp.getSav()));
-			uppC.addObjectInUpperNode(temp, temp2);
-		}
-
-		objDispatch.put(temp.getId(), temp);
-
-	}
-
-	/**
-	 * Load a given Element in Canvas by Deserialization
-	 * 
-	 * @param jsonElement
-	 * @param objDispatch
-	 * @param eleDispatch
-	 */
-	private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-
-		JsonObject object = jsonElement.getAsJsonObject();
-
-		HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
-		initElements(temp);
-		// id which Object it was stored before
-		int stored = object.get("ID").getAsInt();
-		// lookup that object
-		HolonObject temp2 = (HolonObject) objDispatch.get(stored);
-		// add it
-		objC.addElement(temp2, temp);
-		// store element also inside a table
-		eleDispatch.put(temp.getId(), temp);
-	}
-
-	/**
-	 * Load a given Edge by Deserialization
-	 * 
-	 * @param type
-	 * @param jsonElement
-	 * @param objDispatch
-	 */
-	private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
-		initCpsEdge(temp);
-		// look for A and B inside the Table
-		temp.setA(objDispatch.get(object.get("A").getAsInt()));
-		temp.setB(objDispatch.get(object.get("B").getAsInt()));
-
-		int sav = 0;
-
-		switch (type) {
-		case CANVAS:
-			// if in canvas add it into the canvas but delete connection before
-			model.getEdgesOnCanvas().add(temp);
-			break;
-		case CONNECTION:
-			// if no duplicates in connection store them into the given A and B
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
-				temp.getA().getConnections().add(temp);
-			if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
-				temp.getB().getConnections().add(temp);
-			break;
-		case NODE:
-			// put it into given nodeofnode
-			sav = object.get("ID").getAsInt();
-			((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
-			break;
-		case OLD:
-			// same as above
-			sav = object.get("ID").getAsInt();
-			((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
-			break;
-		default:
-			break;
-		}
-
-		if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
-			temp.getA().getConnections().add(temp);
-			temp.getB().getConnections().add(temp);
-		}
-
-	}
-
-	/**
-	 * Load a Unitgraph by Deserialization
-	 * 
-	 * @param type
-	 * @param jsonElement
-	 * @param objDispatch
-	 * @param eleDispatch
-	 */
-	private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
-			HashMap<Integer, HolonElement> eleDispatch) {
-		// TODO Auto-generated method stub
-
-		JsonObject object = jsonElement.getAsJsonObject();
-		List<String> keys = getKeys(object);
-		String p = null;
-		int mid, x, y = 0;
-
-		LinkedList<Point> graphpoint = new LinkedList<>();
-		int sav = 0;
-		// foreach Point in the graph restore it
-		for (String k : keys) {
-			if (!k.equals("ID")) {
-				p = object.get(k).getAsString();
-				mid = p.indexOf(':');
-				x = Integer.parseInt(p.substring(0, mid));
-				y = Integer.parseInt(p.substring(mid + 1, p.length()));
-				graphpoint.add(new Point(x, y));
-			} else
-				// else its an ID
-				sav = object.get(k).getAsInt();
-
-		}
-
-		switch (type) {
-		case SWITCH:
-			HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
-			sw.setGraphPoints(graphpoint);
-			break;
-		case ELEMENT:
-			HolonElement ele = eleDispatch.get(sav);
-			ele.setGraphPoints(graphpoint);
-			break;
-		default:
-			break;
-		}
-	}
-
-	private void loadStatisticGraph(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		model.getGraphTable().clear();
-		model.getStatisticData().add(object);
-	}
-
-	private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
-		// TODO Auto-generated method stub
-		JsonObject object = jsonElement.getAsJsonObject();
-		List<String> keys = getKeys(object);
-
-		for (String k : keys) {
-			int id = object.get(k).getAsInt();
-			model.getTrackingObj().add(objDispatch.get(id));
-			model.addObjectsToGraphListeners();
-			if (objDispatch.get(id) instanceof HolonObject) {
-				((HolonObject) objDispatch.get(id)).updateTrackingInfo();
-			}
-		}
-
-	}
-
-	private File readArchive(String path, File src) throws IOException, ArchiveException {
-		File tmp = Files.createTempDirectory("tmpHolon").toFile();
-		tmp.deleteOnExit();
-		InputStream input = new FileInputStream(src);
-		ArchiveInputStream stream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
-				input);
-
-		ArchiveEntry entry = stream.getNextEntry();
-		while (entry != null) {
-			// String entryName = checkOS(entry.getName());
-			File file = new File(tmp, entry.getName());
-			file.getParentFile().mkdirs();
-			OutputStream output = new FileOutputStream(file);
-			IOUtils.copy(stream, output);
-			output.close();
-			// file.createNewFile();
-			entry = stream.getNextEntry();
-		}
-
-		stream.close();
-		input.close();
-
-		return tmp;
-	}
-
-	private String checkOS(String entryName) {
-		// TODO Auto-generated method stub
-		String os = System.getProperty("os.name").toLowerCase();
-		String ret = entryName;
-		String partition = System.getProperty("user.home");
-
-		if (!ret.contains("HolonGUI"))
-			return ret;
-
-		if (os.contains("windows")) {
-			ret = ret.replace("/", "\\");
-			ret = System.getProperty("user.home") + "\\.config"
-					+ ret.substring(ret.indexOf("\\HolonGUI\\"), ret.length());
-
-		}
-		if (os.contains("mac")) {
-			// dosmth
-			ret = ret.replace("\\", "/");
-			ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
-		}
-		if (os.contains("linux")) {
-			// dosmth
-			ret = ret.replace("\\", "/");
-			ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
-		}
-		if (os.contains("solaris")) {
-			// dosmth
-		}
-		return ret;
-	}
-
-	/**
-	 * Init new Arrays which havent been serialized along the object
-	 * 
-	 * @param obj
-	 */
-	public void initObjects(AbstractCpsObject obj) {
-
-		obj.setConnections(new ArrayList<CpsEdge>());
-		obj.setTags(new ArrayList<Integer>());
-		obj.setPseudoTags(new ArrayList<Integer>());
-
-		if (obj instanceof HolonObject) {
-			((HolonObject) obj).setElements(new ArrayList<HolonElement>());
-
-			((HolonObject) obj).setTrackingProd(new float[100]);
-			((HolonObject) obj).setTrackingCons(new float[100]);
-		}
-
-		if (obj instanceof HolonSwitch) {
-			((HolonSwitch) obj).setActiveAt(true);
-			((HolonSwitch) obj).setGraphPoints(new LinkedList<Point>());
-		}
-
-		if (obj instanceof CpsUpperNode) {
-			((CpsUpperNode) obj).setNodes(new ArrayList<AbstractCpsObject>());
-			((CpsUpperNode) obj).setNodeEdges(new ArrayList<CpsEdge>());
-			((CpsUpperNode) obj).setOldEdges(new ArrayList<CpsEdge>());
-			((CpsUpperNode) obj).setNodesIdx(new HashMap<Integer, Integer>());
-		}
-	}
-
-	/**
-	 * Init Elements
-	 * 
-	 * @param ele
-	 */
-	public void initElements(HolonElement ele) {
-
-		ele.setEnergyAt(ele.getEnergy());
-		ele.setGraphPoints(new LinkedList<Point>());
-	}
-
-	/**
-	 * Init Edges
-	 * 
-	 * @param edge
-	 */
-	public void initCpsEdge(CpsEdge edge) {
-		edge.setTags(new ArrayList<Integer>());
-		edge.setPseudoTag(new ArrayList<Integer>());
-		edge.setA(null);
-		edge.setB(null);
-	}
-
-	/**
-	 * Get Set of Keys
-	 * 
-	 * @param json
-	 * @return
-	 */
-	public List<String> getKeys(JsonObject json) {
-		return json.entrySet().stream().map(i -> i.getKey()).collect(Collectors.toCollection(ArrayList::new));
-	}
+    private Model model;
+    private CategoryController cgC;
+    private CanvasController cvsC;
+    private ObjectController objC;
+    private NodeController uppC;
+    private MultiPurposeController mpC;
+    private JsonParser parser;
+
+    /**
+     * Constructor.
+     *
+     * @param model Model
+     * @param cg    CategoryController
+     * @param cvs   CanvasController
+     * @param obj   ObjectController
+     * @param mp    MultiPurposeController
+     */
+    LoadController(Model model, CategoryController cg, CanvasController cvs, ObjectController obj,
+                   NodeController uppC, MultiPurposeController mp) {
+        this.model = model;
+        this.cgC = cg;
+        this.cvsC = cvs;
+        this.objC = obj;
+        this.uppC = uppC;
+        this.mpC = mp;
+        this.parser = new JsonParser();
+    }
+
+    /**
+     * Reads the the JSON File and load the state into the Model.
+     *
+     * @param path the Path
+     * @throws IOException exception
+     */
+    void readSave(String path) throws IOException, ArchiveException {
+
+        File src = new File(path);
+        File folder = readArchive(src);
+        folder.deleteOnExit();
+        String trim = folder.getPath().substring(0,
+                folder.getPath().lastIndexOf(folder.getName()) + folder.getName().length());
+
+        forwardFiles(folder, trim);
+
+    }
+
+    void readJson(String path) throws IOException {
+        JsonObject json = (JsonObject) parser.parse(new FileReader(path));
+        // get all keys via stream
+        List<String> keys = getKeys(json);
+        List<String> edges = keys.stream().filter(key -> key.contains("EDGE"))
+                .collect(Collectors.toCollection(ArrayList::new));
+
+        HashMap<Integer, AbstractCpsObject> objDispatch = new HashMap<>();
+        HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
+
+        initialize(json);
+        forwardObjects(keys, json, objDispatch, eleDispatch);
+        forwardEdges(edges, json, objDispatch);
+
+    }
+
+    /**
+     * Loads the Files from the Savefile
+     *
+     * @param trim the part of the file's path to be trimmed
+     * @throws IOException if anythings goes wrong reading the files
+     */
+    private void forwardFiles(File folder, String trim) throws IOException {
+        for (File file : folder.listFiles()) {
+            File dst = new File(
+                    System.getProperty("user.home") + "/.config/HolonGUI/" + file.getPath().replace(trim, ""));
+
+            if (file.getName().contains(".json"))
+                readJson(file.getPath());
+            else if (file.isDirectory())
+                forwardFiles(file, trim);
+            else {
+                dst.getParentFile().mkdirs();
+                Files.copy(file.toPath(), dst.toPath(), StandardCopyOption.REPLACE_EXISTING);
+            }
+
+        }
+    }
+
+    /**
+     * distribute the Edges
+     */
+    private void forwardEdges(List<String> edges, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch) {
+
+        List<String> conn = new ArrayList<>();
+
+        for (String edge : edges) {
+            if (edge.contains("CVSEDGE"))
+                loadEdge(EDGETYPE.CANVAS, json.get(edge), objDispatch);
+            if (edge.contains("CONNEDGE"))
+                conn.add(edge);
+            if (edge.contains("NODE"))
+                loadEdge(EDGETYPE.NODE, json.get(edge), objDispatch);
+            if (edge.contains("OLD"))
+                loadEdge(EDGETYPE.OLD, json.get(edge), objDispatch);
+        }
+
+        for (String edge : conn) {
+            loadEdge(EDGETYPE.CONNECTION, json.get(edge), objDispatch);
+        }
+
+    }
+
+    /**
+     * Distribute the given keys for right processing
+     */
+    private void forwardObjects(List<String> keys, JsonObject json, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                HashMap<Integer, HolonElement> eleDispatch) {
+        for (String key : keys) {
+            if (key.contains("CATEGORY"))
+                loadCategory(json.get(key));
+            if (key.contains("CGOBJECT"))
+                loadCategoryObject(json.get(key));
+            if (key.contains("CGELEMENT"))
+                loadCategoryElements(json.get(key));
+            if (key.contains("CVSOBJECT"))
+                loadCanvasObject(json.get(key), objDispatch);
+            if (key.contains("CVSELEMENT"))
+                loadCanvasElements(json.get(key), objDispatch, eleDispatch);
+            if (key.contains("SWUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
+            if (key.contains("ELEUNITGRAPH"))
+                loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
+            if (key.contains("TRACKED"))
+                loadTracked(json.get(key), objDispatch);
+            if (key.contains("STATSGRAPH"))
+                loadStatisticGraph(json.get(key));
+        }
+
+    }
+
+    /**
+     * Init the Global Parameters
+     */
+    private void initialize(JsonObject json) {
+
+        switch (MODE.valueOf(json.get("MODE").getAsString())) {
+            case COMPLETE:
+                model.setCvsObjIdx(new HashMap<>());
+                model.setObjectsOnCanvas(new ArrayList<>());
+                model.setEdgesOnCanvas(new ArrayList<>());
+                model.setTrackingObj(new ArrayList<>());
+                model.setStatisticData(new ArrayList<>());
+                model.setHashcodeMap(new HashMap<>());
+                model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
+                model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
+                IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
+                IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
+                break;
+            case PARTIAL:
+                model.setCvsObjIdx(new HashMap<>());
+                model.setObjectsOnCanvas(new ArrayList<>());
+                model.setEdgesOnCanvas(new ArrayList<>());
+                model.setHashcodeMap(new HashMap<>());
+                model.setCanvasX(json.get("CANVAS_SIZE_X").getAsInt());
+                model.setCanvasX(json.get("CANVAS_SIZE_Y").getAsInt());
+                IdCounter.setCounter(json.get("IDCOUNTER").getAsInt());
+                IdCounterElem.setCounter(json.get("IDCOUNTERELEMENT").getAsInt());
+                break;
+            case CATEGORY:
+                model.setCgIdx(new HashMap<>());
+                model.setCategories(new ArrayList<>());
+
+            default:
+                break;
+        }
+
+    }
+
+    /**
+     * Load a given Category
+     */
+    private void loadCategory(JsonElement jsonElement) {
+        if (mpC.searchCat(jsonElement.getAsString()) == null)
+            cgC.addCategory(new Category(jsonElement.getAsString()));
+    }
+
+    /**
+     * Load a given Object in Category by Deserialization
+     */
+    private void loadCategoryObject(JsonElement jsonElement) {
+        AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
+        temp.setImage(checkOS(temp.getImage()));
+        initObjects(temp);
+        if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getObjName()) != null)
+            cgC.deleteObject(temp.getSav(), temp.getObjName());
+        cgC.addObject(mpC.searchCat(temp.getSav()), temp);
+
+    }
+
+    /**
+     * Load a given Element in Category by Deserialization
+     */
+    private void loadCategoryElements(JsonElement jsonElement) {
+        HolonElement temp = model.getGson().fromJson(jsonElement.getAsJsonObject().get("properties").getAsJsonObject(),
+                HolonElement.class);
+        initElements(temp);
+        objC.addElementIntoCategoryObject(temp.getSaving().getKey(), temp.getSaving().getValue(), temp);
+    }
+
+    /**
+     * Load a given Object in Canvas by Deserialization
+     */
+    private void loadCanvasObject(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
+        AbstractCpsObject temp = model.getGson().fromJson(jsonElement.getAsJsonObject(), AbstractCpsObject.class);
+        initObjects(temp);
+        temp.setImage(checkOS(temp.getImage()));
+        if (temp instanceof CpsUpperNode) {
+            model.getHashcodeMap().put(jsonElement.getAsJsonObject().get("hash").getAsInt(), (CpsUpperNode) temp);
+            ((CpsUpperNode) temp).setLeftBorder(jsonElement.getAsJsonObject().get("properties").getAsJsonObject().get("leftBorder").getAsInt());
+        }
+        // if its stored before on the canvas just put it there
+        if (temp.getSav().equals("CVS")) {
+            cvsC.addObject(temp);
+
+        } else {
+            // else look up the table and put it into the right Uppernode
+            CpsUpperNode temp2 = (CpsUpperNode) objDispatch.get(Integer.parseInt(temp.getSav()));
+            uppC.addObjectInUpperNode(temp, temp2);
+        }
+
+        objDispatch.put(temp.getId(), temp);
+
+    }
+
+    /**
+     * Load a given Element in Canvas by Deserialization
+     */
+    private void loadCanvasElements(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                                    HashMap<Integer, HolonElement> eleDispatch) {
+
+        JsonObject object = jsonElement.getAsJsonObject();
+
+        HolonElement temp = model.getGson().fromJson(object.get("properties"), HolonElement.class);
+        initElements(temp);
+        // id which Object it was stored before
+        int stored = object.get("ID").getAsInt();
+        // lookup that object
+        HolonObject temp2 = (HolonObject) objDispatch.get(stored);
+        // add it
+        objC.addElement(temp2, temp);
+        // store element also inside a table
+        eleDispatch.put(temp.getId(), temp);
+    }
+
+    /**
+     * Load a given Edge by Deserialization
+     */
+    private void loadEdge(EDGETYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        CpsEdge temp = model.getGson().fromJson(object.get("properties"), CpsEdge.class);
+        initCpsEdge(temp);
+        // look for A and B inside the Table
+        temp.setA(objDispatch.get(object.get("A").getAsInt()));
+        temp.setB(objDispatch.get(object.get("B").getAsInt()));
+
+        int sav;
+
+        switch (type) {
+            case CANVAS:
+                // if in canvas add it into the canvas but delete connection before
+                model.getEdgesOnCanvas().add(temp);
+                break;
+            case CONNECTION:
+                // if no duplicates in connection store them into the given A and B
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getA().getConnections()))
+                    temp.getA().getConnections().add(temp);
+                if (!uppC.lookforDuplicates(temp.getA(), temp.getB(), temp.getB().getConnections()))
+                    temp.getB().getConnections().add(temp);
+                break;
+            case NODE:
+                // put it into given nodeofnode
+                sav = object.get("ID").getAsInt();
+                ((CpsUpperNode) objDispatch.get(sav)).getNodeEdges().add(temp);
+                break;
+            case OLD:
+                // same as above
+                sav = object.get("ID").getAsInt();
+                ((CpsUpperNode) objDispatch.get(sav)).getOldEdges().add(temp);
+                break;
+            default:
+                break;
+        }
+
+        if (object.get("connection").getAsBoolean() && !type.equals(EDGETYPE.CONNECTION)) {
+            temp.getA().getConnections().add(temp);
+            temp.getB().getConnections().add(temp);
+        }
+
+    }
+
+    /**
+     * Load a Unitgraph by Deserialization
+     */
+    private void loadUnitGraph(GRAPHTYPE type, JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch,
+                               HashMap<Integer, HolonElement> eleDispatch) {
+
+        JsonObject object = jsonElement.getAsJsonObject();
+        List<String> keys = getKeys(object);
+        String p;
+        int mid, x, y;
+
+        LinkedList<Point> graphpoint = new LinkedList<>();
+        int sav = 0;
+        // foreach Point in the graph restore it
+        for (String k : keys) {
+            if (!k.equals("ID")) {
+                p = object.get(k).getAsString();
+                mid = p.indexOf(':');
+                x = Integer.parseInt(p.substring(0, mid));
+                y = Integer.parseInt(p.substring(mid + 1, p.length()));
+                graphpoint.add(new Point(x, y));
+            } else
+                // else its an ID
+                sav = object.get(k).getAsInt();
+
+        }
+
+        switch (type) {
+            case SWITCH:
+                HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
+                sw.setGraphPoints(graphpoint);
+                break;
+            case ELEMENT:
+                HolonElement ele = eleDispatch.get(sav);
+                ele.setGraphPoints(graphpoint);
+                break;
+            default:
+                break;
+        }
+    }
+
+    private void loadStatisticGraph(JsonElement jsonElement) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        model.getGraphTable().clear();
+        model.getStatisticData().add(object);
+    }
+
+    private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCpsObject> objDispatch) {
+        JsonObject object = jsonElement.getAsJsonObject();
+        List<String> keys = getKeys(object);
+
+        for (String k : keys) {
+            int id = object.get(k).getAsInt();
+            model.getTrackingObj().add(objDispatch.get(id));
+            model.addObjectsToGraphListeners();
+            if (objDispatch.get(id) instanceof HolonObject) {
+                ((HolonObject) objDispatch.get(id)).updateTrackingInfo();
+            }
+        }
+
+    }
+
+    private File readArchive(File src) throws IOException, ArchiveException {
+        File tmp = Files.createTempDirectory("tmpHolon").toFile();
+        tmp.deleteOnExit();
+        InputStream input = new FileInputStream(src);
+        ArchiveInputStream stream = new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.ZIP,
+                input);
+
+        ArchiveEntry entry = stream.getNextEntry();
+        while (entry != null) {
+            // String entryName = checkOS(entry.getName());
+            File file = new File(tmp, entry.getName());
+            file.getParentFile().mkdirs();
+            OutputStream output = new FileOutputStream(file);
+            IOUtils.copy(stream, output);
+            output.close();
+            // file.createNewFile();
+            entry = stream.getNextEntry();
+        }
+
+        stream.close();
+        input.close();
+
+        return tmp;
+    }
+
+    private String checkOS(String entryName) {
+        String os = System.getProperty("os.name").toLowerCase();
+        String ret = entryName;
+//        String partition = System.getProperty("user.home");
+
+        if (!ret.contains("HolonGUI"))
+            return ret;
+
+        if (os.contains("windows")) {
+            ret = ret.replace("/", "\\");
+            ret = System.getProperty("user.home") + "\\.config"
+                    + ret.substring(ret.indexOf("\\HolonGUI\\"), ret.length());
+
+        }
+        if (os.contains("mac")) {
+            // dosmth
+            ret = ret.replace("\\", "/");
+            ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
+        }
+        if (os.contains("linux")) {
+            // dosmth
+            ret = ret.replace("\\", "/");
+            ret = System.getProperty("user.home") + "/.config" + ret.substring(ret.indexOf("/HolonGUI/"), ret.length());
+        }
+//        if (os.contains("solaris")) {
+//            // dosmth
+//        }
+        return ret;
+    }
+
+    /**
+     * Init new Arrays which haven't been serialized along the object
+     */
+    void initObjects(AbstractCpsObject obj) {
+
+        obj.setConnections(new ArrayList<>());
+        obj.setTags(new ArrayList<>());
+        obj.setPseudoTags(new ArrayList<>());
+
+        if (obj instanceof HolonObject) {
+            ((HolonObject) obj).setElements(new ArrayList<>());
+
+            ((HolonObject) obj).setTrackingProd(new float[100]);
+            ((HolonObject) obj).setTrackingCons(new float[100]);
+        }
+
+        if (obj instanceof HolonSwitch) {
+            ((HolonSwitch) obj).setActiveAt(true);
+            ((HolonSwitch) obj).setGraphPoints(new LinkedList<>());
+        }
+
+        if (obj instanceof CpsUpperNode) {
+            ((CpsUpperNode) obj).setNodes(new ArrayList<>());
+            ((CpsUpperNode) obj).setNodeEdges(new ArrayList<>());
+            ((CpsUpperNode) obj).setOldEdges(new ArrayList<>());
+            ((CpsUpperNode) obj).setNodesIdx(new HashMap<>());
+        }
+    }
+
+    /**
+     * Init Elements (set available energy, set new graph points)
+     *
+     * @param ele the element to be initialized
+     */
+    void initElements(HolonElement ele) {
+        ele.setAvailableEnergyPerElementAt(ele.getEnergyPerElement());
+        ele.setGraphPoints(new LinkedList<>());
+    }
+
+    /**
+     * Init Edges (set tags and reset source and target)
+     *
+     * @param edge the edge to be initialized
+     */
+    void initCpsEdge(CpsEdge edge) {
+        edge.setTags(new ArrayList<>());
+        edge.setPseudoTag(new ArrayList<>());
+        edge.setA(null);
+        edge.setB(null);
+    }
+
+    /**
+     * Get Set of Keys
+     *
+     * @return the keys from the json object
+     */
+    List<String> getKeys(JsonObject json) {
+        return json.entrySet().stream().map(i -> i.getKey()).collect(Collectors.toCollection(ArrayList::new));
+    }
+
+    /**
+     * enum Mode.
+     */
+    public enum MODE {
+        COMPLETE, PARTIAL, CATEGORY
+    }
+
+    public enum EDGETYPE {
+        CANVAS, CONNECTION, NODE, OLD
+    }
+
+    public enum GRAPHTYPE {
+        SWITCH, ELEMENT
+    }
 
 }

+ 30 - 92
src/ui/controller/NodeController.java

@@ -1,36 +1,33 @@
 package ui.controller;
 
-import java.awt.Point;
-import java.util.ArrayList;
-import java.util.Iterator;
-
 import classes.AbstractCpsObject;
 import classes.CpsEdge;
 import classes.CpsUpperNode;
 import classes.Position;
 import ui.model.Model;
 
-public class NodeController {
+import java.awt.*;
+import java.util.ArrayList;
+import java.util.Iterator;
+
+
+class NodeController {
 
 	private Model model;
 	private CanvasController cvs;
 	private MultiPurposeController mpC;
 	private Point point;
 
-	public NodeController(Model model, CanvasController cvs, MultiPurposeController mpC) {
-		// TODO Auto-generated constructor stub
-		this.model = model;
+    NodeController(Model model, CanvasController cvs, MultiPurposeController mpC) {
+        this.model = model;
 		this.cvs = cvs;
 		this.mpC = mpC;
 	}
 
 	/**
 	 * Add a CpsUpperNode into Canvas
-	 * 
-	 * @param nodeName
-	 * @param upperNode
 	 */
-	public void doUpperNode(String nodeName, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
+    void doUpperNode(String nodeName, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
 
 		CpsUpperNode node = new CpsUpperNode(nodeName);
 		node.setPosition(calculatePos(toGroup));
@@ -46,11 +43,8 @@ public class NodeController {
 
 	/**
 	 * Delete a CpsUpperNode from the Canvas
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
-	public void undoUpperNode(CpsUpperNode node, CpsUpperNode upperNode) {
+    void undoUpperNode(CpsUpperNode node, CpsUpperNode upperNode) {
 
 		Position old = calculatePos(node.getNodes());
 		Position p = node.getPosition();
@@ -67,9 +61,6 @@ public class NodeController {
 
 	/**
 	 * Put selected Nodes inside the Upper Node
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void makeNodeOfNodes(CpsUpperNode node, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
 
@@ -77,18 +68,13 @@ public class NodeController {
 		ArrayList<CpsEdge> toDelete = new ArrayList<>();
 
 		// Put all selected Nodes into the Upper Node
-		for (Iterator<AbstractCpsObject> it = toGroup.iterator(); it.hasNext();) {
-
-			// füge Neue Objecte in Neuen Node hinzu
-			AbstractCpsObject obj = it.next();
+        for (AbstractCpsObject obj : toGroup) {
+            // füge Neue Objecte in Neuen Node hinzu
 			addObjectInUpperNode(obj, node);
 		}
 
 		// Füge die Edges die Alle Objekte vorher verbunden hat in neuen Node
-		for (Iterator<CpsEdge> it = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())
-				.iterator(); it.hasNext();) {
-
-			CpsEdge edge = it.next();
+        for (CpsEdge edge : (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges())) {
 
 			// kopiere edge in UpperNode
 			if (nodes.contains(edge.getA()) && nodes.contains(edge.getB())) {
@@ -113,12 +99,8 @@ public class NodeController {
 	/**
 	 * Transfer all relevant data from Node into the next higher layer of Node
 	 * (upperNode)
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void unmakeNodesOfNodes(CpsUpperNode node, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
 		// add all nodes into upperNode
 
 		for (CpsEdge edge : node.getConnections()) {
@@ -149,9 +131,6 @@ public class NodeController {
 	/**
 	 * Look for adjacent Nodes connected with the new CpsUpperNode and make
 	 * Connections
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void makeAdjacent(CpsUpperNode node, CpsUpperNode upperNode, ArrayList<AbstractCpsObject> toGroup) {
 
@@ -213,12 +192,8 @@ public class NodeController {
 
 	/**
 	 * Restore the Old Connections from the adjacent Object
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void unmakeAdjacent(CpsUpperNode node, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
 		ArrayList<CpsEdge> toDelete = new ArrayList<>();
 		ArrayList<CpsEdge> lostEdges = new ArrayList<>();
 		ArrayList<CpsEdge> foundEdges = (upperNode == null ? model.getEdgesOnCanvas() : upperNode.getNodeEdges());
@@ -227,10 +202,8 @@ public class NodeController {
 				: upperNode.getNodes());
 
 		// für jede Edge aus upperNode die Node enthält tu sie in toDelete
-		for (Iterator<CpsEdge> it = foundEdges.iterator(); it.hasNext();) {
-
-			CpsEdge edge = it.next();
-			if (edge.getA().equals(node) || edge.getB().equals(node))
+        for (CpsEdge edge : foundEdges) {
+            if (edge.getA().equals(node) || edge.getB().equals(node))
 				toDelete.add(edge);
 
 		}
@@ -315,14 +288,9 @@ public class NodeController {
 
 	/**
 	 * Just checking if an Egde already exists
-	 * 
-	 * @param a
-	 * @param b
-	 * @param list
-	 * @return
 	 */
-	public boolean lookforDuplicates(AbstractCpsObject a, AbstractCpsObject b, ArrayList<CpsEdge> list) {
-		for (CpsEdge cpsEdge : list) {
+    boolean lookforDuplicates(AbstractCpsObject a, AbstractCpsObject b, ArrayList<CpsEdge> list) {
+        for (CpsEdge cpsEdge : list) {
 			if ((a.equals(cpsEdge.getA()) && b.equals(cpsEdge.getB()))
 					|| (b.equals(cpsEdge.getA()) && a.equals(cpsEdge.getB())))
 				return true;
@@ -332,9 +300,6 @@ public class NodeController {
 
 	/**
 	 * Backups Old Edges into next lower layer in Current UpperNode anymore
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void backupOldEdges(CpsUpperNode node, CpsUpperNode upperNode) {
 
@@ -384,9 +349,6 @@ public class NodeController {
 
 	/**
 	 * Restore Old Edges into next higher layer of UpperNode
-	 * 
-	 * @param node
-	 * @param upperNode
 	 */
 	private void restoreOldEdges(CpsUpperNode node, CpsUpperNode upperNode) {
 
@@ -418,10 +380,8 @@ public class NodeController {
 
 	/**
 	 * Calculate new Position of the Upper Node
-	 * 
-	 * @return
 	 */
-	public Position calculatePos(ArrayList<AbstractCpsObject> toGroup) {
+    Position calculatePos(ArrayList<AbstractCpsObject> toGroup) {
 
 		Position pos = new Position(0, 0);
 
@@ -438,8 +398,6 @@ public class NodeController {
 
 	/**
 	 * Removes the Given Obj from current Layer and adjusts the idx
-	 * @param obj
-	 * @param upperNode
 	 */
 	private void removeForNodeOfNode(AbstractCpsObject obj, CpsUpperNode upperNode) {
 
@@ -481,24 +439,18 @@ public class NodeController {
 
 	/**
 	 * Add a Object into a CpsUpperNode
-	 * 
-	 * @param object
-	 * @param upperNode
 	 */
-	public void addObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
-		object.setSav("" + upperNode.getId());
+    void addObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
+        object.setSav("" + upperNode.getId());
 		upperNode.getNodesIdx().put(object.getId(), upperNode.getNodes().size());
 		upperNode.getNodes().add(object);
 	}
 
 	/**
 	 * Delete a AbstactCpsObject from CPSUpperNode
-	 * 
-	 * @param object
-	 * @param upperNode
 	 */
-	public void deleteObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
-		CpsEdge e = null;
+    void deleteObjectInUpperNode(AbstractCpsObject object, CpsUpperNode upperNode) {
+        CpsEdge e = null;
 		for (AbstractCpsObject cps : upperNode.getNodes()) {
 			for (CpsEdge p : cps.getConnections()) {
 				if (p.getA() == object || p.getB() == object) {
@@ -518,22 +470,16 @@ public class NodeController {
 
 	/**
 	 * Add Edge in UpperNode
-	 * 
-	 * @param edge
-	 * @param upperNode
 	 */
-	public void addEdge(CpsEdge edge, CpsUpperNode upperNode) {
-		upperNode.getNodeEdges().add(edge);
+    void addEdge(CpsEdge edge, CpsUpperNode upperNode) {
+        upperNode.getNodeEdges().add(edge);
 	}
 
 	/**
 	 * Delete Edge in UpperNode
-	 * 
-	 * @param edge
-	 * @param upperNode
 	 */
-	public void deleteEdge(CpsEdge edge, CpsUpperNode upperNode) {
-		edge.getA().getConnections().remove(edge);
+    void deleteEdge(CpsEdge edge, CpsUpperNode upperNode) {
+        edge.getA().getConnections().remove(edge);
 		edge.getB().getConnections().remove(edge);
 		upperNode.getNodeEdges().remove(edge);
 		if (edge.getA() instanceof CpsUpperNode || edge.getB() instanceof CpsUpperNode)
@@ -542,23 +488,18 @@ public class NodeController {
 
 	/**
 	 * Connect Objects outside of current Layer to Objects inside the Layer
-	 * 
-	 * @param a
-	 * @param b
 	 */
-	public void connectNodes(CpsEdge edge, CpsUpperNode upperNode) {
-		// keine Connections nötig, da automatisch erzeugt bei Instanziierung
+    void connectNodes(CpsEdge edge, CpsUpperNode upperNode) {
+        // keine Connections nötig, da automatisch erzeugt bei Instanziierung
 		// mache diese Edge auch in OldEdges rein des aktuellen CpsUpperNodes
 		upperNode.getOldEdges().add(edge);
 	}
 	
 	/**
 	 * Disconnect Objects outside of current Layer to Objects inside the Layer
-	 * @param edge
-	 * @param upperNode
 	 */
-	public void disconnectNodes(CpsEdge edge, CpsUpperNode upperNode) {
-		edge.getA().getConnections().remove(edge);
+    void disconnectNodes(CpsEdge edge, CpsUpperNode upperNode) {
+        edge.getA().getConnections().remove(edge);
 		edge.getB().getConnections().remove(edge);
 		if (upperNode != null)
 			upperNode.getOldEdges().remove(edge);
@@ -566,11 +507,8 @@ public class NodeController {
 	
 	/**
 	 * If Position is out of boundaries adjust it
-	 * @param temp
-	 * @param upperNode
 	 */
 	private void updatePosition(AbstractCpsObject temp, CpsUpperNode upperNode) {
-		// TODO Auto-generated method stub
 		int x = temp.getPosition().x - point.x;
 		int y = temp.getPosition().y - point.y;
 

+ 44 - 122
src/ui/controller/SaveController.java

@@ -1,51 +1,19 @@
 package ui.controller;
 
-import java.awt.Color;
-import java.awt.Point;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
+import classes.*;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
 import org.apache.commons.compress.archivers.ArchiveException;
 import org.apache.commons.compress.archivers.ArchiveOutputStream;
 import org.apache.commons.compress.archivers.ArchiveStreamFactory;
 import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
 import org.apache.commons.compress.utils.IOUtils;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonPrimitive;
-
-import TypeAdapter.AbstractCpsObjectAdapter;
-import TypeAdapter.ColorAdapter;
-import TypeAdapter.PositionAdapter;
-import classes.AbstractCpsObject;
-import classes.Category;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounter;
-import classes.IdCounterElem;
-import classes.Position;
-import classes.TrackedDataSet;
 import ui.model.Model;
-import ui.view.StatisticGraph;
-import ui.view.StatisticGraphPanel;
+
+import java.awt.*;
+import java.io.*;
+import java.util.*;
+import java.util.List;
 
 /**
  * Controller for Storage.
@@ -54,50 +22,30 @@ import ui.view.StatisticGraphPanel;
  */
 public class SaveController {
 
-	public enum MODE {
-		COMPLETE, PARTIAL, CATEGORY
-	}
-
-	public enum TYPE {
-		CATEGORY, CANVAS
-	}
-
-	public enum EDGETYPE {
-		CANVAS, CONNECTION, NODE, OLD, LAYER
-	}
-
-	public enum NUMTYPE {
-		CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
-	}
-
-	public enum GRAPHTYPE {
-		SWITCH, ELEMENT
-	}
-
 	private Model model;
 	private int nCat, nObj, nEle, nEdge, nConn, nNodeEdge, nOldEdge, nUnitGraph, nStatsGraph;
 
 	/**
 	 * Constructor.
-	 * 
+	 *
 	 * @param model
 	 *            the Model
 	 */
-	public SaveController(Model model) {
+	SaveController(Model model) {
 		this.model = model;
 	}
 
 	/**
 	 * Writes the current State of the Modelling into a JSON File which can be
 	 * loaded.
-	 * 
+	 *
 	 * @param path
 	 *            the Path
-	 * 
+	 *
 	 * @throws IOException
 	 *             exception
 	 */
-	public void writeSave(String path) throws IOException, ArchiveException {
+	void writeSave(String path) throws IOException, ArchiveException {
 
 		File dst = new File(path);
 		File holonFile = File.createTempFile("tmp", ".json");
@@ -130,13 +78,13 @@ public class SaveController {
 
 	/**
 	 * Writes the Autosave File.
-	 * 
+	 *
 	 * @param path
 	 *            the Path
 	 * @throws IOException
 	 *             Exception
 	 */
-	public void writeAutosave(String path) throws IOException {
+	void writeAutosave(String path) throws IOException {
 
 		initNumeration();
 		JsonObject file = new JsonObject();
@@ -152,11 +100,8 @@ public class SaveController {
 
 	/**
 	 * Writes the Category File in Case of Changes
-	 * 
-	 * @param path
-	 * @throws IOException
 	 */
-	public void writeCategory(String path) throws IOException {
+	void writeCategory(String path) throws IOException {
 
 		initNumeration();
 		JsonObject file = new JsonObject();
@@ -174,12 +119,8 @@ public class SaveController {
 	/**
 	 * Write needed default parameter into the JsonObject. Can be extended later
 	 * on
-	 * 
-	 * @param mode
-	 * @param file
 	 */
 	private void initialize(MODE mode, JsonObject file) {
-		// TODO Auto-generated method stub
 		switch (mode) {
 		case COMPLETE:
 			file.add("MODE", new JsonPrimitive(mode.name()));
@@ -205,11 +146,8 @@ public class SaveController {
 
 	/**
 	 * Store all Categories and Object into a Json File via Serialization
-	 * 
-	 * @param file
 	 */
 	private void storeCategory(JsonObject file) {
-		// TODO Auto-generated method stub
 		// forall categories store them into the jsontree
 		for (Category cat : model.getCategories()) {
 			String key = "CATEGORY" + getNumerator(NUMTYPE.CATEGORY);
@@ -228,11 +166,8 @@ public class SaveController {
 
 	/**
 	 * Travers through all Objects via BFS and Stores everything relevant
-	 * 
-	 * @param file
 	 */
 	private void storeCanvas(JsonObject file) {
-		// TODO Auto-generated method stub
 		ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
 		AbstractCpsObject u = null;
 		// put all objects into queue since there is not starting object
@@ -278,12 +213,8 @@ public class SaveController {
 
 	/**
 	 * Save wanted Data
-	 * 
-	 * @param stream
-	 * @throws IOException
 	 */
 	private void storeData(ArchiveOutputStream stream) throws IOException {
-		// TODO Auto-generated method stub
 		File images = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images");
 		File background = new File(System.getProperty("user.home") + "/.config/HolonGUI/BackgroundImages");
 		addFilesToSave(images, stream);
@@ -293,14 +224,8 @@ public class SaveController {
 
 	/**
 	 * Stores Category or Canvas Elements into Json
-	 * 
-	 * @param type
-	 * @param gson
-	 * @param file
-	 * @param obj
 	 */
-	public void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
-		// TODO Auto-generated method stub
+	void elementsToJson(TYPE type, JsonObject file, AbstractCpsObject obj) {
 		JsonObject temp = new JsonObject();
 		String key = null;
 		// forall elements store them into json and include the id of the object
@@ -329,10 +254,8 @@ public class SaveController {
 
 	/**
 	 * Put the UnitGraphs of Switches or Elements into Json
-	 * 
-	 * @param ele
 	 */
-	public void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
+	void unitgraphToJson(GRAPHTYPE type, JsonObject file, int id, LinkedList<Point> graph) {
 
 		JsonObject temp = new JsonObject();
 		String key = null;
@@ -359,14 +282,8 @@ public class SaveController {
 
 	/**
 	 * Canvas-Edge, Connections, Node-Edge and Old-Edges to json
-	 * 
-	 * @param type
-	 * @param file
-	 * @param id
-	 * @param arr
 	 */
-	public void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
-		// TODO Auto-generated method stub
+	private void edgeToJson(EDGETYPE type, JsonObject file, int id, ArrayList<CpsEdge> arr) {
 		String k = null;
 		boolean b = false;
 		JsonObject temp = new JsonObject();
@@ -408,7 +325,6 @@ public class SaveController {
 	}
 
 	private void trackedToJson(JsonObject file) {
-		// TODO Auto-generated method stub
 		JsonObject temp = new JsonObject();
 		String key = "TRACKED";
 		// forall points add them
@@ -420,17 +336,16 @@ public class SaveController {
 	}
 
 	private void statisticgraphToJson(JsonObject file) {
-		// TODO Auto-generated method stub
 		JsonObject temp = new JsonObject();
 
-		List<String> keys = model.getGraphTable().keySet().stream().collect(Collectors.toCollection(ArrayList::new));
+		List<String> keys = new ArrayList<>(model.getGraphTable().keySet());
 
 		for (String k : keys) {
 			JsonObject dataSet = new JsonObject();
 			for (int i = 0; i < model.getGraphTable().get(k).getStatGraph().getDataSets().size(); i++) {
 				TrackedDataSet set = model.getGraphTable().get(k).getStatGraph().getDataSets().get(i);
 				AbstractCpsObject cps = set.getCpsObject();
-				
+
 				dataSet.add("ID", (cps == null ? null : new JsonPrimitive(cps.getId())));
 				dataSet.add("COLOR", model.getGson().toJsonTree(set.getColor(), Color.class));
 				dataSet.add("PROPERTY", new JsonPrimitive(set.getProperty()));
@@ -447,10 +362,6 @@ public class SaveController {
 
 	/**
 	 * Differs Between Single file or whole Directory to Store
-	 * 
-	 * @param src
-	 * @param stream
-	 * @throws IOException
 	 */
 	private void addFilesToSave(File src, ArchiveOutputStream stream) throws IOException {
 		if (!src.exists())
@@ -470,14 +381,9 @@ public class SaveController {
 
 	/**
 	 * Add a File into the Archive
-	 * 
-	 * @param src
-	 * @param stream
-	 * @param dir
-	 * @throws IOException
 	 */
 	private void addFileToSave(File src, ArchiveOutputStream stream, boolean dir) throws IOException {
-		String entryName = (dir == true ? src.getCanonicalPath() : src.getName());
+		String entryName = (dir ? src.getCanonicalPath() : src.getName());
 
 		entryName = checkOS(entryName);
 
@@ -491,7 +397,6 @@ public class SaveController {
 	}
 
 	private String checkOS(String entryName) {
-		// TODO Auto-generated method stub
 		String os = System.getProperty("os.name").toLowerCase();
 		String ret = entryName;
 		String partition = null;
@@ -518,17 +423,14 @@ public class SaveController {
 	/**
 	 * Just initialize the Numerators for the Json Keys. Maybe bad Style..
 	 */
-	public void initNumeration() {
+	void initNumeration() {
 		this.nCat = this.nObj = this.nEle = this.nEdge = this.nConn = this.nNodeEdge = this.nOldEdge = this.nStatsGraph = 0;
 	}
 
 	/**
 	 * Get the wanted numerator and increment it
-	 * 
-	 * @param type
-	 * @return
 	 */
-	public int getNumerator(NUMTYPE type) {
+	int getNumerator(NUMTYPE type) {
 
 		switch (type) {
 		case CATEGORY:
@@ -556,4 +458,24 @@ public class SaveController {
 		return -1;
 	}
 
+	public enum MODE {
+		COMPLETE, PARTIAL, CATEGORY
+	}
+
+	public enum TYPE {
+		CATEGORY, CANVAS
+	}
+
+	public enum EDGETYPE {
+		CANVAS, CONNECTION, NODE, OLD, LAYER
+	}
+
+	public enum NUMTYPE {
+		CATEGORY, OBJECT, ELEMENT, EDGE, CONNECTION, NODEEDGE, OLDEDGE, UNITGRAPH, STATSGRAPH
+	}
+
+	public enum GRAPHTYPE {
+		SWITCH, ELEMENT
+	}
+
 }

+ 647 - 591
src/ui/controller/SimulationManager.java

@@ -1,604 +1,660 @@
 package ui.controller;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import classes.AbstractCpsObject;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.SubNet;
+import classes.*;
 import ui.model.Model;
 import ui.view.FlexiblePane;
 import ui.view.MyCanvas;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+
 /**
  * Controller for Simulation.
- * 
+ *
  * @author Gruppe14
  */
 public class SimulationManager {
-	private Model model;
-	private ArrayList<AbstractCpsObject> objectsToHandle;
-	private ArrayList<CpsEdge> allConnections;
-	private ArrayList<SubNet> subNets;
-	private ArrayList<CpsEdge> brokenEdges;
-	private MyCanvas canvas;
-	private int timeStep;
-	private HashMap<Integer, Float> tagTable = new HashMap<Integer, Float>();
-	private FlexiblePane flexPane;
-	/**
-	 * Constructor.
-	 * 
-	 * @param m
-	 *            Model
-	 */
-	public SimulationManager(Model m) {
-		canvas = null;
-		model = m;
-		subNets = new ArrayList<SubNet>();
-		brokenEdges = new ArrayList<CpsEdge>();
-	}
-
-	/**
-	 * calculates the flow of the edges and the supply for objects.
-	 * 
-	 * @param x
-	 *            current Iteration
-	 */
-	public void calculateStateForTimeStep(int x) {
-		reset();
-		timeStep = x;
-		searchForSubNets();
-		for (SubNet singleSubNet : subNets) {
-			resetConnections(singleSubNet.getObjects().get(0), new ArrayList<Integer>(), new ArrayList<CpsEdge>());
-		}
-		for (SubNet singleSubNet : subNets) {
-			float production = calculateEnergy("prod", singleSubNet, timeStep);
-			float consumption = calculateEnergy("cons", singleSubNet, timeStep);
-			float minConsumption = calculateMinimumEnergy(singleSubNet, timeStep);
-			setFlowSimulation(singleSubNet);
-			for (HolonObject hl : singleSubNet.getObjects()) {
-				if (!(hl.getState() == 0) && !(hl.getState() == 3)) {
-					for (int i = 0; i < hl.getConnections().size(); i++) {
-						CpsEdge edge = hl.getConnectedTo().get(i);
-						if (edge.getState() && edge.getFlow() > 0 || edge.getCapacity() == -1) {
-							// 0 = no energy, 1 = not supplied, 2 = supplied, 3
-							// = producer, 4 = partially supplied
-							if ((production + consumption) >= 0) {
-								hl.setState(2);
-							}
-							if ((production + consumption) < 0) {
-								if ((production + minConsumption) >= 0) {
-									hl.setState(4);
-								} else if (hl.checkIfPartiallySupplied(timeStep)) {
-									hl.setState(4);
-								} else {
-									hl.setState(1);
-								}
-							}
-							break;
-						}
-						hl.setState(1);
-					}
-					if (hl.checkIfPartiallySupplied(timeStep) && !(hl.getState() == 2)) {
-						hl.setState(4);
-					}
-				}
-			}
-		}
-		canvas.repaint();
-		//printNet();
-		flexPane.recalculate();
-	}
-
-	/**
-	 * Set Flow Simulation.
-	 * 
-	 * @param sN
-	 *            Subnet
-	 */
-	public void setFlowSimulation(SubNet sN) {
-		ArrayList<AbstractCpsObject> producers = new ArrayList<AbstractCpsObject>();
-		AbstractCpsObject tmp = null;
-		tagTable = new HashMap<Integer, Float>();
-		for (HolonObject hl : sN.getObjects()) {
-			float energy = hl.getCurrentEnergyAtTimeStep(timeStep);
-			if (energy > 0) {
-				tagTable.put(hl.getId(), energy);
-				hl.addTag(hl.getId());
-				for (CpsEdge edge : hl.getConnections()) {
-					if (edge.getState()) {
-						if (edge.getA().getId() == hl.getId()) {
-							edge.getB().addTag(hl.getId());
-							tmp = edge.getB();
-						}
-						if (edge.getB().getId() == hl.getId()) {
-							edge.getA().addTag(hl.getId());
-							tmp = edge.getA();
-						}
-						edge.setFlow(edge.getFlow() + energy);
-						edge.calculateState();
-						edge.addTag(hl.getId());
-						if (edge.getState() && !producers.contains(tmp)) {
-							if(tmp instanceof HolonSwitch){
-								if(((HolonSwitch)tmp).getState(timeStep)){
-									producers.add(tmp);
-								}
-							}else if(!(tmp instanceof CpsUpperNode)){
-								producers.add(tmp);
-							}
-						}
-					}
-				}
-			}
-		}
-		setFlowSimRec(producers, 0);
-	}
-
-	/**
-	 * Set Flow Rimulation Rec.
-	 * 
-	 * @param nodes
-	 *            the nodes
-	 * @param iter
-	 *            the Iteration
-	 */
-	public void setFlowSimRec(ArrayList<AbstractCpsObject> nodes, int iter) {
-		ArrayList<AbstractCpsObject> newNodes = new ArrayList<AbstractCpsObject>();
-		ArrayList<CpsEdge> changedEdges = new ArrayList<CpsEdge>();
-		AbstractCpsObject tmp;
-		if(nodes.size() != 0){
-			for(AbstractCpsObject cps: nodes){
-				if(legitState(cps)){
-					for(CpsEdge edge: cps.getConnections()){
-						if(edge.getState() && (!(edge.containsTags(edge.getTags(), cps.getTag())))){
-							if(edge.getA().getId() == cps.getId()){
-								tmp = edge.getB();
-							}else{
-								tmp = edge.getA();
-							}	
-							for(Integer tag: cps.getTag()){
-								if(!(edge.getTags().contains(tag)) && !(edge.getPseudoTags().contains(tag))){
-									edge.setFlow(edge.getFlow() + tagTable.get(tag));
-									edge.addTag(tag);
-								}
-							}
-							// uppernodes do not spread energy
-							if(!(tmp instanceof CpsUpperNode)){
-								for(Integer tag: tmp.getTag()){
-									if(!(edge.getTags().contains(tag)) && tagTable.get(tag) != null && !(edge.getPseudoTags().contains(tag))){
-										edge.setFlow(edge.getFlow() + tagTable.get(tag));
-										edge.addPseudoTag(tag);
-										changedEdges.add(edge);
-									}
-								}
-							}
-							edge.calculateState();
-							if(edge.getState() && !(tmp instanceof CpsUpperNode)){
-								tmp.addAllPseudoTags(cps.getTag());
-								if(!newNodes.contains(tmp)){
-								newNodes.add(tmp);
-								}
-							}
-						}
-					}
-				}
-			}
-			setPseudoTags(newNodes, changedEdges);
-			setFlowSimRec(newNodes, iter+1);
-		}
-	}
-
-	/**
-	 * Set the Pseudo Tags.
-	 * 
-	 * @param nodes
-	 *            Array of AbstractCpsObjects
-	 */
-	public void setPseudoTags(ArrayList<AbstractCpsObject> nodes, ArrayList<CpsEdge> edges) {
-		for (AbstractCpsObject node : nodes) {
-			node.recalculateTags();
-			node.setPseudoTags(new ArrayList<Integer>());
-		}
-		for(CpsEdge edge : edges){
-			edge.recalculateTags();
-			edge.setPseudoTag(new ArrayList<Integer>());
-		}
-	}
-
-	/**
-	 * Print the nodes.
-	 * 
-	 * @param nodes
-	 *            Array of AbstractCpsObject
-	 */
-	public void printNodes(ArrayList<AbstractCpsObject> nodes) {
-		System.out.println("new Nodes:");
-		for (AbstractCpsObject node : nodes) {
-			System.out.println(node.getId());
-		}
-	}
-
-	/**
-	 * Get String.
-	 * 
-	 * @param tags
-	 *            the tags
-	 * @return the String
-	 */
-	public String getString(ArrayList<Integer> tags) {
-		String result = "";
-		for (Integer i : tags) {
-			result = result + ", " + i;
-		}
-		return result;
-	}
-
-	/**
-	 * Merge the Lists.
-	 * 
-	 * @param a
-	 *            first liust
-	 * @param b
-	 *            second list
-	 * @return the Result
-	 */
-	public ArrayList<Integer> mergeLists(ArrayList<Integer> a, ArrayList<Integer> b) {
-		ArrayList<Integer> result = new ArrayList<Integer>();
-		for (Integer i : a) {
-			if (!(result.contains(i))) {
-				result.add(i);
-			}
-		}
-		for (Integer j : b) {
-			if (!(result.contains(j))) {
-				result.add(j);
-			}
-		}
-		return result;
-	}
-
-	/**
-	 * Reset the Connection.
-	 * 
-	 * @param cps
-	 *            CpsObject
-	 * @param visitedObj
-	 *            the visited Objects
-	 * @param visitedEdges
-	 *            the visited Edges
-	 */
-	public void resetConnections(AbstractCpsObject cps, ArrayList<Integer> visitedObj,
-			ArrayList<CpsEdge> visitedEdges) {
-		visitedObj.add(cps.getId());
-		cps.resetTags();
-		for (CpsEdge e : cps.getConnections()) {
-			if (!(visitedEdges.contains(e))) {
-				e.setFlow(0);
-				e.calculateState();
-				e.setTags(new ArrayList<Integer>());
-				visitedEdges.add(e);
-				if (!(visitedObj.contains(e.getA().getId()))) {
-					resetConnections(e.getA(), visitedObj, visitedEdges);
-					e.getA().resetTags();
-				}
-				if (!(visitedObj.contains(e.getB().getId()))) {
-					resetConnections(e.getB(), visitedObj, visitedEdges);
-					e.getB().resetTags();
-				}
-			}
-		}
-	}
-
-	/**
-	 * calculates the energy of either all producers or consumers.
-	 * 
-	 * @param type
-	 *            Type
-	 * @param sN
-	 *            Subnet
-	 * @param x
-	 *            Integer
-	 * 
-	 * @return The Energy
-	 */
-	public float calculateEnergy(String type, SubNet sN, int x) {
-		float energy = 0;
-		for (HolonObject hl : sN.getObjects()) {
-			if (type.equals("prod")) {
-				if (hl.getCurrentEnergyAtTimeStep(x) > 0) {
-					energy = energy + hl.getCurrentEnergyAtTimeStep(x);
-					hl.setState(3);
-				}
-			}
-			if (type.equals("cons")) {
-				if (hl.getCurrentEnergyAtTimeStep(x) < 0) {
-					energy = energy + hl.getCurrentEnergyAtTimeStep(x);
-					hl.setState(1);
-				}
-			}
-			if (hl.getCurrentEnergyAtTimeStep(x) == 0) {
-				hl.setState(0);
-			}
-		}
-		return energy;
-	}
-
-	/**
-	 * Calculate the Minimum Energy.
-	 * 
-	 * @param sN
-	 *            Subnet
-	 * @param x
-	 *            Integer
-	 * @return the Calculated minimum Energy
-	 */
-	public float calculateMinimumEnergy(SubNet sN, int x) {
-		float min = 0;
-		float minElement = 0;
-		for (HolonObject hl : sN.getObjects()) {
-			if (hl.getElements().size() > 0 && hl.getElements().get(0).getTotalEnergyAtTimeStep(x) < 0) {
-				minElement = hl.getElements().get(0).getTotalEnergyAtTimeStep(x);
-			}
-			for (HolonElement he : hl.getElements()) {
-				if (minElement < he.getTotalEnergyAtTimeStep(x) && he.getTotalEnergyAtTimeStep(x) < 0) {
-					minElement = he.getTotalEnergyAtTimeStep(x);
-				}
-			}
-			min = min + minElement;
-		}
-		return min;
-	}
-
-	/**
-	 * generates all subNets from all objectsToHandle.
-	 */
-	public void searchForSubNets() {
-		subNets = new ArrayList<SubNet>();
-		brokenEdges.clear();
-		boolean end = false;
-		int i = 0;
-		AbstractCpsObject cps;
-		if (objectsToHandle.size() > 0) {
-			while (!end) {
-				cps = objectsToHandle.get(i);
-					SubNet singleSubNet = new SubNet(new ArrayList<HolonObject>(), new ArrayList<CpsEdge>(),
-							new ArrayList<HolonSwitch>());
-					singleSubNet = buildSubNet(cps, new ArrayList<Integer>(), singleSubNet);
-					if (singleSubNet.getObjects().size() != 0) {
-						subNets.add(singleSubNet);
-					}
-					if (0 == objectsToHandle.size()) {
-						end = true;
-					}
-			}
-		}
-	}
-
-	/**
-	 * recursivly generates a subnet of all objects, that one specific object is
-	 * connected to.
-	 * 
-	 * @param cps
-	 *            AbstractCpsObject
-	 * @param visited
-	 *            visited Array of Integer
-	 * @param sN
-	 *            Subnets
-	 * @return Subnet
-	 */
-	public SubNet buildSubNet(AbstractCpsObject cps, ArrayList<Integer> visited, SubNet sN) {
-		visited.add(cps.getId());
-		if (cps instanceof HolonObject) {
-			sN.getObjects().add((HolonObject) cps);
-		}
-		if (cps instanceof HolonSwitch) {
-			sN.getSwitches().add((HolonSwitch) cps);
-		}
-		removeFromToHandle(cps.getId());
-		AbstractCpsObject a;
-		AbstractCpsObject b;
-		for (CpsEdge edge : cps.getConnections()) {
-			if(edge.getState()){
-				a = edge.getA();
-				b = edge.getB();
-				if (!(cps instanceof HolonSwitch)) {
-					if (!(sN.getEdges().contains(edge))) {
-						sN.getEdges().add(edge);
-					}
-				}
-				if(cps instanceof HolonSwitch && ((HolonSwitch)cps).getState(timeStep)){
-					if (!(sN.getEdges().contains(edge))) {
-						sN.getEdges().add(edge);
-					}
-				}
-				if (!visited.contains(a.getId()) && legitState(cps) && !(a instanceof CpsUpperNode)) {
-					sN = buildSubNet(a, visited, sN);
-				}
-				if (!visited.contains(b.getId()) && legitState(cps) && !(b instanceof CpsUpperNode)) {
-					sN = buildSubNet(b, visited, sN);
-				}
-				if(a instanceof CpsUpperNode && a.getId() != cps.getId()){
-					edge.setConnected(2);
-					checkForConnectedStates(b, (CpsUpperNode)a, edge);
-				}
-				if(b instanceof CpsUpperNode && b.getId() != cps.getId()){
-					edge.setConnected(2);
-					checkForConnectedStates(a, (CpsUpperNode)b, edge);
-				}
-			}else{
-				brokenEdges.add(edge);
-			}
-		}
-		return sN;
-	}
-
-	/**
-	 * is the Switch in a legitimate State.
-	 * 
-	 * @param neighbor AbstractCpsObject
-	 * @param current AbstractCpsObject
-	 * @return boolean
-	 */
-	public boolean legitState(AbstractCpsObject current) {
-		if (current instanceof HolonSwitch) {
-			if (((HolonSwitch) current).getState(timeStep)) {
-				return true;
-			}else{
-				return false;
-			}
-		}
-		return true;
-	}
-
-	/**
-	 * removes an Object that already has been handled with.
-	 * 
-	 * @param id the Object ID
-	 */
-	public void removeFromToHandle(int id) {
-		for (int i = 0; i < objectsToHandle.size(); i++) {
-			if (objectsToHandle.get(i).getId() == id) {
-				objectsToHandle.remove(i);
-			}
-		}
-	}
-
-	/**
-	 * ensures that objectsToHandle only contains HolonObjects.
-	 */
-	public void cleanObjectsToHandle() {
-		for (int i = 0; i < objectsToHandle.size(); i++) {
-			if (!(objectsToHandle.get(i) instanceof HolonObject)) {
-				objectsToHandle.remove(i);
-			}
-		}
-	}
-
-	/**
-	 * copies the data of an array of Objects.
-	 * 
-	 * @param toCopy the ArrayList of CpsObjects co Copy
-	 */
-	public void copyObjects(ArrayList<AbstractCpsObject> toCopy) {
-		for (AbstractCpsObject cps : toCopy) {
-			if(cps instanceof CpsUpperNode){
-				copyObjects(((CpsUpperNode)cps).getNodes());
-			}else{
-				objectsToHandle.add(cps);
-			}
-		}
-	}
-
-	/**
-	 * Prints the Components auf all subnets.
-	 */
-	public void printNet() {
-		for (int i = 0; i < subNets.size(); i++) {
-			System.out.println("SUBNET NR:" + i);
-			System.out.println("  Objects:");
-			for (int j = 0; j < subNets.get(i).getObjects().size(); j++) {
-				HolonObject hl = subNets.get(i).getObjects().get(j);
-				System.out.println("    " + hl.getName() + " " + hl.getId());
-			}
-			System.out.println("  Edges:");
-			for (int j = 0; j < subNets.get(i).getEdges().size(); j++) {
-				CpsEdge edge = subNets.get(i).getEdges().get(j);
-				System.out.println("     " + edge.getA().getName() + " connected To " + edge.getB().getName());
-			}
-			System.out.println("  Switches:");
-			for (int j = 0; j < subNets.get(i).getSwitches().size(); j++) {
-				HolonSwitch sw = subNets.get(i).getSwitches().get(j);
-				System.out.println("    " + sw.getName() + " " + sw.getId() + " State:" + sw.getActiveAt()[timeStep]);
-			}
-		}
-	}
-
-	/**
-	 * Set the Canvas.
-	 * 
-	 * @param can
-	 *            the Canvas
-	 */
-	public void setCanvas(MyCanvas can) {
-		canvas = can;
-	}
-
-	/**
-	 * Reset all Data to the current state of the Model.
-	 */
-	public void reset() {
-		objectsToHandle = new ArrayList<AbstractCpsObject>();
-		copyObjects(model.getObjectsOnCanvas());
-	}
-	
-	/**
-	 * Resets the State of all Edges
-	 */
-	public void resetEdges(){
-		for(CpsEdge e: brokenEdges){
-			e.setState(true);
-		}
-	}
-	
-	/**
-	 * Resets the State for the whole Simulation Model
-	 */
-	public void resetSimulation(){
-		reset();
-		resetEdges();
-	}
-
-	/**
-	 * Get all Subnets.
-	 * 
-	 * @return all Subnets
-	 */
-	public ArrayList<SubNet> getSubNets() {
-		return subNets;
-	}
-	
-	/**
-	 * Get broken Edges
-	 */
-	public ArrayList<CpsEdge> getBrokenEdges(){
-		return brokenEdges;
-	}
-	
-	/**
-	 * checks wether a given object is connected to an object inside the upperNode.
-	 * if yes, the state for the edge is changed in "connected" or "not connected"
-	 * @param cps
-	 * @param cUNode
-	 */
-	public void checkForConnectedStates(AbstractCpsObject cps, CpsUpperNode cUNode, CpsEdge theEdge){
-		AbstractCpsObject tmp;
-		for(CpsEdge edge: cps.getConnections()){
-			if(edge.getA().getId() == cps.getId()){
-				tmp = edge.getB();
-			} else{
-				tmp = edge.getA();
-			}
-			if(cUNode.getNodes().contains(tmp)){
-				if(tmp instanceof CpsUpperNode){
-					checkForConnectedStates(cps, (CpsUpperNode)tmp, theEdge);
-				}else{
-					theEdge.setConnected(1);
-					break;
-				}
-			}
-		}
-	}
-
-	public void setFlexiblePane(FlexiblePane fp) {
-		flexPane = fp;
-	}
-	
-	public FlexiblePane getFlexiblePane(){
-		return flexPane;
-	}
+    int global = 0;
+    private Model model;
+    private ArrayList<AbstractCpsObject> objectsToHandle;
+    //	private ArrayList<CpsEdge> allConnections;
+    private ArrayList<SubNet> subNets;
+    private ArrayList<CpsEdge> brokenEdges;
+    private MyCanvas canvas;
+    private int timeStep;
+    private HashMap<Integer, Float> tagTable = new HashMap<>();
+    private FlexiblePane flexPane;
+
+    private HashMap<HolonElement, Float> flexDevicesTurnedOnThisTurn = new HashMap<>();
+
+    /**
+     * Constructor.
+     *
+     * @param m Model
+     */
+    SimulationManager(Model m) {
+        canvas = null;
+        model = m;
+        subNets = new ArrayList<>();
+        brokenEdges = new ArrayList<>();
+    }
+
+    /**
+     * calculates the flow of the edges and the supply for objects.
+     *
+     * @param x current Iteration
+     */
+    void calculateStateForTimeStep(int x) {
+        reset();
+        timeStep = x;
+        searchForSubNets();
+        for (SubNet singleSubNet : subNets) {
+            resetConnections(singleSubNet.getObjects().get(0), new ArrayList<>(), new ArrayList<>());
+        }
+        for (SubNet singleSubNet : subNets) {
+            float production = calculateEnergyWithoutFlexDevices("prod", singleSubNet, timeStep);
+            float consumption = calculateEnergyWithoutFlexDevices("cons", singleSubNet, timeStep);
+            // surplus of energy is computed by sum, since consumption is a negative value
+            float energySurplus = production + consumption;
+
+            float minConsumption = calculateMinimumEnergy(singleSubNet, timeStep);
+
+            // --------------- use flexible devices ---------------
+            if (energySurplus != 0 && model.useFlexibleDevices()) {
+                turnOnFlexibleDevices(singleSubNet, energySurplus, x);
+
+//                if (!flexDevicesTurnedOnThisTurn.isEmpty()) {
+//                    System.out.println("The following devices were turned on in this turn: ");
+//                    System.out.println(flexDevicesTurnedOnThisTurn.toString());
+//                }
+
+                // recompute after having examined/turned on all flexible devices
+                production = calculateEnergyWithFlexDevices("prod", singleSubNet, timeStep);
+                consumption = calculateEnergyWithFlexDevices("cons", singleSubNet, timeStep);
+                energySurplus = production + consumption;
+            }
+
+            // --------------- set flow simulation ---------------
+            setFlowSimulation(singleSubNet);
+
+            // --------------- visualise graph ---------------
+            for (HolonObject hl : singleSubNet.getObjects()) {
+                if (hl.getState() != HolonObject.NO_ENERGY
+                        && hl.getState() != HolonObject.PRODUCER) {
+                    for (int i = 0; i < hl.getConnections().size(); i++) {
+                        CpsEdge edge = hl.getConnectedTo().get(i);
+                        if (edge.isWorking() && edge.getFlow() > 0
+                                || edge.getCapacity() == CpsEdge.CAPACITY_INFINITE) {
+                            if ((production + consumption) >= 0) {
+                                if (energySurplus > 0) {
+                                    hl.setState(HolonObject.OVER_SUPPLIED);
+                                } else {
+                                    hl.setState(HolonObject.SUPPLIED);
+                                }
+                            } else {
+                                if ((production + minConsumption) >= 0) {
+                                    hl.setState(HolonObject.PARTIALLY_SUPPLIED);
+                                } else if (hl.checkIfPartiallySupplied(timeStep)) {
+                                    hl.setState(HolonObject.PARTIALLY_SUPPLIED);
+                                } else {
+                                    hl.setState(HolonObject.NOT_SUPPLIED);
+                                }
+                            }
+                            break;
+                        }
+                    }
+                    if (hl.checkIfPartiallySupplied(timeStep)
+                            && hl.getState() != HolonObject.SUPPLIED
+                            && hl.getState() != HolonObject.OVER_SUPPLIED) {
+                        hl.setState(HolonObject.PARTIALLY_SUPPLIED);
+                    }
+                }
+            }
+        }
+        canvas.repaint();
+        flexPane.recalculate();
+    }
+
+    /**
+     * search for all flexible devices in the network and turn them on, until energy surplus = 0
+     * or all devices have been examined.
+     *
+     * This code could be compressed (cases inside over- and underproduction are the same), but we decided that it
+     * is better readable this way
+     *
+     * @param subNet        the subnet
+     * @param energySurplus the current surplus of energy
+     */
+    private void turnOnFlexibleDevices(SubNet subNet, float energySurplus, int timestep) {
+        for (HolonObject holonOb : subNet.getObjects()) {
+            for (HolonElement holonEl : holonOb.getElements()) {
+
+                // if this element is flexible and active (can be considered for calculations)
+                if (holonEl.isFlexible() && holonEl.isActive()) {
+                    float energyAvailableSingle = holonEl.getAvailableEnergyAt(timestep);
+                    float energyAvailableMultiple = energyAvailableSingle * holonEl.getAmount();
+
+                    // ------------- flexible consumer / OVERPRODUCTION -------------
+                    if (energyAvailableMultiple < 0 && energySurplus > 0) {
+
+                        // if there is more wasted energy than energy that this device can give, give all energy available
+                        if (Math.abs(energyAvailableMultiple) <= Math.abs(energySurplus)) {
+                            energySurplus += energyAvailableMultiple;
+                            // set the new energy consumption to the maximum
+                            holonEl.setEnergyPerElement(energyAvailableSingle);
+                            flexDevicesTurnedOnThisTurn.put(holonEl, energyAvailableMultiple);
+                        }
+                        // else: we just need to turn on part of the flexible energy available
+                        else {
+                            float energyNeeded = -energySurplus;
+                            energySurplus += energyNeeded;   // should give 0, but was kept this was for consistency
+                            // the energy needed divided through the amount of elements
+                            holonEl.setEnergyPerElement(energyNeeded / holonEl.getAmount());
+                            flexDevicesTurnedOnThisTurn.put(holonEl, energyNeeded);
+                        }
+                    }
+
+                    // ------------- flexible producer / UNDERPRODUCTION -------------
+                    else if (energyAvailableMultiple > 0 && energySurplus < 0) {
+
+                        // if there is more energy needed than this device can give, give all the energy available
+                        if (Math.abs(energyAvailableMultiple) <= Math.abs(energySurplus)) {
+                            energySurplus += energyAvailableMultiple;
+                            // set the new energy consumption to the maximum
+                            holonEl.setEnergyPerElement(energyAvailableSingle);
+                            flexDevicesTurnedOnThisTurn.put(holonEl, energyAvailableMultiple);
+                        }
+                        // else: we just need to turn on part of the flexible energy available
+                        else {
+                            float energyNeeded = -energySurplus;
+                            int i = 0;
+                            energySurplus += energyNeeded;   // should give 0, but was kept this was for consistency
+                            // the energy needed divided through the amount of elements
+                            holonEl.setEnergyPerElement(energyNeeded / holonEl.getAmount());
+                            flexDevicesTurnedOnThisTurn.put(holonEl, energyNeeded);
+                        }
+
+                    }
+                }
+
+                if (energySurplus == 0) {
+                    break;
+                }
+            }
+
+            if (energySurplus == 0) {
+                break;
+            }
+        }
+    }
+
+    /**
+     * Set Flow Simulation.
+     *
+     * @param sN Subnet
+     */
+    private void setFlowSimulation(SubNet sN) {
+        ArrayList<AbstractCpsObject> producers = new ArrayList<>();
+        AbstractCpsObject tmp = null;
+        tagTable = new HashMap<>();
+        // traverse all objects in this subnet
+        for (HolonObject hl : sN.getObjects()) {
+            float energy = hl.getCurrentEnergyAtTimeStep(timeStep);
+            // if their production is higher than their consumption
+            if (energy > 0) {
+                tagTable.put(hl.getId(), energy);
+                hl.addTag(hl.getId());
+                for (CpsEdge edge : hl.getConnections()) {
+                    if (edge.isWorking()) {
+                        // set other end of edge as tmp-object
+                        // and add this end to the other end's tag-list
+                        AbstractCpsObject a = edge.getA();
+                        AbstractCpsObject b = edge.getB();
+                        if (a.getId() == hl.getId()) {
+                            b.addTag(hl.getId());
+                            tmp = b;
+                        }
+                        if (b.getId() == hl.getId()) {
+                            a.addTag(hl.getId());
+                            tmp = a;
+                        }
+
+                        edge.setFlow(edge.getFlow() + energy);
+                        edge.calculateState();
+                        edge.addTag(hl.getId());
+                        if (edge.isWorking() && !producers.contains(tmp)) {
+                            if (tmp instanceof HolonSwitch) {
+                                if (((HolonSwitch) tmp).getState(timeStep)) {
+                                    producers.add(tmp);
+                                }
+                            } else if (!(tmp instanceof CpsUpperNode)) {
+                                producers.add(tmp);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        setFlowSimRec(producers, 0);
+    }
+
+    /**
+     * Set Flow Simulation Rec.
+     *
+     * @param nodes the nodes
+     * @param iter  the Iteration
+     */
+    private void setFlowSimRec(ArrayList<AbstractCpsObject> nodes, int iter) {
+        ArrayList<AbstractCpsObject> newNodes = new ArrayList<>();
+        ArrayList<CpsEdge> changedEdges = new ArrayList<>();
+        AbstractCpsObject tmp;
+        if (nodes.size() != 0) {
+            for (AbstractCpsObject cps : nodes) {
+                // check whether the cps is in a legit state if it is a switch
+                if (legitState(cps)) {
+                    for (CpsEdge edge : cps.getConnections()) {
+                        // is edge working
+                        // and does the edge's tag-list not (yet) contain all tags of the cps
+                        if (edge.isWorking()
+                                && (!(edge.containsTags(edge.getTags(), cps.getTag())))) {
+                            if (edge.getA().getId() == cps.getId()) {
+                                tmp = edge.getB();
+                            } else {
+                                tmp = edge.getA();
+                            }
+                            for (Integer tag : cps.getTag()) {
+                                if (!(edge.getTags().contains(tag))
+                                        && !(edge.getPseudoTags().contains(tag))) {
+                                    edge.setFlow(edge.getFlow() + tagTable.get(tag));
+                                    edge.addTag(tag);
+                                }
+                            }
+                            // uppernodes do not spread energy
+                            if (!(tmp instanceof CpsUpperNode)) {
+                                for (Integer tag : tmp.getTag()) {
+                                    if (!(edge.getTags().contains(tag))
+                                            && tagTable.get(tag) != null
+                                            && !(edge.getPseudoTags().contains(tag))) {
+                                        edge.setFlow(edge.getFlow() + tagTable.get(tag));
+                                        edge.addPseudoTag(tag);
+                                        changedEdges.add(edge);
+                                    }
+                                }
+                            }
+                            edge.calculateState();
+                            if (edge.isWorking()
+                                    && !(tmp instanceof CpsUpperNode)) {
+                                tmp.addAllPseudoTags(cps.getTag());
+                                if (!newNodes.contains(tmp)) {
+                                    newNodes.add(tmp);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            setPseudoTags(newNodes, changedEdges);
+            setFlowSimRec(newNodes, iter + 1);
+        }
+    }
+
+    /**
+     * Set the Pseudo Tags.
+     *
+     * @param nodes Array of AbstractCpsObjects
+     */
+    private void setPseudoTags(ArrayList<AbstractCpsObject> nodes, ArrayList<CpsEdge> edges) {
+        for (AbstractCpsObject node : nodes) {
+            node.recalculateTags();
+            node.setPseudoTags(new ArrayList<>());
+        }
+        for (CpsEdge edge : edges) {
+            edge.recalculateTags();
+            edge.setPseudoTag(new ArrayList<>());
+        }
+    }
+
+    /**
+     * Reset the Connection.
+     *
+     * @param cps          CpsObject
+     * @param visitedObj   the visited Objects
+     * @param visitedEdges the visited Edges
+     */
+    private void resetConnections(AbstractCpsObject cps, ArrayList<Integer> visitedObj,
+                                  ArrayList<CpsEdge> visitedEdges) {
+        visitedObj.add(cps.getId());
+        cps.resetTags();
+        for (CpsEdge e : cps.getConnections()) {
+            if (!(visitedEdges.contains(e))) {
+                e.setFlow(0);
+                e.calculateState();
+                e.setTags(new ArrayList<>());
+                visitedEdges.add(e);
+                if (!(visitedObj.contains(e.getA().getId()))) {
+                    resetConnections(e.getA(), visitedObj, visitedEdges);
+                    e.getA().resetTags();
+                }
+                if (!(visitedObj.contains(e.getB().getId()))) {
+                    resetConnections(e.getB(), visitedObj, visitedEdges);
+                    e.getB().resetTags();
+                }
+            }
+        }
+    }
+
+    /**
+     * calculates the energy of either all producers or consumers.
+     * Flexible devices are filtered out
+     *
+     * @param type Type
+     * @param sN   Subnet
+     * @param x    Integer
+     * @return The Energy
+     */
+    private float calculateEnergyWithoutFlexDevices(String type, SubNet sN, int x) {
+        float energy = 0;
+        for (HolonObject hl : sN.getObjects()) {
+            float currentEnergyWithoutFlexibles = hl.getCurrentEnergyAtTimeStepWithoutFlexiblesAndResetFlexibles(x);
+
+            if (type.equals("prod")) {
+                if (currentEnergyWithoutFlexibles > 0) {
+                    energy += currentEnergyWithoutFlexibles;
+                    hl.setState(HolonObject.PRODUCER);
+                }
+            }
+            if (type.equals("cons")) {
+                if (currentEnergyWithoutFlexibles < 0) {
+                    energy = energy + currentEnergyWithoutFlexibles;
+                    hl.setState(HolonObject.NOT_SUPPLIED);
+                }
+            }
+            if (currentEnergyWithoutFlexibles == 0) {
+                hl.setState(HolonObject.NO_ENERGY);
+            }
+        }
+        return energy;
+    }
+
+    /**
+     * calculates the energy of either all producers or consumers.
+     * Flexible devices are filtered out
+     *
+     * @param type Type
+     * @param sN   Subnet
+     * @param x    Integer
+     * @return The Energy
+     */
+    private float calculateEnergyWithFlexDevices(String type, SubNet sN, int x) {
+        float energy = 0;
+        for (HolonObject hl : sN.getObjects()) {
+            float currentEnergy = hl.getCurrentEnergyAtTimeStep(x);
+
+            if (type.equals("prod")) {
+                if (currentEnergy > 0) {
+                    energy += currentEnergy;
+                    hl.setState(HolonObject.PRODUCER);
+                }
+            }
+            if (type.equals("cons")) {
+                if (currentEnergy < 0) {
+                    energy = energy + currentEnergy;
+                    hl.setState(HolonObject.NOT_SUPPLIED);
+                }
+            }
+            if (currentEnergy == 0) {
+                hl.setState(HolonObject.NO_ENERGY);
+            }
+        }
+        return energy;
+    }
+
+    /**
+     * Calculate the Minimum Energy.
+     *
+     * @param sN Subnet
+     * @param x  Integer
+     * @return the Calculated minimum Energy
+     */
+    private float calculateMinimumEnergy(SubNet sN, int x) {
+        float min = 0;
+        float minElement = 0;
+        for (HolonObject hl : sN.getObjects()) {
+            if (hl.getElements().size() > 0 && hl.getElements().get(0).getOverallEnergyAtTimeStep(x) < 0) {
+                minElement = hl.getElements().get(0).getOverallEnergyAtTimeStep(x);
+            }
+            for (HolonElement he : hl.getElements()) {
+                float overallEnergy = he.getOverallEnergyAtTimeStep(x);
+                if (minElement < overallEnergy && overallEnergy < 0) {
+                    minElement = overallEnergy;
+                }
+            }
+            min = min + minElement;
+        }
+        return min;
+    }
+
+    /**
+     * generates all subNets from all objectsToHandle.
+     */
+    private void searchForSubNets() {
+        subNets = new ArrayList<>();
+        brokenEdges.clear();
+        boolean end = false;
+        int i = 0;
+        AbstractCpsObject cps;
+        if (objectsToHandle.size() > 0) {
+            while (!end) {
+                cps = objectsToHandle.get(i);
+                SubNet singleSubNet = new SubNet(new ArrayList<>(), new ArrayList<>(),
+                        new ArrayList<>());
+                singleSubNet = buildSubNet(cps, new ArrayList<>(), singleSubNet);
+                if (singleSubNet.getObjects().size() != 0) {
+                    subNets.add(singleSubNet);
+                }
+                if (0 == objectsToHandle.size()) {
+                    end = true;
+                }
+            }
+        }
+    }
+
+    /**
+     * recursivly generates a subnet of all objects, that one specific object is
+     * connected to.
+     *
+     * @param cps     AbstractCpsObject
+     * @param visited visited Array of Integer
+     * @param sN      Subnets
+     * @return Subnet
+     */
+    private SubNet buildSubNet(AbstractCpsObject cps, ArrayList<Integer> visited, SubNet sN) {
+        visited.add(cps.getId());
+        if (cps instanceof HolonObject) {
+            sN.getObjects().add((HolonObject) cps);
+        }
+        if (cps instanceof HolonSwitch) {
+            sN.getSwitches().add((HolonSwitch) cps);
+        }
+        removeFromToHandle(cps.getId());
+        AbstractCpsObject a;
+        AbstractCpsObject b;
+        for (CpsEdge edge : cps.getConnections()) {
+            if (edge.isWorking()) {
+                a = edge.getA();
+                b = edge.getB();
+                if (!(cps instanceof HolonSwitch)) {
+                    if (!(sN.getEdges().contains(edge))) {
+                        sN.getEdges().add(edge);
+                    }
+                }
+                if (cps instanceof HolonSwitch && ((HolonSwitch) cps).getState(timeStep)) {
+                    if (!(sN.getEdges().contains(edge))) {
+                        sN.getEdges().add(edge);
+                    }
+                }
+                if (!visited.contains(a.getId()) && legitState(cps) && !(a instanceof CpsUpperNode)) {
+                    sN = buildSubNet(a, visited, sN);
+                }
+                if (!visited.contains(b.getId()) && legitState(cps) && !(b instanceof CpsUpperNode)) {
+                    sN = buildSubNet(b, visited, sN);
+                }
+                if (a instanceof CpsUpperNode && a.getId() != cps.getId()) {
+                    edge.setConnected(CpsEdge.CON_UPPER_NODE_NOT_INSIDE);
+                    checkForConnectedStates(b, (CpsUpperNode) a, edge);
+                }
+                if (b instanceof CpsUpperNode && b.getId() != cps.getId()) {
+                    edge.setConnected(CpsEdge.CON_UPPER_NODE_NOT_INSIDE);
+                    checkForConnectedStates(a, (CpsUpperNode) b, edge);
+                }
+            } else {
+                brokenEdges.add(edge);
+            }
+        }
+        return sN;
+    }
+
+    /**
+     * is the Switch in a legitimate State.
+     *
+     * @param current AbstractCpsObject
+     * @return boolean
+     */
+    private boolean legitState(AbstractCpsObject current) {
+        return !(current instanceof HolonSwitch)
+                || ((HolonSwitch) current).getState(timeStep);
+    }
+
+//    /**
+//     * ensures that objectsToHandle only contains HolonObjects.
+//     */
+//	public void cleanObjectsToHandle() {
+//		for (int i = 0; i < objectsToHandle.size(); i++) {
+//			if (!(objectsToHandle.get(i) instanceof HolonObject)) {
+//				objectsToHandle.remove(i);
+//			}
+//		}
+//	}
+
+    /**
+     * removes an Object that already has been handled.
+     *
+     * @param id the Object ID
+     */
+    private void removeFromToHandle(int id) {
+        for (int i = 0; i < objectsToHandle.size(); i++) {
+            if (objectsToHandle.get(i).getId() == id) {
+                objectsToHandle.remove(i);
+            }
+        }
+    }
+
+    /**
+     * copies the data of an array of Objects.
+     *
+     * @param toCopy the ArrayList of CpsObjects co Copy
+     */
+    private void copyObjects(ArrayList<AbstractCpsObject> toCopy) {
+        for (AbstractCpsObject cps : toCopy) {
+            if (cps instanceof CpsUpperNode) {
+                copyObjects(((CpsUpperNode) cps).getNodes());
+            } else {
+                objectsToHandle.add(cps);
+            }
+        }
+    }
+
+    /**
+     * Prints the Components auf all subnets.
+     */
+    private void printNetsToConsole() {
+        for (int i = 0; i < subNets.size(); i++) {
+            SubNet subNet = subNets.get(i);
+            System.out.println("SUBNET NR:" + i);
+            subNet.toString(timeStep);
+        }
+    }
+
+    /**
+     * Set the Canvas.
+     *
+     * @param can the Canvas
+     */
+    public void setCanvas(MyCanvas can) {
+        canvas = can;
+    }
+
+    /**
+     * Reset all Data to the current state of the Model.
+     */
+    public void reset() {
+        objectsToHandle = new ArrayList<>();
+        copyObjects(model.getObjectsOnCanvas());
+        flexDevicesTurnedOnThisTurn = new HashMap<>();
+    }
+
+    /**
+     * Resets the State of all Edges
+     */
+    private void resetEdges() {
+        for (CpsEdge e : brokenEdges) {
+            e.setWorkingState(true);
+        }
+    }
+
+    /**
+     * Resets the State for the whole Simulation Model
+     */
+    void resetSimulation() {
+        reset();
+        resetEdges();
+    }
+
+    /**
+     * Get all Subnets.
+     *
+     * @return all Subnets
+     */
+    public ArrayList<SubNet> getSubNets() {
+        return subNets;
+    }
+
+    /**
+     * Get broken Edges
+     */
+//    public ArrayList<CpsEdge> getBrokenEdges() {
+//        return brokenEdges;
+//    }
+
+    /**
+     * checks whether a given object is connected to an object inside the upperNode.
+     * if yes, the state for the edge is changed in "connected" or "not connected"
+     */
+    private void checkForConnectedStates(AbstractCpsObject cps, CpsUpperNode cUNode, CpsEdge theEdge) {
+        AbstractCpsObject tmp;
+        for (CpsEdge edge : cps.getConnections()) {
+            if (edge.getA().getId() == cps.getId()) {
+                tmp = edge.getB();
+            } else {
+                tmp = edge.getA();
+            }
+            if (cUNode.getNodes().contains(tmp)) {
+                if (tmp instanceof CpsUpperNode) {
+                    checkForConnectedStates(cps, (CpsUpperNode) tmp, theEdge);
+                } else {
+                    theEdge.setConnected(CpsEdge.CON_UPPER_NODE_AND_INSIDE);
+                    break;
+                }
+            }
+        }
+    }
+
+    public FlexiblePane getFlexiblePane() {
+        return flexPane;
+    }
+
+    void setFlexiblePane(FlexiblePane fp) {
+        flexPane = fp;
+    }
 
 }

+ 14 - 22
src/ui/controller/UpdateController.java

@@ -1,21 +1,15 @@
 package ui.controller;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import classes.AbstractCpsObject;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.SubNet;
+import classes.*;
 import ui.model.Model;
 import ui.view.DefaulTable;
 import ui.view.Languages;
 import ui.view.PropertyTable;
 import ui.view.UpperNodeCanvas;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+
 /**
  * This class is for all update methods and more ;)
  * 
@@ -64,8 +58,8 @@ public class UpdateController {
 			for (AbstractCpsObject o : objects) {
 				if (o instanceof HolonObject) {
 					for (HolonElement he : ((HolonObject) o).getElements()) {
-						Object[] temp = { o.getName() + ", " + o.getId(), he.getId(), he.getEleName(), he.getEnergy(),
-								he.getFlexibility(), he.getAmount(), he.getActive(), he.getActiveFlex() };
+						Object[] temp = {o.getName() + ", " + o.getId(), he.getId(), he.getEleName(), he.getEnergyPerElement(),
+								he.getFlexibleEnergyAvailablePerElement(), he.getAmount(), he.isActive(), he.isFlexible()};
 						table.addRow(temp);
 					}
 				}
@@ -74,9 +68,9 @@ public class UpdateController {
 			AbstractCpsObject o = objects.get(0);
 			if (o instanceof HolonObject) {
 				for (HolonElement he : ((HolonObject) o).getElements()) {
-					Object[] temp = { he.getId(), he.getEleName(), he.getEnergy(), he.getFlexibility(), he.getAmount(),
-							he.getActive(), he.getActiveFlex() };
-					table.addRow(temp);
+					Object[] temp = {he.getId(), he.getEleName(), he.getEnergyPerElement(), he.getFlexibleEnergyAvailablePerElement(), he.getAmount(),
+							he.isActive(), he.isFlexible()};
+                    table.addRow(temp);
 				}
 			}
 		}
@@ -206,13 +200,11 @@ public class UpdateController {
 	 * @return selected CpsObject
 	 */
 	public AbstractCpsObject getActualCps() {
-		AbstractCpsObject tempCps = null;
-		if (model.getSelectedCpsObjects().size() == 1) {
+        AbstractCpsObject tempCps;
+        if (model.getSelectedCpsObjects().size() == 1) {
 			tempCps = model.getSelectedCpsObjects().get(0);
 		} else {
-			// tempCps = model.getSelectedCpsObject();
 			int tempID = model.getSelectedObjectID();
-			// System.out.println(model.getSelectedObjectID());
 			tempCps = controller.searchByID(tempID);
 		}
 		return tempCps;
@@ -329,9 +321,9 @@ public class UpdateController {
 			Object[] tempCapacity = { Languages.getLanguage()[81], model.getSelectedEdge().getCapacity() };
 			model.getPropertyTable().addRow(tempCapacity);
 			// Status displayed
-			Object[] tempStatus = { Languages.getLanguage()[82], model.getSelectedEdge().getState() };
-			model.getPropertyTable().addRow(tempStatus);
-			// For edges, the only possible editable cell is the max
+            Object[] tempStatus = {Languages.getLanguage()[82], model.getSelectedEdge().isWorking()};
+            model.getPropertyTable().addRow(tempStatus);
+            // For edges, the only possible editable cell is the max
 			// flow
 			model.getPropertyTable().setCellEditable(0, 1, false);
 			model.getPropertyTable().setCellEditable(2, 1, true);

+ 941 - 997
src/ui/model/Model.java

@@ -1,1016 +1,960 @@
 package ui.model;
 
-import java.awt.Color;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Hashtable;
-import java.util.LinkedList;
-import java.util.List;
-
-import javax.swing.JTable;
-
-import com.google.gson.Gson;
-import com.google.gson.GsonBuilder;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-
 import TypeAdapter.AbstractCpsObjectAdapter;
 import TypeAdapter.ColorAdapter;
 import TypeAdapter.PairAdapter;
 import TypeAdapter.PositionAdapter;
-import classes.AbstractCpsObject;
-import classes.Category;
-import classes.CpsEdge;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonSwitch;
-import classes.Pair;
-import classes.Position;
+import classes.*;
+import com.google.gson.Gson;
+import com.google.gson.GsonBuilder;
+import com.google.gson.JsonObject;
 import interfaces.CategoryListener;
 import interfaces.GraphListener;
 import interfaces.ObjectListener;
+import ui.view.*;
 
-import ui.view.Console;
-import ui.view.DefaulTable;
-import ui.view.PropertyTable;
-import ui.view.StatisticGraphPanel;
-import ui.view.StatisticPanel;
+import javax.swing.*;
+import java.awt.*;
+import java.util.*;
+import java.util.List;
 
 /**
  * The Class Model is the class where everything is saved. All changes made to
  * the Data is managed via a controller.
- * 
- * @author Gruppe14
  *
+ * @author Gruppe14
  */
 public class Model {
 
-	// Canvas Attributes
-	private String imgPath = "";
-	private int backgroundMode = 0;
-	private int backgroundWidth = 0;
-	private int backgroundHeight = 0;
-	private int canvasX = 1000;
-	private int canvasY = 1000;
-
-	// Global Variables
-	private static int sCALE = 50; // Picture Scale
-	private static int sCALEdIV2 = sCALE / 2;
-	private static int holonBodysCALE = 100; // Picture Scale
-	private static final int ITERATIONS = 100;
-	private int curIteration = 0;
-	private LinkedList<Color> subNetColors = new LinkedList<>();
-	// ID of the Selected Object
-	private AbstractCpsObject selectedCpsObject = null;
-	private HolonElement selectedHolonElement;
-	private CpsEdge selectedEdge;
-	private ArrayList<AbstractCpsObject> selectedObjects = new ArrayList<AbstractCpsObject>();
-	private ArrayList<AbstractCpsObject> clipboardObjects = new ArrayList<AbstractCpsObject>();
-	private Console console;
-	private HashMap<Integer, ArrayList<HolonElement>> eleToDelete;
-	// Capacity for Edge
-	private float maxCapacity;
-
-	// Table for HolonElements --> all cells are editable
-	private JTable tableHolonElement;
-
-	private ArrayList<GraphListener> graphListeners = new ArrayList<GraphListener>();
-	// Iteration Speed
-	private int timerSpeed = 1000;
-
-	private int selectedID = 0;
-	// number of the current autosave
-	private int autoSaveNr = -1;
-	// number of max simultaneous autosaves
-	private int numberOfSaves = 35;
-	// if the simulation is running and has not been reseted
-	private boolean isSimRunning = false;
-	// if the console log of the program should be displayed
-	private boolean showConsoleLog = true;
-	/*
-	 * Array of all categories in the model. It is set by default with the
-	 * categories ENERGY, BUILDINGS and COMPONENTS
-	 */
-	private ArrayList<Category> categories;
-
-	/*
-	 * Array of all HolonObj and HolonSwitches, that should be tracked through
-	 * out the statistics tab
-	 */
-	private ArrayList<AbstractCpsObject> trackedObjects;
-
-	/*
-	 * Array of all CpsObjects in our canvas. It is set by default as an empty
-	 * list.
-	 */
-	private ArrayList<AbstractCpsObject> objectsOnCanvas;
-
-	private HashMap<String, Integer> cgIdx;
-	private HashMap<Integer, Integer> cvsObjIdx;
-
-	/*
-	 * Array of all CpsObjects in our canvas. It is set by default as an empty
-	 * list.
-	 */
-	private ArrayList<CpsEdge> edgesOnCanvas;
-
-	/*
-	 * Array for all Listeners
-	 */
-	private List<CategoryListener> categoryListeners;
-	private List<ObjectListener> objectListeners;
-
-	private PropertyTable tableModelHolonElementMulti;
-	private PropertyTable tableModelHolonElementSingle;
-	private DefaulTable tableModelProperties;
-	public String[] colNames = { "Field", "Information" };
-	/*
-	 * Object that runs the Algorithm
-	 */
-	private Object algorithm = null;
-	private int selectedHolonBody;
-
-	// Statistic Graph Data
-	private Hashtable<String, StatisticGraphPanel> statisticGraphTable = new Hashtable<String, StatisticGraphPanel>();
-	private HashMap<Integer, CpsUpperNode> hashcodeMap = new HashMap<>();
-	private ArrayList<JsonObject> statisticData = new ArrayList<>();
-
-	private Gson gson;
-
-	private StatisticPanel statPanel;
-
-	/**
-	 * Constructor for the model. It initializes the categories and
-	 * objectsOnCanvas by default values. Listeners are also initialized by
-	 * default values.
-	 */
-	public Model() {
-		setCategories(new ArrayList<Category>());
-		setObjectsOnCanvas(new ArrayList<AbstractCpsObject>());
-		setEdgesOnCanvas(new ArrayList<CpsEdge>());
-		setCategoryListeners(new LinkedList<CategoryListener>());
-		setObjectListeners(new LinkedList<ObjectListener>());
-		setCgIdx(new HashMap<String, Integer>());
-		setCvsObjIdx(new HashMap<Integer, Integer>());
-		setClipboradObjects(new ArrayList<AbstractCpsObject>());
-		setTrackingObj(new ArrayList<AbstractCpsObject>());
-		setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
-		setSingleTable(new PropertyTable());
-		setMultiTable(new PropertyTable());
-		setPropertyTable(new DefaulTable(1000, colNames.length));
-		getPropertyTable().setColumnIdentifiers(colNames);
-		setTableHolonElement(new JTable());
-		initGson();
-	}
-
-	/**
-	 * Returns all Categories.
-	 * 
-	 * @return the categories
-	 */
-	public ArrayList<Category> getCategories() {
-		return categories;
-	}
-
-	/**
-	 * Sets all Categories.
-	 * 
-	 * @param categories
-	 *            the categories to set
-	 */
-	public void setCategories(ArrayList<Category> categories) {
-		this.categories = categories;
-	}
-
-	/**
-	 * Transform the Arraylist of categories into a string of all objectName
-	 * with a separation (',') between each name.
-	 * 
-	 * @return String of all names separeted by ','
-	 */
-	public String toStringCat() {
-		String text = "";
-		for (int i = 0; i < categories.size(); i++) {
-			if (text == "") {
-				text = categories.get(i).getName();
-			} else {
-				text = text + ", " + categories.get(i).getName();
-			}
-		}
-		return text;
-	}
-
-	/**
-	 * Returns all Objects on the Canvas.
-	 * 
-	 * @return the objectsOnCanvas
-	 */
-	public ArrayList<AbstractCpsObject> getObjectsOnCanvas() {
-		return objectsOnCanvas;
-	}
-
-	/**
-	 * Sets all Objects on the Canvas.
-	 * 
-	 * @param objectsOnCanvas
-	 *            the objectsOnCanvas to set
-	 */
-	public void setObjectsOnCanvas(ArrayList<AbstractCpsObject> objectsOnCanvas) {
-		this.objectsOnCanvas = objectsOnCanvas;
-	}
-
-	/**
-	 * Get all Edges on the Canvas.
-	 * 
-	 * @return the objectsOnCanvas
-	 */
-	public ArrayList<CpsEdge> getEdgesOnCanvas() {
-		return edgesOnCanvas;
-	}
-
-	/**
-	 * Adds an Edge to The Canvas.
-	 * 
-	 * @param edge
-	 *            the edgesOnCanvas to add
-	 */
-	public void addEdgeOnCanvas(CpsEdge edge) {
-		this.edgesOnCanvas.add(edge);
-	}
-
-	/**
-	 * Remove an edge from the Canvas.
-	 * 
-	 * @param edge
-	 *            the edge to remove
-	 */
-	public void removeEdgesOnCanvas(CpsEdge edge) {
-		this.edgesOnCanvas.remove(edge);
-	}
-
-	/**
-	 * Sets the edges on the Canvas.
-	 * 
-	 * @param arrayList
-	 *            the edgesOnCanvas to set
-	 */
-	public void setEdgesOnCanvas(ArrayList<CpsEdge> arrayList) {
-		this.edgesOnCanvas = arrayList;
-	}
-
-	/**
-	 * Returns the ObjectListener.
-	 * 
-	 * @return the objectListeners
-	 */
-	public List<ObjectListener> getObjectListeners() {
-		return objectListeners;
-	}
-
-	/**
-	 * Sets the ObjectListener.
-	 * 
-	 * @param linkedList
-	 *            the objectListeners to set
-	 */
-	public void setObjectListeners(LinkedList<ObjectListener> linkedList) {
-		this.objectListeners = linkedList;
-	}
-
-	/**
-	 * Returns the CategorieListener.
-	 * 
-	 * @return the categoryListeners
-	 */
-	public List<CategoryListener> getCategoryListeners() {
-		return categoryListeners;
-	}
-
-	/**
-	 * Sets the CategorieListener.
-	 * 
-	 * @param linkedList
-	 *            the categoryListeners to set
-	 */
-	public void setCategoryListeners(LinkedList<CategoryListener> linkedList) {
-		this.categoryListeners = linkedList;
-	}
-
-	/**
-	 * Set the ID of the selected Object 0 = no Object is selected.
-	 * 
-	 * @param id
-	 *            the ID
-	 * 
-	 */
-	public void setSelectedObjectID(int id) {
-		this.selectedID = id;
-	}
-
-	/**
-	 * Returns the ID of the selected Object 0 = no Object is selected.
-	 * 
-	 * @return ID
-	 */
-	public int getSelectedObjectID() {
-		return selectedID;
-	}
-
-	/**
-	 * Returns the Selected Cps Object.
-	 * 
-	 * @return selected Cps Object
-	 */
-	public AbstractCpsObject getSelectedCpsObject() {
-		return selectedCpsObject;
-	}
-
-	/**
-	 * Set the Selected Objecs.
-	 * 
-	 * @param selectedCpsObject
-	 *            Objects that are selected
-	 */
-	public void setSelectedCpsObject(AbstractCpsObject selectedCpsObject) {
-		this.selectedCpsObject = selectedCpsObject;
-	}
-
-	/**
-	 * Returns all selected Objects on the Canvas.
-	 * 
-	 * @return The selected Objects
-	 */
-	public ArrayList<AbstractCpsObject> getSelectedCpsObjects() {
-		return selectedObjects;
-	}
-
-	/**
-	 * Returns all selected Objects on the Canvas.
-	 * 
-	 * @return The selected Objects
-	 */
-	public void setSelectedCpsObjects(ArrayList<AbstractCpsObject> arr) {
-		this.selectedObjects = arr;
-	}
-
-	/**
-	 * Returns the Selected Holon Element.
-	 * 
-	 * @return selected Holon Element
-	 */
-	public HolonElement getSelectedHolonElement() {
-		return selectedHolonElement;
-	}
-
-	/**
-	 * Sets the Selecte HolonElement.
-	 * 
-	 * @param selectedHolonElement
-	 *            that is Selected
-	 */
-	public void setSelectedHolonElement(HolonElement selectedHolonElement) {
-		this.selectedHolonElement = selectedHolonElement;
-	}
-
-	/**
-	 * Returns the sCale (Scale for the Images).
-	 * 
-	 * @return sCALE
-	 */
-	public int getScale() {
-		return sCALE;
-	}
-
-	/**
-	 * Returns sCALEdIV2 (The Scale divided by 2).
-	 * 
-	 * @return sCALEdIV2
-	 */
-	public int getScaleDiv2() {
-		return sCALEdIV2;
-	}
-
-	/**
-	 * Sets the Image Scale.
-	 * 
-	 * @param scale
-	 *            for the image
-	 */
-	public void setScale(int scale) {
-		sCALE = scale;
-		if ((sCALE & 1) == 0)
-			sCALEdIV2 = sCALE / 2;
-		else
-			sCALEdIV2 = (sCALE + 1) / 2;
-	}
-
-	/**
-	 * Returns ITERATIONS.
-	 * 
-	 * @return ITERATIONS
-	 */
-	public int getIterations() {
-		return ITERATIONS;
-	}
-
-	/**
-	 * sets the current Iteration.
-	 * 
-	 * @param curIT
-	 *            the current Iteration
-	 */
-	public void setCurIteration(int curIT) {
-		this.curIteration = curIT;
-		notifyGraphListeners();
-	}
-
-	private void notifyGraphListeners() {
-		for (GraphListener gl : graphListeners) {
-			gl.repaintTree();
-		}
-
-	}
-
-	/**
-	 * Returns cURiTERATION.
-	 * 
-	 * @return cURiTERATION
-	 */
-	public int getCurIteration() {
-		return curIteration;
-	}
-
-	/**
-	 * Set the selected Edge.
-	 * 
-	 * @param edge
-	 *            that is selected
-	 * 
-	 */
-	public void setSelectedEdge(CpsEdge edge) {
-		this.selectedEdge = edge;
-	}
-
-	/**
-	 * Returns the selected Edge.
-	 * 
-	 * @return selectedEdge
-	 */
-	public CpsEdge getSelectedEdge() {
-		return selectedEdge;
-	}
-
-	/**
-	 * Returns the Categorie Index.
-	 * 
-	 * @return the cgIdx
-	 */
-	public HashMap<String, Integer> getCgIdx() {
-		return cgIdx;
-	}
-
-	/**
-	 * Sets the Categorie Index.
-	 * 
-	 * @param cgIdx
-	 *            the cgIdx to set
-	 */
-	public void setCgIdx(HashMap<String, Integer> cgIdx) {
-		this.cgIdx = cgIdx;
-	}
-
-	/**
-	 * Returns the CanvasObject Index.
-	 * 
-	 * @return the cvsObjIdx
-	 */
-	public HashMap<Integer, Integer> getCvsObjIdx() {
-		return cvsObjIdx;
-	}
-
-	/**
-	 * Sets the CanvasObject Index.
-	 * 
-	 * @param cvsObjIdx
-	 *            the cvsObjIdx to set
-	 */
-	public void setCvsObjIdx(HashMap<Integer, Integer> cvsObjIdx) {
-		this.cvsObjIdx = cvsObjIdx;
-	}
-
-	/**
-	 * Sets the auto save Number.
-	 * 
-	 * @param autoSaveNr
-	 *            the auto save number
-	 */
-	public void setAutoSaveNr(int autoSaveNr) {
-		this.autoSaveNr = autoSaveNr;
-	}
-
-	/**
-	 * Returns the auto save Number.
-	 * 
-	 * @return the auto save Number
-	 */
-	public int getAutoSaveNr() {
-		return autoSaveNr;
-	}
-
-	/**
-	 * Returns the Number of Saves.
-	 * 
-	 * @return the numberOfSaves
-	 */
-	public int getNumberOfSaves() {
-		return numberOfSaves;
-	}
-
-	/**
-	 * Set the Number of Saves.
-	 * 
-	 * @param numberOfSaves
-	 *            the numberOfSaves to set
-	 */
-	public void setNumberOfSaves(int numberOfSaves) {
-		this.numberOfSaves = numberOfSaves;
-	}
-
-	/**
-	 * Sets the ClipboardObjects.
-	 * 
-	 * @param c
-	 *            Array of Objects
-	 */
-	public void setClipboradObjects(ArrayList<AbstractCpsObject> c) {
-		this.clipboardObjects = c;
-	}
-
-	/**
-	 * Returns all Objects in the Clipboard.
-	 * 
-	 * @return Objects in the Clipboard
-	 */
-	public ArrayList<AbstractCpsObject> getClipboradObjects() {
-		return clipboardObjects;
-	}
-
-	/**
-	 * Sets the console.
-	 * 
-	 * @param console
-	 *            the console
-	 */
-	public void setConsole(Console console) {
-		this.console = console;
-	}
-
-	/**
-	 * Returns the Console.
-	 * 
-	 * @return console the console
-	 */
-	public Console getConsole() {
-		return console;
-	}
-
-	/**
-	 * @return the maxCapacity
-	 */
-	public float getMaxCapacity() {
-		return maxCapacity;
-	}
-
-	/**
-	 * @param maxCapacity
-	 *            the maxCapacity to set
-	 */
-	public void setMaxCapacity(float maxCapacity) {
-		this.maxCapacity = maxCapacity;
-	}
-
-	/**
-	 * Sets the Interval in ms between each Iteration.
-	 * 
-	 * @param t
-	 *            speed for the Iterations
-	 */
-	public void setTimerSpeed(int t) {
-		this.timerSpeed = t;
-	}
-
-	/**
-	 * get the Interval in ms between each Iteration.
-	 * 
-	 * @return timerSpeed speed for the Iterations
-	 */
-	public int getTimerSpeed() {
-		return this.timerSpeed;
-	}
-
-	/**
-	 * Get Canvas X Size.
-	 * 
-	 * @return the cANVAS_X
-	 */
-	public int getCanvasX() {
-		return canvasX;
-	}
-
-	/**
-	 * Set Canvas X Size.
-	 * 
-	 * @param canvasX
-	 *            the cANVAS_X to set
-	 */
-	public void setCanvasX(int canvasX) {
-		this.canvasX = canvasX;
-	}
-
-	/**
-	 * get Canvas Y size.
-	 * 
-	 * @return the cANVAS_Y
-	 */
-	public int getCanvasY() {
-		return canvasY;
-	}
-
-	/**
-	 * Set Canvas Y size.
-	 * 
-	 * @param canvasY
-	 *            the cANVAS_Y to set
-	 */
-	public void setCanvasY(int canvasY) {
-		this.canvasY = canvasY;
-	}
-
-	/**
-	 * get the Algorithm.
-	 * 
-	 * @return the Algorithm
-	 */
-	public Object getAlgorithm() {
-		return algorithm;
-	}
-
-	/**
-	 * Set the Algorithm.
-	 * 
-	 * @param obj
-	 *            the Algorithm
-	 */
-	public void setAlgorithm(Object obj) {
-		this.algorithm = null;
-		this.algorithm = obj;
-	}
-
-	/**
-	 * Add a SubNetColor.
-	 * 
-	 * @param c
-	 *            the Color
-	 */
-	public void addSubNetColor(Color c) {
-		this.subNetColors.add(c);
-	}
-
-	/**
-	 * Get the SubNetColors.
-	 * 
-	 * @return SubNetColors
-	 */
-	public LinkedList<Color> getSubNetColors() {
-		return this.subNetColors;
-	}
-
-	public void setTrackingObj(ArrayList<AbstractCpsObject> toTrack) {
-		trackedObjects = toTrack;
-	}
-
-	public ArrayList<AbstractCpsObject> getTrackingObj() {
-		return trackedObjects;
-	}
-
-	public void addGraphListener(GraphListener gl) {
-		graphListeners.add(gl);
-	}
-
-	public void setEleToDelete(HashMap<Integer, ArrayList<HolonElement>> theHash) {
-		this.eleToDelete = theHash;
-	}
-
-	public HashMap<Integer, ArrayList<HolonElement>> getEleToDelete() {
-		return this.eleToDelete;
-	}
-
-	public void setSingleTable(PropertyTable pt) {
-		this.tableModelHolonElementSingle = pt;
-	}
-
-	public PropertyTable getSingleTable() {
-		return this.tableModelHolonElementSingle;
-	}
-
-	public PropertyTable getMultiTable() {
-		return this.tableModelHolonElementMulti;
-	}
-
-	public void setMultiTable(PropertyTable pt) {
-		this.tableModelHolonElementMulti = pt;
-	}
-
-	public void addObjectsToGraphListeners() {
-		for (GraphListener gl : graphListeners) {
-			gl.addTrackedObject(trackedObjects);
-			gl.repaintTree();
-		}
-	}
-
-	public DefaulTable getPropertyTable() {
-		return this.tableModelProperties;
-	}
-
-	public void setPropertyTable(DefaulTable pt) {
-		this.tableModelProperties = pt;
-	}
-
-	public JTable getTableHolonElement() {
-		return tableHolonElement;
-	}
-
-	public void setTableHolonElement(JTable tableHolonElement) {
-		this.tableHolonElement = tableHolonElement;
-	}
-
-	/**
-	 * Sets the HolonBody Scale.
-	 * 
-	 * @param scale
-	 *            for the HolonBody
-	 */
-	public void setHolonBodyScale(int scale) {
-		holonBodysCALE = scale;
-	}
-
-	/**
-	 * Returns the sCale (Scale for the Images).
-	 * 
-	 * @return sCALE
-	 */
-	public int getHolonBodyScale() {
-		return holonBodysCALE;
-	}
-
-	/**
-	 * Sets the ID of the selected HolonBody
-	 * 
-	 * @param i
-	 *            int
-	 */
-	public void setSelectedHolonBody(int i) {
-		selectedHolonBody = i;
-	}
-
-	/**
-	 * Returns the ID of the selected HolonBody
-	 * 
-	 * @return selectedHolonBody
-	 */
-	public int getSelectedHolonBody() {
-		return selectedHolonBody;
-	}
-
-	/**
-	 * get all Switches
-	 */
-	public ArrayList<HolonSwitch> getSwitches() {
-		ArrayList<HolonSwitch> switches = new ArrayList<>();
-		for (AbstractCpsObject obj : getObjectsOnCanvas()) {
-			if (obj instanceof HolonSwitch) {
-				switches.add((HolonSwitch) obj);
-			} else if (obj instanceof CpsUpperNode) {
-				getSwitchesRec(((CpsUpperNode) obj).getNodes(), switches);
-			}
-		}
-		return switches;
-	}
-
-	/**
-	 * get the Amount of Switches help function
-	 *
-	 * @param objects
-	 *            objects
-	 * @param switches
-	 *            List of switches
-	 */
-	private ArrayList<HolonSwitch> getSwitchesRec(ArrayList<AbstractCpsObject> objects,
-			ArrayList<HolonSwitch> switches) {
-		for (AbstractCpsObject obj : objects) {
-			if (obj instanceof HolonSwitch) {
-				switches.add((HolonSwitch) obj);
-			} else if (obj instanceof CpsUpperNode) {
-				getSwitchesRec(((CpsUpperNode) obj).getNodes(), switches);
-			}
-		}
-		return switches;
-	}
-
-	/**
-	 * Returns the Path for the background Image of the Canvas.
-	 * 
-	 * @return imgPath the Path
-	 */
-	public String getCanvasImagePath() {
-		return imgPath;
-	}
-
-	/**
-	 * Returns the mode for the background Image of the Canvas.
-	 * 
-	 * 0 take size of the Image 1 stretch the Image 2 Custom Image size
-	 * 
-	 * @return backgroundMode the mode
-	 */
-	public int getCanvasImageMode() {
-		return backgroundMode;
-	}
-
-	/**
-	 * Returns the Custom width of the background Image of the Canvas.
-	 * 
-	 * @return backgroundWidth the Width
-	 */
-	public int getCanvasImageWidth() {
-		return backgroundWidth;
-	}
-
-	/**
-	 * Returns the Custom height of the background Image of the Canvas.
-	 * 
-	 * @return backgroundHeight the height
-	 */
-	public int getCanvasImageHeight() {
-		return backgroundHeight;
-	}
-
-	/**
-	 * Set the Path for the background Image of the Canvas.
-	 * 
-	 * @param paththe
-	 *            Path
-	 */
-	public void setCanvasImagePath(String path) {
-		imgPath = path;
-	}
-
-	/**
-	 * Set the mode for the background Image of the Canvas.
-	 * 
-	 * 0 take size of the Image, 1 stretch the Image, 2 Custom Image size
-	 * 
-	 * @param backgroundMode
-	 *            the mode
-	 */
-	public void setCanvasImageMode(int mode) {
-		backgroundMode = mode;
-	}
-
-	/**
-	 * Set the Custom width of the background Image of the Canvas.
-	 * 
-	 * @param width
-	 *            the Width
-	 */
-	public void setCanvasImageWidth(int width) {
-		backgroundWidth = width;
-	}
-
-	/**
-	 * Set the Custom height of the background Image of the Canvas.
-	 * 
-	 * @param height
-	 *            the height
-	 */
-	public void setCanvasImageHeight(int height) {
-		backgroundHeight = height;
-	}
-
-	/**
-	 * Set the graphtable for Statistic Graphs
-	 */
-	public void setGraphTable(Hashtable<String, StatisticGraphPanel> gT) {
-		statisticGraphTable = gT;
-	}
-
-	/**
-	 * Returns the graphtable for Statistic Graphs.
-	 */
-	public Hashtable<String, StatisticGraphPanel> getGraphTable() {
-		return statisticGraphTable;
-	}
-
-	/**
-	 * Returns if the Simulation is running.
-	 */
-	public boolean getIsSimRunning() {
-		return isSimRunning;
-	}
-
-	/**
-	 * Sets isSimRunning.
-	 * 
-	 * @param isRunning
-	 */
-	public void setIsSimRunning(boolean isRunning) {
-		isSimRunning = isRunning;
-	}
-
-	/**
-	 * @return the statisticData
-	 */
-	public ArrayList<JsonObject> getStatisticData() {
-		return statisticData;
-	}
-
-	/**
-	 * @param statisticData
-	 *            the statisticData to set
-	 */
-	public void setStatisticData(ArrayList<JsonObject> statisticData) {
-		this.statisticData = statisticData;
-	}
-
-	/**
-	 * Returns showConsoleLog.
-	 */
-	public boolean getShowConsoleLog() {
-		return this.showConsoleLog;
-	}
-
-	/**
-	 * Sets showConsoleLog.
-	 * 
-	 * @param showConsoleLog
-	 */
-	public void setShowConsoleLog(boolean showConsoleLog) {
-		this.showConsoleLog = showConsoleLog;
-
-	}
-
-	/**
-	 * Initialize the Gson with wanted parameters
-	 */
-	private void initGson() {
-		// TODO Auto-generated method stub
-		GsonBuilder builder = new GsonBuilder();
-		builder.serializeNulls();
-		builder.excludeFieldsWithoutExposeAnnotation();
-		builder.setPrettyPrinting();
-		builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter());
-		builder.registerTypeAdapter(Position.class, new PositionAdapter());
-		builder.registerTypeAdapter(Color.class, new ColorAdapter());
-		builder.registerTypeAdapter(Pair.class, new PairAdapter());
-		// use the builder and make a instance of the Gson
-		this.setGson(builder.create());
-
-	}
-
-	/**
-	 * @return the gson
-	 */
-	public Gson getGson() {
-		return gson;
-	}
-
-	/**
-	 * @param gson
-	 *            the gson to set
-	 */
-	public void setGson(Gson gson) {
-		this.gson = gson;
-	}
-
-	public void setStatPanel(StatisticPanel sP) {
-		statPanel = sP;
-	}
-
-	public StatisticPanel getStatPanel() {
-		return statPanel;
-	}
-
-	/**
-	 * @return the hashcodeMap
-	 */
-	public HashMap<Integer, CpsUpperNode> getHashcodeMap() {
-		return hashcodeMap;
-	}
-
-	/**
-	 * @param hashcodeMap the hashcodeMap to set
-	 */
-	public void setHashcodeMap(HashMap<Integer, CpsUpperNode> hashcodeMap) {
-		this.hashcodeMap = hashcodeMap;
-	}
+    private static final int ITERATIONS = 100;
+    // Global Variables
+    private static int sCALE = 50; // Picture Scale
+    private static int sCALEdIV2 = sCALE / 2;
+    private static int holonBodysCALE = 100; // Picture Scale
+    public String[] colNames = {"Field", "Information"};
+    // Canvas Attributes
+    private String imgPath = "";
+    private int backgroundMode = 0;
+    private int backgroundWidth = 0;
+    private int backgroundHeight = 0;
+    private int canvasX = 1000;
+    private int canvasY = 1000;
+    private int curIteration = 0;
+    private LinkedList<Color> subNetColors = new LinkedList<>();
+    // ID of the Selected Object
+    private AbstractCpsObject selectedCpsObject = null;
+    private HolonElement selectedHolonElement;
+    private CpsEdge selectedEdge;
+    private ArrayList<AbstractCpsObject> selectedObjects = new ArrayList<>();
+    private ArrayList<AbstractCpsObject> clipboardObjects = new ArrayList<>();
+    private Console console;
+    private HashMap<Integer, ArrayList<HolonElement>> eleToDelete;
+    // Capacity for Edge
+    private float maxCapacity;
+    // Table for HolonElements --> all cells are editable
+    private JTable tableHolonElement;
+    private ArrayList<GraphListener> graphListeners = new ArrayList();
+    // Iteration Speed
+    private int timerSpeed = 1000;
+    private int selectedID = 0;
+    // number of the current autosave
+    private int autoSaveNr = -1;
+    // number of max simultaneous autosaves
+    private int numberOfSaves = 35;
+    // whether the simulation is running and has not been reseted
+    private boolean isSimRunning = false;
+    // whether the console log of the program should be displayed
+    private boolean showConsoleLog = true;
+    // whether the console log of the program should be displayed
+    private boolean useFlexibleDevices = true;
+
+    /*
+     * Array of all categories in the model. It is set by default with the
+     * categories ENERGY, BUILDINGS and COMPONENTS
+     */
+    private ArrayList<Category> categories;
+    /*
+     * Array of all HolonObj and HolonSwitches, that should be tracked through
+     * out the statistics tab
+     */
+    private ArrayList<AbstractCpsObject> trackedObjects;
+    /*
+     * Array of all CpsObjects in our canvas. It is set by default as an empty
+     * list.
+     */
+    private ArrayList<AbstractCpsObject> objectsOnCanvas;
+    private HashMap<String, Integer> cgIdx;
+    private HashMap<Integer, Integer> cvsObjIdx;
+    /*
+     * Array of all CpsObjects in our canvas. It is set by default as an empty
+     * list.
+     */
+    private ArrayList<CpsEdge> edgesOnCanvas;
+    /*
+     * Array for all Listeners
+     */
+    private List<CategoryListener> categoryListeners;
+    private List<ObjectListener> objectListeners;
+    private PropertyTable tableModelHolonElementMulti;
+    private PropertyTable tableModelHolonElementSingle;
+    private DefaulTable tableModelProperties;
+    /*
+     * Object that runs the Algorithm
+     */
+    private Object algorithm = null;
+    private int selectedHolonBody;
+
+    // Statistic Graph Data
+    private Hashtable<String, StatisticGraphPanel> statisticGraphTable = new Hashtable<>();
+    private HashMap<Integer, CpsUpperNode> hashcodeMap = new HashMap<>();
+    private ArrayList<JsonObject> statisticData = new ArrayList<>();
+
+    private Gson gson;
+
+    private StatisticPanel statPanel;
+
+    /**
+     * Constructor for the model. It initializes the categories and
+     * objectsOnCanvas by default values. Listeners are also initialized by
+     * default values.
+     */
+    public Model() {
+        setCategories(new ArrayList<>());
+        setObjectsOnCanvas(new ArrayList<>());
+        setEdgesOnCanvas(new ArrayList<>());
+        setCategoryListeners(new LinkedList<>());
+        setObjectListeners(new LinkedList<>());
+        setCgIdx(new HashMap<>());
+        setCvsObjIdx(new HashMap<>());
+        setClipboradObjects(new ArrayList<>());
+        setTrackingObj(new ArrayList<>());
+        setEleToDelete(new HashMap<>());
+        setSingleTable(new PropertyTable());
+        setMultiTable(new PropertyTable());
+        setPropertyTable(new DefaulTable(1000, colNames.length));
+        getPropertyTable().setColumnIdentifiers(colNames);
+        setTableHolonElement(new JTable());
+        initGson();
+    }
+
+    /**
+     * Returns all Categories.
+     *
+     * @return the categories
+     */
+    public ArrayList<Category> getCategories() {
+        return categories;
+    }
+
+    /**
+     * Sets all Categories.
+     *
+     * @param categories the categories to set
+     */
+    public void setCategories(ArrayList<Category> categories) {
+        this.categories = categories;
+    }
+
+    /**
+     * Transform the Arraylist of categories into a string of all objectName
+     * with a separation (',') between each name.
+     *
+     * @return String of all names separeted by ','
+     */
+    public String toStringCat() {
+        String text = "";
+        for (int i = 0; i < categories.size(); i++) {
+            if (text.equals("")) {
+                text = categories.get(i).getName();
+            } else {
+                text = text + ", " + categories.get(i).getName();
+            }
+        }
+        return text;
+    }
+
+    /**
+     * Returns all Objects on the Canvas.
+     *
+     * @return the objectsOnCanvas
+     */
+    public ArrayList<AbstractCpsObject> getObjectsOnCanvas() {
+        return objectsOnCanvas;
+    }
+
+    /**
+     * Sets all Objects on the Canvas.
+     *
+     * @param objectsOnCanvas the objectsOnCanvas to set
+     */
+    public void setObjectsOnCanvas(ArrayList<AbstractCpsObject> objectsOnCanvas) {
+        this.objectsOnCanvas = objectsOnCanvas;
+    }
+
+    /**
+     * Get all Edges on the Canvas.
+     *
+     * @return the objectsOnCanvas
+     */
+    public ArrayList<CpsEdge> getEdgesOnCanvas() {
+        return edgesOnCanvas;
+    }
+
+    /**
+     * Sets the edges on the Canvas.
+     *
+     * @param arrayList the edgesOnCanvas to set
+     */
+    public void setEdgesOnCanvas(ArrayList<CpsEdge> arrayList) {
+        this.edgesOnCanvas = arrayList;
+    }
+
+    /**
+     * Adds an Edge to The Canvas.
+     *
+     * @param edge the edgesOnCanvas to add
+     */
+    public void addEdgeOnCanvas(CpsEdge edge) {
+        this.edgesOnCanvas.add(edge);
+    }
+
+    /**
+     * Remove an edge from the Canvas.
+     *
+     * @param edge the edge to remove
+     */
+    public void removeEdgesOnCanvas(CpsEdge edge) {
+        this.edgesOnCanvas.remove(edge);
+    }
+
+    /**
+     * Returns the ObjectListener.
+     *
+     * @return the objectListeners
+     */
+    public List<ObjectListener> getObjectListeners() {
+        return objectListeners;
+    }
+
+    /**
+     * Sets the ObjectListener.
+     *
+     * @param linkedList the objectListeners to set
+     */
+    public void setObjectListeners(LinkedList<ObjectListener> linkedList) {
+        this.objectListeners = linkedList;
+    }
+
+    /**
+     * Returns the CategorieListener.
+     *
+     * @return the categoryListeners
+     */
+    public List<CategoryListener> getCategoryListeners() {
+        return categoryListeners;
+    }
+
+    /**
+     * Sets the CategorieListener.
+     *
+     * @param linkedList the categoryListeners to set
+     */
+    public void setCategoryListeners(LinkedList<CategoryListener> linkedList) {
+        this.categoryListeners = linkedList;
+    }
+
+    /**
+     * Returns the ID of the selected Object 0 = no Object is selected.
+     *
+     * @return ID
+     */
+    public int getSelectedObjectID() {
+        return selectedID;
+    }
+
+    /**
+     * Set the ID of the selected Object 0 = no Object is selected.
+     *
+     * @param id the ID
+     */
+    public void setSelectedObjectID(int id) {
+        this.selectedID = id;
+    }
+
+    /**
+     * Returns the Selected Cps Object.
+     *
+     * @return selected Cps Object
+     */
+    public AbstractCpsObject getSelectedCpsObject() {
+        return selectedCpsObject;
+    }
+
+    /**
+     * Set the Selected Objecs.
+     *
+     * @param selectedCpsObject Objects that are selected
+     */
+    public void setSelectedCpsObject(AbstractCpsObject selectedCpsObject) {
+        this.selectedCpsObject = selectedCpsObject;
+    }
+
+    /**
+     * Returns all selected Objects on the Canvas.
+     *
+     * @return The selected Objects
+     */
+    public ArrayList<AbstractCpsObject> getSelectedCpsObjects() {
+        return selectedObjects;
+    }
+
+    /**
+     * Returns all selected Objects on the Canvas.
+     *
+     * @return The selected Objects
+     */
+    public void setSelectedCpsObjects(ArrayList<AbstractCpsObject> arr) {
+        this.selectedObjects = arr;
+    }
+
+    /**
+     * Returns the Selected Holon Element.
+     *
+     * @return selected Holon Element
+     */
+    public HolonElement getSelectedHolonElement() {
+        return selectedHolonElement;
+    }
+
+    /**
+     * Sets the Selecte HolonElement.
+     *
+     * @param selectedHolonElement that is Selected
+     */
+    public void setSelectedHolonElement(HolonElement selectedHolonElement) {
+        this.selectedHolonElement = selectedHolonElement;
+    }
+
+    /**
+     * Returns the sCale (Scale for the Images).
+     *
+     * @return sCALE
+     */
+    public int getScale() {
+        return sCALE;
+    }
+
+    /**
+     * Sets the Image Scale.
+     *
+     * @param scale for the image
+     */
+    public void setScale(int scale) {
+        sCALE = scale;
+        if ((sCALE & 1) == 0)
+            sCALEdIV2 = sCALE / 2;
+        else
+            sCALEdIV2 = (sCALE + 1) / 2;
+    }
+
+    /**
+     * Returns sCALEdIV2 (The Scale divided by 2).
+     *
+     * @return sCALEdIV2
+     */
+    public int getScaleDiv2() {
+        return sCALEdIV2;
+    }
+
+    /**
+     * Returns ITERATIONS.
+     *
+     * @return ITERATIONS
+     */
+    public int getIterations() {
+        return ITERATIONS;
+    }
+
+    private void notifyGraphListeners() {
+        for (GraphListener gl : graphListeners) {
+            gl.repaintTree();
+        }
+
+    }
+
+    /**
+     * Returns cURiTERATION.
+     *
+     * @return cURiTERATION
+     */
+    public int getCurIteration() {
+        return curIteration;
+    }
+
+    /**
+     * sets the current Iteration.
+     *
+     * @param curIT the current Iteration
+     */
+    public void setCurIteration(int curIT) {
+        this.curIteration = curIT;
+        notifyGraphListeners();
+    }
+
+    /**
+     * Returns the selected Edge.
+     *
+     * @return selectedEdge
+     */
+    public CpsEdge getSelectedEdge() {
+        return selectedEdge;
+    }
+
+    /**
+     * Set the selected Edge.
+     *
+     * @param edge that is selected
+     */
+    public void setSelectedEdge(CpsEdge edge) {
+        this.selectedEdge = edge;
+    }
+
+    /**
+     * Returns the Categorie Index.
+     *
+     * @return the cgIdx
+     */
+    public HashMap<String, Integer> getCgIdx() {
+        return cgIdx;
+    }
+
+    /**
+     * Sets the Categorie Index.
+     *
+     * @param cgIdx the cgIdx to set
+     */
+    public void setCgIdx(HashMap<String, Integer> cgIdx) {
+        this.cgIdx = cgIdx;
+    }
+
+    /**
+     * Returns the CanvasObject Index.
+     *
+     * @return the cvsObjIdx
+     */
+    public HashMap<Integer, Integer> getCvsObjIdx() {
+        return cvsObjIdx;
+    }
+
+    /**
+     * Sets the CanvasObject Index.
+     *
+     * @param cvsObjIdx the cvsObjIdx to set
+     */
+    public void setCvsObjIdx(HashMap<Integer, Integer> cvsObjIdx) {
+        this.cvsObjIdx = cvsObjIdx;
+    }
+
+    /**
+     * Returns the auto save Number.
+     *
+     * @return the auto save Number
+     */
+    public int getAutoSaveNr() {
+        return autoSaveNr;
+    }
+
+    /**
+     * Sets the auto save Number.
+     *
+     * @param autoSaveNr the auto save number
+     */
+    public void setAutoSaveNr(int autoSaveNr) {
+        this.autoSaveNr = autoSaveNr;
+    }
+
+    /**
+     * Returns the Number of Saves.
+     *
+     * @return the numberOfSaves
+     */
+    public int getNumberOfSaves() {
+        return numberOfSaves;
+    }
+
+    /**
+     * Set the Number of Saves.
+     *
+     * @param numberOfSaves the numberOfSaves to set
+     */
+    public void setNumberOfSaves(int numberOfSaves) {
+        this.numberOfSaves = numberOfSaves;
+    }
+
+    /**
+     * Returns all Objects in the Clipboard.
+     *
+     * @return Objects in the Clipboard
+     */
+    public ArrayList<AbstractCpsObject> getClipboradObjects() {
+        return clipboardObjects;
+    }
+
+    /**
+     * Sets the ClipboardObjects.
+     *
+     * @param c Array of Objects
+     */
+    public void setClipboradObjects(ArrayList<AbstractCpsObject> c) {
+        this.clipboardObjects = c;
+    }
+
+    /**
+     * Returns the Console.
+     *
+     * @return console the console
+     */
+    public Console getConsole() {
+        return console;
+    }
+
+    /**
+     * Sets the console.
+     *
+     * @param console the console
+     */
+    public void setConsole(Console console) {
+        this.console = console;
+    }
+
+    /**
+     * @return the maxCapacity
+     */
+    public float getMaxCapacity() {
+        return maxCapacity;
+    }
+
+    /**
+     * @param maxCapacity the maxCapacity to set
+     */
+    public void setMaxCapacity(float maxCapacity) {
+        this.maxCapacity = maxCapacity;
+    }
+
+    /**
+     * get the Interval in ms between each Iteration.
+     *
+     * @return timerSpeed speed for the Iterations
+     */
+    public int getTimerSpeed() {
+        return this.timerSpeed;
+    }
+
+    /**
+     * Sets the Interval in ms between each Iteration.
+     *
+     * @param t speed for the Iterations
+     */
+    public void setTimerSpeed(int t) {
+        this.timerSpeed = t;
+    }
+
+    /**
+     * Get Canvas X Size.
+     *
+     * @return the cANVAS_X
+     */
+    public int getCanvasX() {
+        return canvasX;
+    }
+
+    /**
+     * Set Canvas X Size.
+     *
+     * @param canvasX the cANVAS_X to set
+     */
+    public void setCanvasX(int canvasX) {
+        this.canvasX = canvasX;
+    }
+
+    /**
+     * get Canvas Y size.
+     *
+     * @return the cANVAS_Y
+     */
+    public int getCanvasY() {
+        return canvasY;
+    }
+
+    /**
+     * Set Canvas Y size.
+     *
+     * @param canvasY the cANVAS_Y to set
+     */
+    public void setCanvasY(int canvasY) {
+        this.canvasY = canvasY;
+    }
+
+    /**
+     * get the Algorithm.
+     *
+     * @return the Algorithm
+     */
+    public Object getAlgorithm() {
+        return algorithm;
+    }
+
+    /**
+     * Set the Algorithm.
+     *
+     * @param obj the Algorithm
+     */
+    public void setAlgorithm(Object obj) {
+        this.algorithm = null;
+        this.algorithm = obj;
+    }
+
+    /**
+     * Add a SubNetColor.
+     *
+     * @param c the Color
+     */
+    public void addSubNetColor(Color c) {
+        this.subNetColors.add(c);
+    }
+
+    /**
+     * Get the SubNetColors.
+     *
+     * @return SubNetColors
+     */
+    public LinkedList<Color> getSubNetColors() {
+        return this.subNetColors;
+    }
+
+    public ArrayList<AbstractCpsObject> getTrackingObj() {
+        return trackedObjects;
+    }
+
+    public void setTrackingObj(ArrayList<AbstractCpsObject> toTrack) {
+        trackedObjects = toTrack;
+    }
+
+    public void addGraphListener(GraphListener gl) {
+        graphListeners.add(gl);
+    }
+
+    public HashMap<Integer, ArrayList<HolonElement>> getEleToDelete() {
+        return this.eleToDelete;
+    }
+
+    public void setEleToDelete(HashMap<Integer, ArrayList<HolonElement>> theHash) {
+        this.eleToDelete = theHash;
+    }
+
+    public PropertyTable getSingleTable() {
+        return this.tableModelHolonElementSingle;
+    }
+
+    public void setSingleTable(PropertyTable pt) {
+        this.tableModelHolonElementSingle = pt;
+    }
+
+    public PropertyTable getMultiTable() {
+        return this.tableModelHolonElementMulti;
+    }
+
+    public void setMultiTable(PropertyTable pt) {
+        this.tableModelHolonElementMulti = pt;
+    }
+
+    public void addObjectsToGraphListeners() {
+        for (GraphListener gl : graphListeners) {
+            gl.addTrackedObject(trackedObjects);
+            gl.repaintTree();
+        }
+    }
+
+    public DefaulTable getPropertyTable() {
+        return this.tableModelProperties;
+    }
+
+    public void setPropertyTable(DefaulTable pt) {
+        this.tableModelProperties = pt;
+    }
+
+    public JTable getTableHolonElement() {
+        return tableHolonElement;
+    }
+
+    public void setTableHolonElement(JTable tableHolonElement) {
+        this.tableHolonElement = tableHolonElement;
+    }
+
+    /**
+     * Returns the sCale (Scale for the Images).
+     *
+     * @return sCALE
+     */
+    public int getHolonBodyScale() {
+        return holonBodysCALE;
+    }
+
+    /**
+     * Sets the HolonBody Scale.
+     *
+     * @param scale for the HolonBody
+     */
+    public void setHolonBodyScale(int scale) {
+        holonBodysCALE = scale;
+    }
+
+    /**
+     * Returns the ID of the selected HolonBody
+     *
+     * @return selectedHolonBody
+     */
+    public int getSelectedHolonBody() {
+        return selectedHolonBody;
+    }
+
+    /**
+     * Sets the ID of the selected HolonBody
+     *
+     * @param i int
+     */
+    public void setSelectedHolonBody(int i) {
+        selectedHolonBody = i;
+    }
+
+    /**
+     * get all Switches
+     */
+    public ArrayList<HolonSwitch> getSwitches() {
+        ArrayList<HolonSwitch> switches = new ArrayList<>();
+        for (AbstractCpsObject obj : getObjectsOnCanvas()) {
+            if (obj instanceof HolonSwitch) {
+                switches.add((HolonSwitch) obj);
+            } else if (obj instanceof CpsUpperNode) {
+                getSwitchesRec(((CpsUpperNode) obj).getNodes(), switches);
+            }
+        }
+        return switches;
+    }
+
+    /**
+     * get the Amount of Switches help function
+     *
+     * @param objects  objects
+     * @param switches List of switches
+     */
+    private ArrayList<HolonSwitch> getSwitchesRec(ArrayList<AbstractCpsObject> objects,
+                                                  ArrayList<HolonSwitch> switches) {
+        for (AbstractCpsObject obj : objects) {
+            if (obj instanceof HolonSwitch) {
+                switches.add((HolonSwitch) obj);
+            } else if (obj instanceof CpsUpperNode) {
+                getSwitchesRec(((CpsUpperNode) obj).getNodes(), switches);
+            }
+        }
+        return switches;
+    }
+
+    /**
+     * Returns the Path for the background Image of the Canvas.
+     *
+     * @return imgPath the Path
+     */
+    public String getCanvasImagePath() {
+        return imgPath;
+    }
+
+    /**
+     * Set the Path for the background Image of the Canvas.
+     *
+     * @param path the Path
+     */
+    public void setCanvasImagePath(String path) {
+        imgPath = path;
+    }
+
+    /**
+     * Returns the mode for the background Image of the Canvas.
+     * <p>
+     * 0 take size of the Image 1 stretch the Image 2 Custom Image size
+     *
+     * @return backgroundMode the mode
+     */
+    public int getCanvasImageMode() {
+        return backgroundMode;
+    }
+
+    /**
+     * Set the mode for the background Image of the Canvas.
+     * <p>
+     * 0 take size of the Image, 1 stretch the Image, 2 Custom Image size
+     *
+     * @param mode the backgroundMode
+     */
+    public void setCanvasImageMode(int mode) {
+        backgroundMode = mode;
+    }
+
+    /**
+     * Returns the Custom width of the background Image of the Canvas.
+     *
+     * @return backgroundWidth the Width
+     */
+    public int getCanvasImageWidth() {
+        return backgroundWidth;
+    }
+
+    /**
+     * Set the Custom width of the background Image of the Canvas.
+     *
+     * @param width the Width
+     */
+    public void setCanvasImageWidth(int width) {
+        backgroundWidth = width;
+    }
+
+    /**
+     * Returns the Custom height of the background Image of the Canvas.
+     *
+     * @return backgroundHeight the height
+     */
+    public int getCanvasImageHeight() {
+        return backgroundHeight;
+    }
+
+    /**
+     * Set the Custom height of the background Image of the Canvas.
+     *
+     * @param height the height
+     */
+    public void setCanvasImageHeight(int height) {
+        backgroundHeight = height;
+    }
+
+    /**
+     * Returns the graphtable for Statistic Graphs.
+     */
+    public Hashtable<String, StatisticGraphPanel> getGraphTable() {
+        return statisticGraphTable;
+    }
+
+    /**
+     * Set the graphtable for Statistic Graphs
+     */
+    public void setGraphTable(Hashtable<String, StatisticGraphPanel> gT) {
+        statisticGraphTable = gT;
+    }
+
+    /**
+     * Returns if the Simulation is running.
+     */
+    public boolean getIsSimRunning() {
+        return isSimRunning;
+    }
+
+    /**
+     * Sets isSimRunning.
+     *
+     * @param isRunning
+     */
+    public void setIsSimRunning(boolean isRunning) {
+        isSimRunning = isRunning;
+    }
+
+    /**
+     * @return the statisticData
+     */
+    public ArrayList<JsonObject> getStatisticData() {
+        return statisticData;
+    }
+
+    /**
+     * @param statisticData the statisticData to set
+     */
+    public void setStatisticData(ArrayList<JsonObject> statisticData) {
+        this.statisticData = statisticData;
+    }
+
+    /**
+     * Returns showConsoleLog.
+     */
+    public boolean getShowConsoleLog() {
+        return this.showConsoleLog;
+    }
+
+    /**
+     * Sets showConsoleLog.
+     *
+     * @param showConsoleLog
+     */
+    public void setShowConsoleLog(boolean showConsoleLog) {
+        this.showConsoleLog = showConsoleLog;
+    }
+
+
+    public boolean useFlexibleDevices() {
+        return this.useFlexibleDevices;
+    }
+
+    public void setUseFlexibleDevices(boolean useFlexibleDevices) {
+        this.useFlexibleDevices = useFlexibleDevices;
+    }
+
+    /**
+     * Initialize the Gson with wanted parameters
+     */
+    private void initGson() {
+        GsonBuilder builder = new GsonBuilder();
+        builder.serializeNulls();
+        builder.excludeFieldsWithoutExposeAnnotation();
+        builder.setPrettyPrinting();
+        builder.registerTypeAdapter(AbstractCpsObject.class, new AbstractCpsObjectAdapter());
+        builder.registerTypeAdapter(Position.class, new PositionAdapter());
+        builder.registerTypeAdapter(Color.class, new ColorAdapter());
+        builder.registerTypeAdapter(Pair.class, new PairAdapter());
+        // use the builder and make a instance of the Gson
+        this.setGson(builder.create());
+
+    }
+
+    /**
+     * @return the gson
+     */
+    public Gson getGson() {
+        return gson;
+    }
+
+    /**
+     * @param gson the gson to set
+     */
+    public void setGson(Gson gson) {
+        this.gson = gson;
+    }
+
+    public StatisticPanel getStatPanel() {
+        return statPanel;
+    }
+
+    public void setStatPanel(StatisticPanel sP) {
+        statPanel = sP;
+    }
+
+    /**
+     * @return the hashcodeMap
+     */
+    public HashMap<Integer, CpsUpperNode> getHashcodeMap() {
+        return hashcodeMap;
+    }
+
+    /**
+     * @param hashcodeMap the hashcodeMap to set
+     */
+    public void setHashcodeMap(HashMap<Integer, CpsUpperNode> hashcodeMap) {
+        this.hashcodeMap = hashcodeMap;
+    }
 }

+ 372 - 0
src/ui/view/AbstractCanvas.java

@@ -0,0 +1,372 @@
+package ui.view;
+
+import classes.*;
+import ui.controller.Control;
+import ui.controller.UpdateController;
+import ui.model.Model;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.MouseEvent;
+import java.io.File;
+import java.util.ArrayList;
+import java.util.TimerTask;
+
+/**
+ * Collection of methods and values needed in both <code>MyCanvas</code> and <code>UpperNodeCanvas</code>
+ * <p>
+ * Although Java works on references we chose to add explicit return values for clearer code understanding in most cases
+ *
+ * @author: I. Dix
+ */
+public abstract class AbstractCanvas extends JPanel {
+    final JMenuItem itemDelete = new JMenuItem(Languages.getLanguage()[98]);
+    final JMenuItem itemCut = new JMenuItem(Languages.getLanguage()[95]);
+    final JMenuItem itemCopy = new JMenuItem(Languages.getLanguage()[96]);
+    final JMenuItem itemPaste = new JMenuItem(Languages.getLanguage()[97]);
+    final JMenuItem itemGroup = new JMenuItem(Languages.getLanguage()[99]);
+    final JMenuItem itemUngroup = new JMenuItem(Languages.getLanguage()[100]);
+    final JMenuItem itemTrack = new JMenuItem(Languages.getLanguage()[101]);
+    final JMenuItem itemUntrack = new JMenuItem(Languages.getLanguage()[102]);
+    final int ANIMTIME = 500; // animation Time
+    private final int animFPS = 60;
+    final int animDelay = 1000 / animFPS; // animation Delay
+    protected Model model;
+    protected Control controller;
+    protected int x = 0;
+    protected int y = 0;
+    // Selection
+    AbstractCpsObject tempCps = null;
+    UpdateController updCon;
+    // PopUpMenu
+    JPopupMenu popmenu = new JPopupMenu();
+    // Tooltip
+    boolean toolTip; // Tooltip on or off
+    Position toolTipPos = new Position(); // Tooltip Position
+    String toolTipText = "";
+    ArrayList<HolonElement> dataSelected = new ArrayList<>();
+    ArrayList<AbstractCpsObject> tempSelected = new ArrayList<>();
+    boolean[] showedInformation = new boolean[5];
+    boolean dragging = false; // for dragging
+    boolean dragged = false; // if an object/objects was/were dragged
+    boolean drawEdge = false; // for drawing edges
+    boolean doMark = false; // for double click
+    CpsEdge edgeHighlight = null;
+    Point mousePosition = new Point(); // Mouse Position when
+    ArrayList<Position> savePos;
+    // edge Object Start Point
+    int cx, cy;
+    int sx, sy; // Mark Coords
+    Position unPos;
+    // Animation
+    Timer animT; // animation Timer
+    int animDuration = ANIMTIME; // animation Duration
+    int animSteps = animDuration / animDelay; // animation Steps;
+    ArrayList<AbstractCpsObject> animCps = null;
+    // Graphics
+    Image img = null; // Contains the image to draw on the Canvas
+    Graphics2D g2; // For Painting
+    float scalediv20;
+    // Mouse
+    private boolean click = false;
+
+    // ------------------------------------------ METHODS ------------------------------------------
+    String paintEdge(CpsEdge con, String maxCap) {
+        if (con.getA().getId() != model.getSelectedObjectID() && con.getB().getId() != model.getSelectedObjectID()
+                && con != edgeHighlight) {
+            if (con.getConnected() == CpsEdge.CON_UPPER_NODE) {
+                setEdgeState(con);
+            } else {
+                g2.setColor(Color.DARK_GRAY);
+                g2.setStroke(new BasicStroke(2));
+            }
+            g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
+                    con.getB().getPosition().y);
+
+            maxCap = setCapacityString(con, maxCap);
+
+            if (showedInformation[0]) {
+                if (con.getConnected() == CpsEdge.CON_UPPER_NODE
+                        || con.getConnected() == CpsEdge.CON_UPPER_NODE_AND_INSIDE) {
+                    g2.drawString(con.getFlow() + "/" + maxCap,
+                            (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
+                            (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
+                } else {
+                    g2.drawString("not connected", (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
+                            (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
+                }
+            }
+        }
+
+        return maxCap;
+    }
+
+
+    void setEdgeState(CpsEdge con) {
+        if (con.isWorking()) {
+            g2.setColor(Color.GREEN);
+            if (con.getCapacity() != CpsEdge.CAPACITY_INFINITE) {
+                g2.setStroke(new BasicStroke(Math.min(((con.getFlow() / con.getCapacity() * 3) + 1), 4)));
+            }
+        } else {
+            g2.setColor(Color.RED);
+            g2.setStroke(new BasicStroke(2));
+        }
+    }
+
+
+    String setCapacityString(CpsEdge con, String maxCap) {
+        if (con.getCapacity() == -1) {
+            maxCap = Character.toString('\u221e');
+        } else if (con.getCapacity() == -2) {
+            maxCap = "???";
+        } else {
+            maxCap = String.valueOf(con.getCapacity());
+        }
+        return maxCap;
+    }
+
+
+    String drawEdgeLine(CpsEdge con, String maxCap) {
+        if (con.getA().getId() == model.getSelectedObjectID()
+                || model.getSelectedCpsObjects().contains(con.getA()) || tempSelected.contains(con.getA())
+                || con.getB().getId() == model.getSelectedObjectID()
+                || model.getSelectedCpsObjects().contains(con.getB())
+                || tempSelected.contains(con.getB()) && con != edgeHighlight) {
+            g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
+                    con.getB().getPosition().y);
+
+            maxCap = setCapacityString(con, maxCap);
+
+            if (showedInformation[0]) {
+                if (con.getConnected() == CpsEdge.CON_UPPER_NODE
+                        || con.getConnected() == CpsEdge.CON_UPPER_NODE_AND_INSIDE) {
+                    g2.drawString(con.getFlow() + "/" + maxCap,
+                            (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
+                            (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
+                } else {
+                    g2.drawString("not connected",
+                            (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
+                            (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
+                }
+            }
+        }
+
+        return maxCap;
+    }
+
+
+    void setEdgePictureAndHighlighting(AbstractCpsObject cps) {
+        // node image
+        if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
+                || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
+            img = new ImageIcon(this.getClass().getResource("/Images/node_selected.png")).getImage();
+        } else {
+            if (cps instanceof HolonSwitch) {
+                if (((HolonSwitch) cps).getActiveAt()[model.getCurIteration()]) {
+                    ((HolonSwitch) cps).setAutoState(true);
+                } else {
+                    ((HolonSwitch) cps).setAutoState(false);
+                }
+            }
+            // Highlighting
+            if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
+                    || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
+                g2.setColor(Color.BLUE);
+                g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20),
+                        (int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20),
+                        (int) (controller.getScale() + (scalediv20 * 2)),
+                        (int) (controller.getScale() + (scalediv20 * 2)));
+                if (showedInformation[1] && cps instanceof HolonObject) {
+                    g2.setColor(Color.BLACK);
+                    float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
+                    g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - controller.getScaleDiv2(),
+                            cps.getPosition().y - controller.getScaleDiv2() - 10);
+                }
+            } else if (cps instanceof HolonObject) {
+                g2.setColor(((HolonObject) cps).getColor());
+
+                g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20),
+                        (int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20),
+                        (int) (controller.getScale() + (scalediv20 * 2)),
+                        (int) (controller.getScale() + (scalediv20 * 2)));
+
+                if (showedInformation[1]) {
+                    g2.setColor(Color.BLACK);
+                    float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
+                    g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - controller.getScaleDiv2(),
+                            cps.getPosition().y - controller.getScaleDiv2() - 10);
+                }
+            }
+            // draw image
+            File checkPath = new File(cps.getImage());
+            if (checkPath.exists()) {
+                img = new ImageIcon(cps.getImage()).getImage();
+            } else {
+                img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage();
+            }
+        }
+    }
+
+
+    void drawMarker() {
+        if (sx > x && sy > y) {
+            g2.drawRect(x, y, sx - x, sy - y);
+        } else if (sx < x && sy < y) {
+            g2.drawRect(sx, sy, x - sx, y - sy);
+        } else if (sx >= x) {
+            g2.drawRect(x, sy, sx - x, y - sy);
+        } else if (sy >= y) {
+            g2.drawRect(sx, y, x - sx, sy - y);
+        }
+    }
+
+
+    void showTooltip(Graphics g) {
+        if (toolTip) {
+            g2.setColor(new Color(255, 225, 150));
+            g2.setStroke(new BasicStroke(1));
+            int textWidth = g.getFontMetrics().stringWidth(toolTipText) + 2; // Text
+            // width
+
+            // fixed x and y Position to the screen
+            int fixXPos = toolTipPos.x - (textWidth >> 1) + model.getScaleDiv2();
+            int fixYPos = toolTipPos.y;
+
+            if (fixXPos < 0) {
+                fixXPos = 0;
+            } else if (fixXPos + textWidth + 1 > this.getWidth()) {
+                fixXPos -= (fixXPos + textWidth + 1) - this.getWidth();
+            }
+            if (fixYPos + 16 > this.getHeight()) {
+                fixYPos -= (fixYPos + 16) - this.getHeight();
+            }
+            g2.fillRect(fixXPos, fixYPos, textWidth, 15);
+            g2.setColor(Color.BLACK);
+            g2.drawRect(fixXPos, fixYPos, textWidth, 15);
+            g2.drawString(toolTipText, fixXPos + 2, fixYPos + 12);
+        }
+    }
+
+
+    void setConsoleTextAfterSelect(AbstractCpsObject cps) {
+        if (model.getShowConsoleLog()) {
+            controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
+            controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
+            controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
+            controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
+        }
+    }
+
+
+    void setRightClickMenu(MouseEvent e) {
+        if (e.getButton() == MouseEvent.BUTTON3) {
+            if (tempCps != null) {
+                itemDelete.setEnabled(true);
+                itemCut.setEnabled(true);
+                itemCopy.setEnabled(true);
+                if (tempCps != null) {
+                    itemGroup.setEnabled(true);
+                    itemTrack.setEnabled(true);
+                    itemUntrack.setEnabled(true);
+                }
+                if (tempCps instanceof CpsUpperNode)
+                    itemUngroup.setEnabled(true);
+                else
+                    itemUngroup.setEnabled(false);
+                if (model.getSelectedCpsObjects().size() == 0) {
+                    controller.addSelectedObject(tempCps);
+                }
+            } else {
+                itemCut.setEnabled(false);
+                itemCopy.setEnabled(false);
+                itemDelete.setEnabled(false);
+                itemGroup.setEnabled(false);
+                itemUngroup.setEnabled(false);
+                itemTrack.setEnabled(false);
+                itemUntrack.setEnabled(false);
+            }
+            mousePosition = this.getMousePosition();
+            popmenu.show(e.getComponent(), e.getX(), e.getY());
+        }
+    }
+
+
+    void markObjects() {
+        if (doMark) {
+            doMark = false;
+            for (AbstractCpsObject cps : tempSelected) {
+                if (!model.getSelectedCpsObjects().contains(cps)) {
+                    controller.addSelectedObject(cps);
+                }
+            }
+            controller.getObjectsInDepth();
+            tempSelected.clear();
+        }
+    }
+
+    int[] determineMousePositionOnEdge(CpsEdge p) {
+        int lx, ly, hx, hy;
+
+        if (p.getA().getPosition().x > p.getB().getPosition().x) {
+            hx = p.getA().getPosition().x + model.getScaleDiv2() + 7;
+            lx = p.getB().getPosition().x + model.getScaleDiv2() - 7;
+        } else {
+            lx = p.getA().getPosition().x + model.getScaleDiv2() - 7;
+            hx = p.getB().getPosition().x + model.getScaleDiv2() + 7;
+        }
+        if (p.getA().getPosition().y > p.getB().getPosition().y) {
+            hy = p.getA().getPosition().y + model.getScaleDiv2() + 7;
+            ly = p.getB().getPosition().y + model.getScaleDiv2() - 7;
+        } else {
+            ly = p.getA().getPosition().y + model.getScaleDiv2() - 7;
+            hy = p.getB().getPosition().y + model.getScaleDiv2() + 7;
+        }
+
+        return new int[]{lx, ly, hx, hy};
+    }
+
+
+    /**
+     * Checks if a double click was made.
+     *
+     * @return true if doublecklick, false if not
+     */
+    boolean doubleClick() {
+        if (click) {
+            click = false;
+            return true;
+        } else {
+            click = true;
+            java.util.Timer t = new java.util.Timer("doubleclickTimer", false);
+            t.schedule(new TimerTask() {
+                @Override
+                public void run() {
+                    click = false;
+                }
+            }, 500);
+        }
+        return false;
+    }
+
+    boolean setToolTipInfoAndPosition(boolean on, AbstractCpsObject cps) {
+        if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
+            on = true;
+            toolTipPos.x = cps.getPosition().x - controller.getScaleDiv2();
+            toolTipPos.y = cps.getPosition().y + controller.getScaleDiv2();
+            toolTipText = cps.getName() + ", " + cps.getId();
+        }
+
+        return on;
+    }
+
+
+    abstract void drawDeleteEdge();
+
+
+    void triggerUpdateController() {
+        updCon.paintProperties(tempCps);
+        updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
+        updCon.refreshTableProperties(model.getPropertyTable());
+    }
+}

+ 51 - 73
src/ui/view/AddElementPopUp.java

@@ -1,26 +1,14 @@
 package ui.view;
 
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.FlowLayout;
-import java.awt.Image;
-import javax.swing.JButton;
-import javax.swing.JDialog;
-import javax.swing.JPanel;
-import javax.swing.border.EmptyBorder;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JTextField;
-import javax.swing.ImageIcon;
-
 import classes.AbstractCpsObject;
 import classes.HolonElement;
 import classes.HolonObject;
-import java.awt.event.ActionListener;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import java.awt.*;
 import java.awt.event.KeyEvent;
 import java.awt.event.KeyListener;
-import java.awt.event.ActionEvent;
 
 /**
  * popup for adding an Holon Element to a holon Object.
@@ -40,12 +28,12 @@ public class AddElementPopUp extends JDialog {
 	private HolonElement hl;
 	private AbstractCpsObject tempCps;
 
-	/**
-	 * Launch the application.
-	 *
-	 * @param args
-	 *            standard
-	 */
+//	/**
+//	 * Launch the application.
+//	 *
+//	 * @param args
+//	 *            standard
+//	 */
 //	public static void main(String[] args) {
 //		try {
 //
@@ -60,8 +48,8 @@ public class AddElementPopUp extends JDialog {
 	/**
 	 * Create the dialog.
 	 */
-	public AddElementPopUp() {
-		super((java.awt.Frame) null, true);
+    AddElementPopUp() {
+        super((java.awt.Frame) null, true);
 		this.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage()
 				.getScaledInstance(30, 30, Image.SCALE_SMOOTH));
 		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
@@ -89,14 +77,10 @@ public class AddElementPopUp extends JDialog {
 		elementName.addKeyListener(new KeyListener() {
 			@Override
 			public void keyPressed(KeyEvent arg0) {
-				// TODO Auto-generated method stub
-
 			}
 
 			@Override
 			public void keyReleased(KeyEvent e) {
-				// TODO Auto-generated method stub
-
 			}
 
 			@Override
@@ -125,43 +109,41 @@ public class AddElementPopUp extends JDialog {
 			getContentPane().add(buttonPane, BorderLayout.SOUTH);
 			{
 				JButton okButton = new JButton("OK");
-				okButton.addActionListener(new ActionListener() {
-					public void actionPerformed(ActionEvent arg0) {
-						boolean repeated = false;
-						for (HolonElement e : ((HolonObject) tempCps).getElements()) {
-							if (elementName.getText().equals(e.getEleName())) {
-								repeated = true;
-								break;
-							}
-						}
-						if (elementName.getText().length() != 0 && !repeated) {
-							try {
-								float energy = Float.parseFloat(providedEnergy.getText().toString());
-								int elementAmount = Integer.parseInt(amount.getText().toString());
-								hl = new HolonElement(elementName.getText().toString(), elementAmount, energy);
-
-								dispose();
-							} catch (NumberFormatException e) {
-								JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[68]);
-							}
-						} else {
-							// JOptionPane.showMessageDialog(new JFrame(),
-							// "Please enter a Name");
-
-							if (elementName.getText().length() == 0) {
-								JLabel errorString = new JLabel(Languages.getLanguage()[69]);
-								errorString.setBounds(240, 8, 100, 20);
-								contentPanel.add(errorString);
-							} else if (repeated) {
-								JLabel errorString = new JLabel(Languages.getLanguage()[70]);
-								errorString.setBounds(250, 8, 100, 20);
-								contentPanel.add(errorString);
-							}
-							elementName.setBackground(new Color(255, 50, 50));
-						}
-					}
-				});
-				okButton.setActionCommand("OK");
+                okButton.addActionListener(arg0 -> {
+                    boolean repeated = false;
+                    for (HolonElement e : ((HolonObject) tempCps).getElements()) {
+                        if (elementName.getText().equals(e.getEleName())) {
+                            repeated = true;
+                            break;
+                        }
+                    }
+                    if (elementName.getText().length() != 0 && !repeated) {
+                        try {
+                            float energy = Float.parseFloat(providedEnergy.getText());
+                            int elementAmount = Integer.parseInt(amount.getText());
+                            hl = new HolonElement(elementName.getText(), elementAmount, energy);
+
+                            dispose();
+                        } catch (NumberFormatException e) {
+                            JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[68]);
+                        }
+                    } else {
+                        // JOptionPane.showMessageDialog(new JFrame(),
+                        // "Please enter a Name");
+
+                        if (elementName.getText().length() == 0) {
+                            JLabel errorString = new JLabel(Languages.getLanguage()[69]);
+                            errorString.setBounds(240, 8, 100, 20);
+                            contentPanel.add(errorString);
+                        } else if (repeated) {
+                            JLabel errorString = new JLabel(Languages.getLanguage()[70]);
+                            errorString.setBounds(250, 8, 100, 20);
+                            contentPanel.add(errorString);
+                        }
+                        elementName.setBackground(new Color(255, 50, 50));
+                    }
+                });
+                okButton.setActionCommand("OK");
 				buttonPane.add(okButton);
 				getRootPane().setDefaultButton(okButton);
 			}
@@ -169,12 +151,8 @@ public class AddElementPopUp extends JDialog {
 				JButton cancelButton = new JButton(Languages.getLanguage()[71]);
 				cancelButton.setActionCommand("Cancel");
 				buttonPane.add(cancelButton);
-				cancelButton.addActionListener(new ActionListener() {
-					public void actionPerformed(ActionEvent e) {
-						dispose();
-					}
-				});
-			}
+                cancelButton.addActionListener(e -> dispose());
+            }
 		}
 
 	}
@@ -185,8 +163,8 @@ public class AddElementPopUp extends JDialog {
 	 * @param cps
 	 *            actual Cps
 	 */
-	public void setActualCps(AbstractCpsObject cps) {
-		this.tempCps = cps;
+    void setActualCps(AbstractCpsObject cps) {
+        this.tempCps = cps;
 	}
 
 	/**

+ 88 - 124
src/ui/view/AddObjectPopUp.java

@@ -1,36 +1,22 @@
 package ui.view;
 
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.FlowLayout;
-import java.awt.Image;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URLDecoder;
-import java.security.CodeSource;
-import java.util.ArrayList;
-
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import javax.swing.filechooser.FileNameExtensionFilter;
-
 import classes.AbstractCpsObject;
 import classes.HolonElement;
 import classes.HolonObject;
 import classes.Pair;
 import ui.controller.Control;
 
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import javax.swing.filechooser.FileNameExtensionFilter;
+import java.awt.*;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.io.*;
+import java.util.ArrayList;
+
 /**
  * Popup for adding a Holon Object to a Category.
  * 
@@ -39,7 +25,6 @@ import ui.controller.Control;
 public class AddObjectPopUp extends JDialog {
 
 	private static final long serialVersionUID = 1L;
-	private final JPanel contentPanel = new JPanel();
 	private AddElementPopUp addElement;
 	private JTextField objectName;
 	private JTextField sourcePath;
@@ -47,7 +32,7 @@ public class AddObjectPopUp extends JDialog {
 	private DefaultListModel listModel;
 	private JList list;
 	private String imagePath;
-	private HolonObject theObject;
+	//	private HolonObject theObject;
 	private Control controller;
 	private File selectedFile = null;
 	private String filePath = " ";
@@ -57,12 +42,12 @@ public class AddObjectPopUp extends JDialog {
 	private boolean editState;
 	private boolean imageChanged = false;
 
-	/**
-	 * Launch the application.
-	 *
-	 * @param args
-	 *            standard
-	 */
+//	/**
+//	 * Launch the application.
+//	 *
+//	 * @param args
+//	 *            standard
+//	 */
 //	public static void main(String[] args) {
 //		try {
 //			AddObjectPopUp dialog = new AddObjectPopUp(false, null, null);
@@ -83,7 +68,7 @@ public class AddObjectPopUp extends JDialog {
 	 * @param cat
 	 *            the categorie
 	 */
-	public AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat) {
+	AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat) {
 		toEdit = obj;
 		editState = edit;
 		this.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage()
@@ -91,6 +76,7 @@ public class AddObjectPopUp extends JDialog {
 		setBounds(100, 100, 450, 342);
 		setLocationRelativeTo(this.getParent());
 		getContentPane().setLayout(new BorderLayout());
+		JPanel contentPanel = new JPanel();
 		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
 		getContentPane().add(contentPanel, BorderLayout.CENTER);
 		contentPanel.setLayout(null);
@@ -107,13 +93,11 @@ public class AddObjectPopUp extends JDialog {
 			objectName.addKeyListener(new KeyListener() {
 				@Override
 				public void keyPressed(KeyEvent arg0) {
-					// TODO Auto-generated method stub
 
 				}
 
 				@Override
 				public void keyReleased(KeyEvent e) {
-					// TODO Auto-generated method stub
 
 				}
 
@@ -150,14 +134,10 @@ public class AddObjectPopUp extends JDialog {
 			sourcePath.addKeyListener(new KeyListener() {
 				@Override
 				public void keyPressed(KeyEvent arg0) {
-					// TODO Auto-generated method stub
-
 				}
 
 				@Override
 				public void keyReleased(KeyEvent e) {
-					// TODO Auto-generated method stub
-
 				}
 
 				@Override
@@ -176,8 +156,7 @@ public class AddObjectPopUp extends JDialog {
 				sourcePath.setText(filePath);
 				ImageIcon icon = new ImageIcon(
 						new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
-				if (icon != null)
-					lblImagePreview.setIcon(icon);
+				lblImagePreview.setIcon(icon);
 			}
 			sourcePath.setBounds(148, 77, 271, 20);
 			contentPanel.add(sourcePath);
@@ -185,19 +164,17 @@ public class AddObjectPopUp extends JDialog {
 		}
 		{
 			JButton btnAddDefaultElement = new JButton(Languages.getLanguage()[61]);
-			btnAddDefaultElement.addActionListener(new ActionListener() {
-				public void actionPerformed(ActionEvent arg0) {
-					addElement = new AddElementPopUp();
-					addElement.setActualCps(toEdit);
-					addElement.setVisible(true);
-					HolonElement hl = addElement.getElement();
-					hl.setSaving(new Pair<String, String>(givenCategory, objectName.getText()));
-					// if (hl != null) {
-					// hl.setSav(givenCategory);
-					// }
-					// hl.setObj(objectName.getText());
-					addElement(hl);
-				}
+			btnAddDefaultElement.addActionListener(actionEvent -> {
+				addElement = new AddElementPopUp();
+				addElement.setActualCps(toEdit);
+				addElement.setVisible(true);
+				HolonElement hl = addElement.getElement();
+				hl.setSaving(new Pair<>(givenCategory, objectName.getText()));
+				// if (hl != null) {
+				// hl.setSav(givenCategory);
+				// }
+				// hl.setObj(objectName.getText());
+				addElement(hl);
 			});
 
 			btnAddDefaultElement.setBounds(270, 144, 142, 23);
@@ -227,13 +204,11 @@ public class AddObjectPopUp extends JDialog {
 		}
 		{
 			JButton btnNewButton = new JButton(Languages.getLanguage()[62]);
-			btnNewButton.addActionListener(new ActionListener() {
-				public void actionPerformed(ActionEvent e) {
-					int selectedIndex = list.getSelectedIndex();
-					if (selectedIndex != -1) {
-						listModel.remove(selectedIndex);
-						hElements.remove(selectedIndex);
-					}
+			btnNewButton.addActionListener(actionEvent -> {
+				int selectedIndex = list.getSelectedIndex();
+				if (selectedIndex != -1) {
+					listModel.remove(selectedIndex);
+					hElements.remove(selectedIndex);
 				}
 			});
 			btnNewButton.setBounds(270, 182, 142, 27);
@@ -248,7 +223,7 @@ public class AddObjectPopUp extends JDialog {
 				JButton okButton = new JButton("OK");
 				okButton.addMouseListener(new MouseAdapter() {
 					public void mouseClicked(MouseEvent e) {
-						Component frame = null;
+//						Component frame = null;
 						if (objectName.getText().length() > 0) {
 							if (sourcePath.getText().equals(filePath)) {
 								imagePath = filePath;
@@ -272,8 +247,6 @@ public class AddObjectPopUp extends JDialog {
 												objectName.getText(), hElements, imagePath);
 									}
 								} catch (Exception e2) {
-									// TODO: handle exception
-
 								}
 
 								// controller.addObjectCategory(controller.searchCategory(givenCategory),
@@ -301,31 +274,49 @@ public class AddObjectPopUp extends JDialog {
 				JButton cancelButton = new JButton(Languages.getLanguage()[63]);
 				cancelButton.setActionCommand("Cancel");
 				buttonPane.add(cancelButton);
-				cancelButton.addActionListener(new ActionListener() {
-					public void actionPerformed(ActionEvent e) {
-						dispose();
-					}
-				});
+				cancelButton.addActionListener(e -> dispose());
 			}
 		}
 	}
 
+//	/**
+//	 * Get Jar Containing Folder.
+//	 *
+//	 * @param aclass aClass
+//	 * @return String
+//	 * @throws Exception Exception
+//	 */
+//	public static String getJarContainingFolder(Class aclass) throws Exception {
+//		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
+//
+//		File jarFile;
+//
+//		if (codeSource.getLocation() != null) {
+//			jarFile = new File(codeSource.getLocation().toURI());
+//		} else {
+//			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
+//			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
+//			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
+//			jarFile = new File(jarFilePath);
+//		}
+//		return jarFile.getParentFile().getAbsolutePath();
+//	}
+
 	/**
 	 * adds a Holon Element.
-	 * 
+	 *
 	 * @param hl
 	 *            the HolonElement
 	 */
-	public void addElement(HolonElement hl) {
+	private void addElement(HolonElement hl) {
 		hElements.add(hl);
-		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergy() + "U");
+		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergyPerElement() + "U");
 	}
 
 	/**
 	 * Choose the file.
 	 */
-	protected void fileChooser() {
-		// TODO Auto-generated method stub
+	private void fileChooser() {
 		JFileChooser fileChooser = new JFileChooser();
 		FileNameExtensionFilter filter = new FileNameExtensionFilter("png, jpg or jpeg", "png", "jpg", "jpeg");
 		fileChooser.setFileFilter(filter);
@@ -347,9 +338,9 @@ public class AddObjectPopUp extends JDialog {
 	/**
 	 * Copies the File.
 	 */
-	protected void copieFile() {
-		InputStream inStream = null;
-		OutputStream outStream = null;
+	private void copieFile() {
+		InputStream inStream;
+		OutputStream outStream;
 		try {
 			File source = new File(filePath);
 			File dest = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images/");
@@ -366,59 +357,32 @@ public class AddObjectPopUp extends JDialog {
 				outStream.write(buffer, 0, length);
 			}
 
-			if (inStream != null)
-				inStream.close();
-			if (outStream != null)
-				outStream.close();
+			inStream.close();
+			outStream.close();
 			System.out.println("File Copied..");
 		} catch (IOException eex) {
 			eex.printStackTrace();
 		}
 	}
 
-	/**
-	 * Edit the Information.
-	 * 
-	 * @param obj
-	 *            the CpsObject
-	 */
-	public void editInformation(HolonObject obj) {
-		objectName.setText(obj.getName());
-	}
-
-	/**
-	 * Get Jar Containing Folder.
-	 * 
-	 * @param aclass
-	 *            aClass
-	 * @return String
-	 * @throws Exception
-	 *             Exception
-	 */
-	public static String getJarContainingFolder(Class aclass) throws Exception {
-		CodeSource codeSource = aclass.getProtectionDomain().getCodeSource();
-
-		File jarFile;
-
-		if (codeSource.getLocation() != null) {
-			jarFile = new File(codeSource.getLocation().toURI());
-		} else {
-			String path = aclass.getResource(aclass.getSimpleName() + ".class").getPath();
-			String jarFilePath = path.substring(path.indexOf(":") + 1, path.indexOf("!"));
-			jarFilePath = URLDecoder.decode(jarFilePath, "UTF-8");
-			jarFile = new File(jarFilePath);
-		}
-		return jarFile.getParentFile().getAbsolutePath();
-	}
+//	/**
+//	 * Edit the Information.
+//	 *
+//	 * @param obj
+//	 *            the CpsObject
+//	 */
+//	public void editInformation(HolonObject obj) {
+//		objectName.setText(obj.getName());
+//	}
 
-	/**
-	 * Return the Object.
-	 * 
-	 * @return the CpsObject
-	 */
-	public HolonObject getObject() {
-		return theObject;
-	}
+//	/**
+//	 * Return the Object.
+//	 *
+//	 * @return the CpsObject
+//	 */
+//	public HolonObject getObject() {
+//		return theObject;
+//	}
 
 	/**
 	 * Sets the Controller.

+ 9 - 21
src/ui/view/DisplayedInformationPopUp.java

@@ -1,16 +1,10 @@
 package ui.view;
 
-import java.awt.BorderLayout;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
+import ui.controller.Control;
 
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JDialog;
-import javax.swing.JPanel;
+import javax.swing.*;
 import javax.swing.border.EmptyBorder;
-
-import ui.controller.Control;
+import java.awt.*;
 
 /**
  * This Class represents a Popup to edit the shown Information.
@@ -60,24 +54,18 @@ public class DisplayedInformationPopUp extends JDialog {
 
 		objectEnergyCheckbox.setSelected(canvas.getShowedInformation()[1]);
 		connectionCheckbox.setSelected(canvas.getShowedInformation()[0]);
-		btnOk.addActionListener(new ActionListener() {
-			public void actionPerformed(ActionEvent arg0) {
-				setInformation(connectionCheckbox.isSelected(), objectEnergyCheckbox.isSelected(),
-						colorizedBorderCheckbox.isSelected(), nodeOfnodeConnectionCheckbox.isSelected());
-				controller.getSimManager().getFlexiblePane().recalculate();
-				dispose();
-			}
+		btnOk.addActionListener(actionEvent -> {
+			setInformation(connectionCheckbox.isSelected(), objectEnergyCheckbox.isSelected(),
+					colorizedBorderCheckbox.isSelected(), nodeOfnodeConnectionCheckbox.isSelected());
+			controller.getSimManager().getFlexiblePane().recalculate();
+			dispose();
 		});
 		btnOk.setBounds(174, 193, 82, 23);
 		contentPanel.add(btnOk);
 
 		JButton btnCancel = new JButton(Languages.getLanguage()[34]);
 		btnCancel.setActionCommand(Languages.getLanguage()[34]);
-		btnCancel.addActionListener(new ActionListener() {
-			public void actionPerformed(ActionEvent arg0) {
-				dispose();
-			}
-		});
+		btnCancel.addActionListener(actionEvent -> dispose());
 		btnCancel.setBounds(69, 193, 89, 23);
 		contentPanel.add(btnCancel);
 		

+ 9 - 19
src/ui/view/EditEdgesPopUp.java

@@ -1,26 +1,16 @@
 package ui.view;
 
-import java.awt.BorderLayout;
-import java.awt.Font;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-
-import javax.swing.ButtonGroup;
-import javax.swing.JButton;
-import javax.swing.JDialog;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JRadioButton;
-import javax.swing.JTextField;
-import javax.swing.border.EmptyBorder;
-
 import classes.AbstractCpsObject;
 import classes.CpsEdge;
 import classes.CpsUpperNode;
 import ui.controller.Control;
 
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
 /**
  * Popup for Editing Edges.
  * 
@@ -202,9 +192,9 @@ public class EditEdgesPopUp extends JDialog {
 		 */
 		for (CpsEdge edge : controller.getModel().getEdgesOnCanvas()) {
 			edge.setCapacity(cap);
-			edge.setState(true);
-		}
-		for (AbstractCpsObject abs : controller.getModel().getObjectsOnCanvas()) {
+            edge.setWorkingState(true);
+        }
+        for (AbstractCpsObject abs : controller.getModel().getObjectsOnCanvas()) {
 			if (abs instanceof CpsUpperNode) {
 				changeInUpperNode((CpsUpperNode) abs, cap);
 			}

+ 146 - 113
src/ui/view/GUI.java

@@ -33,10 +33,9 @@ import java.util.stream.Collectors;
 /**
  * Graphical User Interface.
  *
- * @param <E> Generic
  * @author Gruppe14
  */
-public class GUI<E> implements CategoryListener {
+public class GUI implements CategoryListener {
 
     private final AlgorithmMenu algorithmMenu;
     private final JMenuBar menuBar = new JMenuBar();
@@ -46,6 +45,7 @@ public class GUI<E> implements CategoryListener {
     private final JMenu mnNewMenuView = new JMenu("View");
     private final JMenu mnHelp = new JMenu("Help");
     private final JCheckBox consoleLogCheckBox = new JCheckBox("Show program console log");
+    private final JCheckBox useFlexibleDevicesCheckBox = new JCheckBox("Automatically use flexible devices");
     private final JMenuItem mntmOpen = new JMenuItem("Open");
     private final JMenuItem mntmNew = new JMenuItem("New");
     private final JMenuItem mntmSave = new JMenuItem("Save");
@@ -58,7 +58,6 @@ public class GUI<E> implements CategoryListener {
     private final JSplitPane splitPaneCanvasConsole = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
     // the tabbed canvas containing the different sub-net tabs of the grid (Main Grid + Nodes of Nodes)
     private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(JTabbedPane.TOP);
-    //    private final JTabbedPane tabbedPaneInnerSplit = new JTabbedPane(JTabbedPane.TOP);
     // the main canvas where we can see the grid currently displayed
     private final JScrollPane canvasSP = new JScrollPane();
     private final JScrollPane scrollPane1 = new JScrollPane();
@@ -160,10 +159,10 @@ public class GUI<E> implements CategoryListener {
     private final JMenuItem mntmEditShowedInformation = new JMenuItem("Edit showed Information");
     private final JMenuItem mntmResetCategory = new JMenuItem("Reset Categories");
     private final JMenu mnLanguage = new JMenu("Language");
-    private final String[] columnNamesMulti = {"Object", "Nr.", "Device", "Energy", "Flexibility", "Quantity", "Activated",
-            "Flex. activated"};
-    private final String[] columnNamesSingle = {"Nr.", "Device", "Energy", "Flexibility", "Quantity", "Activated",
-            "Flex. activated"};
+    private final String[] columnNamesMulti = {"Object", "Nr.", "Device", "Energy", "Flexible Energy Available",
+            "Quantity", "Activated", "Flexible"};
+    private final String[] columnNamesSingle = {"Nr.", "Device", "Energy", "Flexible Energy Available", "Quantity",
+            "Activated", "Flexible"};
     private final ArrayList<PropertyTable> tables = new ArrayList<>();
     private final String[] comboBoxCat = {"Category", "Object", "Switch"};
     private final UpdateController updCon;
@@ -178,7 +177,6 @@ public class GUI<E> implements CategoryListener {
     private JSplitPane tempSplit;
     private boolean initSplit = true;
     private String catOfObjToBeEdited;
-    private FlexiblePane flexPane;
     private UpperNodeCanvas unc;
     private JPanel contentPane;
     private String holonEleNamesDisplayed = "None ";
@@ -210,14 +208,13 @@ public class GUI<E> implements CategoryListener {
     private String saveBeforeNew = "Do you want to save your current data?";
     private String eraseCategory = "Do you really want to delete the Category ";
     private String selectObjBeforeErase = "Please select a Category or an Object in order to delete something.";
-    private Component horizontalStrut = Box.createHorizontalStrut(20);
 
     /**
      * Create the application.
      *
      * @param control the Controller
      */
-    public GUI(Control control) {
+    GUI(Control control) {
         this.controller = control;
         this.model = control.getModel();
         statSplitPane = new StatisticPanel(controller);
@@ -237,32 +234,32 @@ public class GUI<E> implements CategoryListener {
         updCon = new UpdateController(model, controller);
     }
 
-    /**
-     * Adds a Popup.
-     *
-     * @param component Component
-     * @param popup     PopupMenu
-     */
-    private static void addPopup(Component component, final JPopupMenu popup) {
-        component.addMouseListener(new MouseAdapter() {
-            public void mousePressed(MouseEvent e) {
-                if (e.isPopupTrigger()) {
-                    showMenu(e);
-                }
-            }
-
-            public void mouseReleased(MouseEvent e) {
-                if (e.isPopupTrigger()) {
-                    showMenu(e);
-                }
-            }
-
-            private void showMenu(MouseEvent e) {
-                popup.show(e.getComponent(), e.getX(), e.getY());
-            }
-
-        });
-    }
+//    /**
+//     * Adds a Popup.
+//     *
+//     * @param component Component
+//     * @param popup     PopupMenu
+//     */
+//    private static void addPopup(Component component, final JPopupMenu popup) {
+//        component.addMouseListener(new MouseAdapter() {
+//            public void mousePressed(MouseEvent e) {
+//                if (e.isPopupTrigger()) {
+//                    showMenu(e);
+//                }
+//            }
+//
+//            public void mouseReleased(MouseEvent e) {
+//                if (e.isPopupTrigger()) {
+//                    showMenu(e);
+//                }
+//            }
+//
+//            private void showMenu(MouseEvent e) {
+//                popup.show(e.getComponent(), e.getX(), e.getY());
+//            }
+//
+//        });
+//    }
 
     /**
      * Initialize the contents of the frame.
@@ -379,9 +376,18 @@ public class GUI<E> implements CategoryListener {
                 JScrollPane scrollPane = getScrollPaneFromTabbedPane();
                 Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
 
+                // check whether a producer was deleted (this triggers a complete re-evaluation of the net)
+                boolean wasProducerDeleted = false;
+
                 if (canvasOrUpperNodeCanvas instanceof UpperNodeCanvas) {
                     UpperNodeCanvas uNC = (UpperNodeCanvas) canvasOrUpperNodeCanvas;
                     for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
+
+                        if (cps instanceof HolonObject
+                                && ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
+                            wasProducerDeleted = true;
+                        }
+
                         controller.removeTrackingObj(cps);
                         if (uNC.upperNode.getNodes().contains(cps)) {
                             controller.delObjUpperNode(cps, uNC.upperNode);
@@ -398,6 +404,12 @@ public class GUI<E> implements CategoryListener {
                     boolean save = false;
                     for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
                         AbstractCpsObject cps = model.getSelectedCpsObjects().get(j);
+
+                        if (cps instanceof HolonObject
+                                && ((HolonObject) cps).getState() == HolonObject.PRODUCER) {
+                            wasProducerDeleted = true;
+                        }
+
                         controller.removeTrackingObj(cps);
                         if (j < model.getSelectedCpsObjects().size() - 1)
                             save = true;
@@ -409,6 +421,13 @@ public class GUI<E> implements CategoryListener {
                     }
                     canvas.repaint();
                 }
+
+                // recalculate net if a producer was deleted
+                if (wasProducerDeleted) {
+                    controller.resetSimulation();
+                    controller.calculateStateForCurrentTimeStep();
+                }
+
                 model.getSelectedCpsObjects().clear();
                 hideScrollGraph();
             }
@@ -596,7 +615,6 @@ public class GUI<E> implements CategoryListener {
                 }
                 controller.resetCategorys();
             } catch (Exception e2) {
-                // TODO: handle exception
             }
 
             tree.repaint();
@@ -605,6 +623,11 @@ public class GUI<E> implements CategoryListener {
         consoleLogCheckBox.setSelected(true);
         consoleLogCheckBox.addActionListener(arg0 -> controller.setShowConsoleLog(consoleLogCheckBox.isSelected()));
 
+        mnNewMenuOptions.add(useFlexibleDevicesCheckBox);
+        useFlexibleDevicesCheckBox.setSelected(true);
+        useFlexibleDevicesCheckBox.addActionListener(
+                actionEvent -> model.setUseFlexibleDevices(useFlexibleDevicesCheckBox.isSelected()));
+
         menuBar.add(mnNewMenuView);
 
         mnNewMenuView.add(mntmCanvasSize);
@@ -798,7 +821,7 @@ public class GUI<E> implements CategoryListener {
 
         toolBarGraph.add(lblSelectedElement);
         toolBarGraph.add(elementGraph);
-        horizontalStrut = Box.createHorizontalStrut(toolBarGraph.getWidth() - resetGraphBtn.getWidth());
+        Component horizontalStrut = Box.createHorizontalStrut(toolBarGraph.getWidth() - resetGraphBtn.getWidth());
 
         toolBarGraph.add(horizontalStrut);
         resetGraphBtn.setHorizontalAlignment(SwingConstants.RIGHT);
@@ -827,11 +850,10 @@ public class GUI<E> implements CategoryListener {
                     HolonElement ele = addElementPopUp.getElement();
                     if (ele != null) {
                         controller.addElementCanvasObject(tempCpsObject.getId(), ele.getEleName(), ele.getAmount(),
-                                ele.getEnergy(), ele.getId());
+                                ele.getEnergyPerElement(), ele.getId());
                     }
-                    updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-                    updCon.refreshTableProperties(model.getPropertyTable());
                     controller.calculateStateForTimeStep(model.getCurIteration());
+                    triggerUpdateController(null);
                     contentPane.updateUI();
                 }
             }
@@ -847,9 +869,8 @@ public class GUI<E> implements CategoryListener {
                     HolonObject obj = (HolonObject) updCon.getActualCps();
                     for (HolonElement e : selectedElements) {
                         controller.deleteElementCanvas(obj.getId(), e.getId());
-                        updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-                        updCon.refreshTableProperties(model.getPropertyTable());
                         controller.calculateStateForTimeStep(model.getCurIteration());
+                        triggerUpdateController(null);
                         contentPane.updateUI();
                         // Names displayed in graph are not updated
                     }
@@ -863,12 +884,11 @@ public class GUI<E> implements CategoryListener {
                         controller.deleteElementCanvas(i, e.getId());
                     }
                 }
-                updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-                updCon.refreshTableProperties(model.getPropertyTable());
+                triggerUpdateController(null);
                 model.getEleToDelete().clear();
                 selectedElements.clear();
             }
-            updCon.refreshTableProperties(model.getPropertyTable());
+            triggerUpdateController(null);
             elementGraph.setText(Languages.getLanguage()[25]);
             holonEleNamesDisplayed = Languages.getLanguage()[25];
         });
@@ -948,7 +968,7 @@ public class GUI<E> implements CategoryListener {
                 int yBMouse = yBTis;
                 int selectedValueY = (int) Math.floor(yMouse / 16);
                 int selectedValueBY = (int) Math.floor(yBMouse / 16);
-                // for multi-selection mode
+                // ------------------ multi-selection mode ------------------
                 if (model.getSelectedCpsObjects().size() > 1) {
                     int selectedValueX = (int) Math.floor(xThis / (model.getTableHolonElement().getWidth() / 8));
                     int selectedValueBX = (int) Math.floor(xBThis / (model.getTableHolonElement().getWidth() / 8));
@@ -967,7 +987,7 @@ public class GUI<E> implements CategoryListener {
                             String newBStuff = model.getMultiTable().getValueAt(selectedValueBY, selectedValueBX)
                                     .toString();
                             Boolean bTemp = Boolean.parseBoolean(newBStuff);
-                            eleBTemp.setActiveFlex(bTemp);
+                            eleBTemp.setFlexible(bTemp);
                         } else {
                             // Update of HolonElement
                             HolonElement eleTemp = updCon.getActualHolonElement(null, yMouse, 0, tables);
@@ -980,12 +1000,12 @@ public class GUI<E> implements CategoryListener {
                             // Energy Update
                             else if (selectedValueX == 3) {
                                 Float ftemp = Float.parseFloat(newStuff);
-                                eleTemp.setEnergy(ftemp);
+                                eleTemp.setEnergyPerElement(ftemp);
                             }
                             // Flexibility
                             else if (selectedValueX == 4) {
                                 Float ftemp = Float.parseFloat(newStuff);
-                                eleTemp.setFlexibility(ftemp);
+                                eleTemp.setFlexibleEnergyAvailable(ftemp);
                             }
                             // Amount of Elements update
                             else if (selectedValueX == 5) {
@@ -994,30 +1014,34 @@ public class GUI<E> implements CategoryListener {
                             }
                         }
                     }
-                } // For single-selection mode
+                } // ------------------ single-selection mode ------------------
                 else if (model.getSelectedCpsObjects().size() == 1) {
                     int selectedValueX = (int) Math.floor(xThis / (model.getTableHolonElement().getWidth() / 7));
                     int selectedValueBX = (int) Math.floor(xBThis / (model.getTableHolonElement().getWidth() / 7));
                     if (updCon.getActualCps() != null && updCon.getActualCps().getClass() == HolonObject.class) {
+                        HolonElement eleTemp;
+
                         // For active column (boolean with a checkbox)
                         if (selectedValueBX == 5) {
-                            HolonElement eleBTemp = updCon
+                            eleTemp = updCon
                                     .getActualHolonElement((HolonObject) updCon.getActualCps(), yBMouse, 0, tables);
                             String newBStuff = model.getSingleTable().getValueAt(selectedValueBY, selectedValueBX)
                                     .toString();
                             Boolean bTemp = Boolean.parseBoolean(newBStuff);
-                            eleBTemp.setActive(bTemp);
+                            eleTemp.setActive(bTemp);
+
                         } // For activeFlex column (boolean with a checkbox)
                         else if (selectedValueBX == 6) {
-                            HolonElement eleBTemp = updCon
+                            eleTemp = updCon
                                     .getActualHolonElement((HolonObject) updCon.getActualCps(), yBMouse, 0, tables);
                             String newBStuff = model.getSingleTable().getValueAt(selectedValueBY, selectedValueBX)
                                     .toString();
                             Boolean bTemp = Boolean.parseBoolean(newBStuff);
-                            eleBTemp.setActiveFlex(bTemp);
+                            eleTemp.setFlexible(bTemp);
+
                         } else {
                             // Update of HolonElement
-                            HolonElement eleTemp = updCon.getActualHolonElement((HolonObject) updCon.getActualCps(),
+                            eleTemp = updCon.getActualHolonElement((HolonObject) updCon.getActualCps(),
                                     yMouse, 0, tables);
                             String newStuff = model.getSingleTable().getValueAt(selectedValueY, selectedValueX)
                                     .toString();
@@ -1027,11 +1051,17 @@ public class GUI<E> implements CategoryListener {
                             } // Energy Update
                             else if (selectedValueX == 2) {
                                 Float ftemp = Float.parseFloat(newStuff);
-                                eleTemp.setEnergy(ftemp);
+                                eleTemp.setEnergyPerElement(ftemp);
                             } // Flexibility
                             else if (selectedValueX == 3) {
                                 Float ftemp = Float.parseFloat(newStuff);
-                                eleTemp.setFlexibility(ftemp);
+                                eleTemp.setFlexibleEnergyAvailable(ftemp);
+
+                                // if this is a flexible device and the flexibly available energy was changed,
+                                // set used energy to 0, so that it can be computed anew
+                                if (eleTemp.isFlexible()) {
+                                    eleTemp.setEnergyPerElement(0);
+                                }
                             }
                             // Amount of Elements update
                             else if (selectedValueX == 4) {
@@ -1039,15 +1069,22 @@ public class GUI<E> implements CategoryListener {
                                 eleTemp.setAmount(iTemp);
                             }
                         }
+
+                        // set all cells anew, if anything was changed
+                        updateElementTableAfterChange(eleTemp, selectedValueBY);
                     }
                 }
-                updCon.refreshTableProperties(model.getPropertyTable());
-                model.getSingleTable().fireTableDataChanged();
                 controller.calculateStateForTimeStep(model.getCurIteration());
+                model.getSingleTable().fireTableDataChanged();
+                triggerUpdateController(null);
                 contentPane.updateUI();
                 unitGraph.repaint();
-            } catch (Exception e) {
 
+                // trigger update of table after UnitGraph was painted
+                SwingUtilities.invokeLater(() -> {
+                    triggerUpdateController(null);
+                });
+            } catch (Exception e) {
             }
         });
         /***********************
@@ -1145,7 +1182,7 @@ public class GUI<E> implements CategoryListener {
                     // Status edition through a check box
                     if (selValueYBool == 3) {
                         Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
-                        model.getSelectedEdge().setState(bbTemp);
+                        model.getSelectedEdge().setWorkingState(bbTemp);
                     }
                 }
                 canvas.repaint();
@@ -1389,7 +1426,7 @@ public class GUI<E> implements CategoryListener {
                             JOptionPane.showMessageDialog(new JFrame(),
                                     Languages.getLanguage()[57] + selectedOption + ".");
                         }
-                        if (selectedNode.getLevel() == 1) {
+                        if (selectedNode != null && selectedNode.getLevel() == 1) {
                             AbstractCpsObject tmp = new HolonObject("");
                             addObjectPopUP = new AddObjectPopUp(false, tmp, null);
                             addObjectPopUP.setVisible(true);
@@ -1403,7 +1440,6 @@ public class GUI<E> implements CategoryListener {
                         break;
                 }
             } catch (Exception e) {
-                // TODO: handle exception
             }
             tree.repaint();
         });
@@ -1459,8 +1495,7 @@ public class GUI<E> implements CategoryListener {
                     unitGraph.fillArrayofBooleans();
                 }
                 // Write new data in the PropertyTable
-                updCon.paintProperties(temp);
-                updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
+                triggerUpdateController(temp);
 
                 // New Tab with NodeOfNode
                 if (doubleClick() && MouseEvent.BUTTON3 != e.getButton() && temp instanceof CpsUpperNode) {
@@ -1524,7 +1559,6 @@ public class GUI<E> implements CategoryListener {
                             JOptionPane.showMessageDialog(new JFrame(), selectObjBeforeErase);
                     }
                 } catch (Exception e2) {
-                    // TODO: handle exception
                 }
 
             } else {
@@ -1562,10 +1596,10 @@ public class GUI<E> implements CategoryListener {
         mntmOpen.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuFileExitActionPerformed(evt);
+                menuFileExitActionPerformed();
             }
 
-            private void menuFileExitActionPerformed(ActionEvent evt) {
+            private void menuFileExitActionPerformed() {
                 JFileChooser fileChooser = new JFileChooser();
                 JFrame test = new JFrame();
                 FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
@@ -1583,7 +1617,6 @@ public class GUI<E> implements CategoryListener {
                             readStatistics(json);
                         }
                     } catch (IOException | ArchiveException e) {
-                        // TODO Auto-generated catch block
                         e.printStackTrace();
                         JLabel message = new JLabel("The savefile is corrupt and cannot be opened.");
                         JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
@@ -1595,10 +1628,10 @@ public class GUI<E> implements CategoryListener {
         mntmSave.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuSaveActionPerformed(evt);
+                menuSaveActionPerformed();
             }
 
-            private void menuSaveActionPerformed(ActionEvent evt) {
+            private void menuSaveActionPerformed() {
                 JFileChooser fileChooser = new JFileChooser();
                 JFrame test = new JFrame();
                 FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
@@ -1627,7 +1660,6 @@ public class GUI<E> implements CategoryListener {
                     try {
                         controller.saveFile(new File(file).getAbsolutePath());
                     } catch (IOException | ArchiveException e) {
-                        // TODO Auto-generated catch block
                         e.printStackTrace();
                     }
                 }
@@ -1663,30 +1695,17 @@ public class GUI<E> implements CategoryListener {
         mntmUndo.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuUndoActionPerformed(evt);
+                menuUndoActionPerformed();
             }
 
-            private void menuUndoActionPerformed(ActionEvent evt) {
+            private void menuUndoActionPerformed() {
                 try {
                     controller.loadAutoSave(controller.getUndoSave());
                     canvas.repaint();
-                    ArrayList<HolonElement> tempList = new ArrayList<>();
-                    for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
-                        if (cps instanceof HolonObject) {
-                            for (HolonElement h : ((HolonObject) cps).getElements()) {
-                                tempList.add(h);
-                                unitGraph.repaintWithNewElement(tempList);
-                                unitGraph.fillArrayofValue();
-                                tempList.remove(0);
-                            }
-                        } else if (cps instanceof HolonSwitch) {
-                            unitGraph.repaintWithNewSwitch((HolonSwitch) cps);
-                            unitGraph.fillArrayofBooleans();
-                        }
-                    }
+
+                    repaintGraphAfterUndoRedo();
                     hideScrollGraph();
                 } catch (IOException e) {
-                    // TODO Auto-generated catch block
                     e.printStackTrace();
                 }
             }
@@ -1695,27 +1714,15 @@ public class GUI<E> implements CategoryListener {
         mntmRedo.addActionListener(new ActionListener() {
             @Override
             public void actionPerformed(ActionEvent evt) {
-                menuRedoActionPerformed(evt);
+                menuRedoActionPerformed();
             }
 
-            private void menuRedoActionPerformed(ActionEvent evt) {
+            private void menuRedoActionPerformed() {
                 try {
                     controller.loadAutoSave(controller.getRedoSave());
                     canvas.repaint();
-                    ArrayList<HolonElement> tempList = new ArrayList<>();
-                    for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
-                        if (cps instanceof HolonObject) {
-                            for (HolonElement h : ((HolonObject) cps).getElements()) {
-                                tempList.add(h);
-                                unitGraph.repaintWithNewElement(tempList);
-                                unitGraph.fillArrayofValue();
-                                tempList.remove(0);
-                            }
-                        } else if (cps instanceof HolonSwitch) {
-                            unitGraph.repaintWithNewSwitch((HolonSwitch) cps);
-                            unitGraph.fillArrayofBooleans();
-                        }
-                    }
+
+                    repaintGraphAfterUndoRedo();
                     hideScrollGraph();
                 } catch (IOException e) {
                     e.printStackTrace();
@@ -1750,7 +1757,7 @@ public class GUI<E> implements CategoryListener {
 //        tabbedPaneInnerSplit.addTab("Main Grid", null);
         tabbedPaneOriginal.addTab("Statistics", statScrollPane);
         tabbedPaneOriginal.addTab("Holon", holonCanvas);
-        flexPane = new FlexiblePane(controller);
+        FlexiblePane flexPane = new FlexiblePane(controller);
         controller.setFlexiblePane(flexPane);
         controller.getModel().getObjectListeners().add(flexPane);
         tabbedPaneOriginal.addTab("Flexibility", flexPane);
@@ -1794,7 +1801,6 @@ public class GUI<E> implements CategoryListener {
         try {
             controller.loadAutoSave(System.getProperty("user.home") + "/.config/HolonGUI/Category/Category.json");
         } catch (IOException e1) {
-            // TODO Auto-generated catch block
         }
 
         String autoPath = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
@@ -1880,7 +1886,6 @@ public class GUI<E> implements CategoryListener {
                                 break;
                         }
                     } catch (Exception e) {
-                        // TODO: handle exception
                     }
 
                 }
@@ -1933,7 +1938,7 @@ public class GUI<E> implements CategoryListener {
      *
      * @return the Frame
      */
-    public JFrame getFrmCyberPhysical() {
+    JFrame getFrmCyberPhysical() {
         return frmCyberPhysical;
     }
 
@@ -2205,9 +2210,9 @@ public class GUI<E> implements CategoryListener {
         return getScrollPaneFromTabbedPane(index);
     }
 
-    private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
-        return getScrollPaneFromTabbedPane(tabbedPane, -1);
-    }
+//    private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
+//        return getScrollPaneFromTabbedPane(tabbedPane, -1);
+//    }
 
     private JScrollPane getScrollPaneFromTabbedPane() {
         return getScrollPaneFromTabbedPane(-1);
@@ -2230,6 +2235,34 @@ public class GUI<E> implements CategoryListener {
         }
     }
 
+    private void repaintGraphAfterUndoRedo() {
+        for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
+            unitGraph.repaintGraph(cps);
+        }
+    }
+
+    /**
+     * if flexibility was turned on, then active needs to be turned off, the energy currently produced/consumed
+     *
+     * @param eleBTemp        element that needs to be updated
+     * @param selectedValueBY the y value in the table
+     */
+    private void updateElementTableAfterChange(HolonElement eleBTemp, int selectedValueBY) {
+        model.getSingleTable().setValueAt(eleBTemp.isFlexible(), selectedValueBY, 6);
+        model.getSingleTable().setValueAt(eleBTemp.isActive(), selectedValueBY, 5);
+        model.getSingleTable().setValueAt(eleBTemp.getAmount(), selectedValueBY, 4);
+        model.getSingleTable().setValueAt(eleBTemp.getFlexibleEnergyAvailablePerElement(), selectedValueBY, 3);
+        model.getSingleTable().setValueAt(eleBTemp.getEnergyPerElement(), selectedValueBY, 2);
+    }
+
+    private void triggerUpdateController(AbstractCpsObject temp) {
+        if (temp != null) {
+            updCon.paintProperties(temp);
+        }
+        updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
+        updCon.refreshTableProperties(model.getPropertyTable());
+    }
+
     /**
      * Custom Mouse adapter makes contentPane gain focus once mouse leaves this component
      * so copy/paste/cut and "select all" works

+ 41 - 81
src/ui/view/HolonCanvas.java

@@ -1,27 +1,5 @@
 package ui.view;
 
-import java.awt.Color;
-import java.awt.Dimension;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
-import java.awt.event.MouseWheelEvent;
-import java.awt.event.MouseWheelListener;
-import java.util.ArrayList;
-
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
-
-import classes.AbstractCpsObject;
 import classes.HolonBody;
 import classes.SubNet;
 import classes.Vector2d;
@@ -29,6 +7,11 @@ import ui.controller.Control;
 import ui.controller.HolonCanvasController;
 import ui.model.Model;
 
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.ArrayList;
+
 public class HolonCanvas extends JPanel implements MouseWheelListener, MouseListener, MouseMotionListener {
 
 	/**
@@ -36,19 +19,12 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 	 */
 	private static final long serialVersionUID = 1L;
 
-	// Rendering
-	private Graphics2D g2;
-
 	// Ball objects
 	private ArrayList<HolonBody> bodies = new ArrayList<>();
 	private int subCount;
 
-	// Frames
-	private int currentFrameRate;
-
 	private long previousTime = System.currentTimeMillis();
 	private long currentTime = previousTime;
-	private long elapsedTime;
 	private long totalElapsedTime = 0;
 	private int frameCount = 0;
 	private Dimension center;
@@ -59,21 +35,19 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 	private Model model;
 	private JComboBox<String> combo = new JComboBox<>();
 	private int comboChoice = 0;
-	private String info;
-	private int bodyNr;
-	private final JLabel lblBodyInfo = new JLabel("Holon Info:");
 	private JCheckBox chckbxSort = new JCheckBox("sort by size");
 	private boolean sizeChange = false;
 	private HolonBody toDrag;
-	
-	public HolonCanvas(Model mod, Control control) {
-		// Wire up Events
+
+    HolonCanvas(Model mod, Control control) {
+        // Wire up Events
 		this.controller = control;
 		this.model = mod;
 		
 		hCController = new HolonCanvasController(mod);
 
-		add(lblBodyInfo);
+        JLabel lblBodyInfo = new JLabel("Holon Info:");
+        add(lblBodyInfo);
 		this.add(combo);
 		subnets = controller.getSimManager().getSubNets();
 		subCount = subnets.size();
@@ -92,23 +66,12 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 		combo.addItem("Nr. of Producers");
 		combo.addItem("Nr. of active Elements");
 
-		combo.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				comboChoice = combo.getSelectedIndex();
-			}
-		});
-		this.addMouseListener(this);
+        combo.addActionListener(e -> comboChoice = combo.getSelectedIndex());
+        this.addMouseListener(this);
 		this.addMouseMotionListener(this);
 
-		chckbxSort.addChangeListener(new ChangeListener() {
-
-			@Override
-			public void stateChanged(ChangeEvent e) {
-				sizeChange = true;
-			}
-		});
-		add(chckbxSort);
+        chckbxSort.addChangeListener(e -> sizeChange = true);
+        add(chckbxSort);
 	}
 
 	// Start Render and Update Threads
@@ -132,12 +95,12 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 		}
 
 		currentTime = System.currentTimeMillis();
-		elapsedTime = (currentTime - previousTime); // elapsed time in seconds
-		totalElapsedTime += elapsedTime;
+        long elapsedTime = (currentTime - previousTime);
+        totalElapsedTime += elapsedTime;
 
 		if (totalElapsedTime > 1000) {
-			currentFrameRate = frameCount;
-			frameCount = 0;
+//			int currentFrameRate = frameCount;
+            frameCount = 0;
 			totalElapsedTime = 0;
 		}
 
@@ -160,21 +123,22 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 		previousTime = currentTime;
 		frameCount++;
 		repaint();
-	}	
+	}
 
-	public void render(Graphics g) {
-		this.g2 = (Graphics2D) g;
-		this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+    private void render(Graphics g) {
+        Graphics2D g2 = (Graphics2D) g;
+        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
 
 		// Render Background
-		this.g2.setColor(Color.WHITE);
-		this.g2.fillRect(0, 0, getWidth(), getHeight());
+        g2.setColor(Color.WHITE);
+        g2.fillRect(0, 0, getWidth(), getHeight());
 
 		bodies = hCController.getBodies();
 		// Render Objects
 		for (int i = 0; i < subCount; i++) {
-			bodyNr = bodies.get(i).getId();
-			switch (comboChoice) {
+            int bodyNr = bodies.get(i).getId();
+            String info;
+            switch (comboChoice) {
 			case 0:
 				info = "" + bodyNr;
 				break;
@@ -188,34 +152,34 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 				info = "" + subnets.get(bodyNr).getSwitches().size();
 				break;
 			case 4:
-				info = "" + hCController.getTotalProduction(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalProduction(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 5:
-				info = "" + hCController.getTotalConsumption(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalConsumption(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 6:
-				info = "" + hCController.getTotalElements(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalElements(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 7:
-				info = "" + hCController.getTotalProducers(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getTotalProducers(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			case 8:
-				info = "" + hCController.getActiveElements(new ArrayList<AbstractCpsObject>(subnets.get(bodyNr).getObjects()));
-				break;
+                info = "" + hCController.getActiveElements(new ArrayList<>(subnets.get(bodyNr).getObjects()));
+                break;
 			default:
 				info = "" + bodyNr;
 				break;
 			}
 			bodies.get(i).setRadius((subnets.get(bodies.get(i).getId()).getObjects().size() * 5 + 10)
 					* controller.getHolonBodyScale() / 100);
-			bodies.get(i).draw(this.g2, info);
-		}
+            bodies.get(i).draw(g2, info);
+        }
 	}
 
 	
 	// calc the center of the canvas
-	public void calcCenter() {
-		center = this.getSize();
+    private void calcCenter() {
+        center = this.getSize();
 		center.height /= 2;
 		center.width /= 2;
 	}
@@ -227,19 +191,16 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 
 	@Override
 	public void mouseClicked(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseEntered(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseExited(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
@@ -279,6 +240,5 @@ public class HolonCanvas extends JPanel implements MouseWheelListener, MouseList
 
 	@Override
 	public void mouseMoved(MouseEvent e) {
-		// TODO Auto-generated method stub
 	}
 }

+ 15 - 20
src/ui/view/Main.java

@@ -1,11 +1,10 @@
 package ui.view;
 
-import java.awt.EventQueue;
-import javax.swing.UIManager;
-import javax.swing.UnsupportedLookAndFeelException;
+import ui.controller.Control;
+import ui.model.Model;
 
-import ui.controller.*;
-import ui.model.*;
+import javax.swing.*;
+import java.awt.*;
 
 /**
  * The main Class in this Program. The GUI is created in this Class.
@@ -28,7 +27,6 @@ public class Main {
 			try {
 			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
 			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 			}
 		else
@@ -36,24 +34,21 @@ public class Main {
 				UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
 			} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
 					| UnsupportedLookAndFeelException e) {
-				// TODO Auto-generated catch block
 				e.printStackTrace();
 			}
 
-		EventQueue.invokeLater(new Runnable() {
-			public void run() {
-				try {
-					Model model = new Model();
-					Control control = new Control(model);
-					GUI view = new GUI(control);
+        EventQueue.invokeLater(() -> {
+            try {
+                Model model = new Model();
+                Control control = new Control(model);
+                GUI view = new GUI(control);
 
-					view.getFrmCyberPhysical().setVisible(true);
+                view.getFrmCyberPhysical().setVisible(true);
 
-				} catch (Exception e) {
-					e.printStackTrace();
-				}
-			}
-		});
-	}
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        });
+    }
 
 }

+ 89 - 365
src/ui/view/MyCanvas.java

@@ -9,71 +9,22 @@ import ui.model.Model;
 import javax.swing.*;
 import java.awt.*;
 import java.awt.datatransfer.UnsupportedFlavorException;
-import java.awt.event.*;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
 import java.awt.geom.Line2D;
-import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Timer;
-import java.util.TimerTask;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
  *
  * @author Gruppe14
  */
-public class MyCanvas extends JPanel implements MouseListener, MouseMotionListener {
+public class MyCanvas extends AbstractCanvas implements MouseListener, MouseMotionListener {
 
     private static final long serialVersionUID = 1L;
-    public final JMenuItem itemPaste = new JMenuItem(Languages.getLanguage()[97]);
-    // edge Object Start Point
-    private final Model model;
-    private final Control controller;
-    private final float scalediv20;
-    private final UpdateController updCon;
-    private final boolean[] showedInformation = new boolean[5];
-    // PopUpMenu
-    private final JPopupMenu popmenu = new JPopupMenu();
-    private final JMenuItem itemDelete = new JMenuItem(Languages.getLanguage()[98]);
-    private final JMenuItem itemCut = new JMenuItem(Languages.getLanguage()[95]);
-    private final JMenuItem itemCopy = new JMenuItem(Languages.getLanguage()[96]);
-    private final JMenuItem itemGroup = new JMenuItem(Languages.getLanguage()[99]);
-    private final JMenuItem itemUngroup = new JMenuItem(Languages.getLanguage()[100]);
-    private final JMenuItem itemTrack = new JMenuItem(Languages.getLanguage()[101]);
-    private final JMenuItem itemUntrack = new JMenuItem(Languages.getLanguage()[102]);
-    private final Position toolTipPos = new Position(); // Tooltip Position
-    private final int ANIMTIME = 500; // animation Time
-    private final int animFPS = 60;
-    private final int animDelay = 1000 / animFPS; // animation Delay
-    public AbstractCpsObject tempCps = null;
-    ArrayList<HolonElement> dataSelected = new ArrayList<>();
-    ArrayList<AbstractCpsObject> tempSelected = new ArrayList<>();
-    private Image img = null; // Contains the image to draw on MyCanvas
-    private int x = 0;
-    private int y = 0;
-    private Graphics2D g2; // For Painting
-    private int cx, cy;
-    private int sx, sy; // Mark Coords
-    private Position unPos;
-    private ArrayList<Position> savePos;
-    private boolean dragging = false; // for dragging
-    private boolean dragged = false; // if an object/objects was/were dragged
-    private boolean drawEdge = false; // for drawing edges
-    private boolean click = false; // for double click
-    private boolean doMark = false; // for double click
-    private CpsEdge edgeHighlight = null;
-    // rightclicked
-    // Tooltip
-    private boolean toolTip; // Tooltip on or off
-    private String toolTipText = "";
-    private Point mousePosition = new Point(); // Mouse Position when
-    // Animation Stuff
-    private javax.swing.Timer animT; // animation Timer
-    private ArrayList<AbstractCpsObject> animCps = null;
-    private int animDuration = ANIMTIME; // animation Duration
-    private int animSteps = animDuration / animDelay; // animation Steps;
-
-    // contains the value of the Capacity for new created Edges
+
 
     /**
      * Constructor.
@@ -137,32 +88,29 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                 savePos.get(i).y = animCps.get(i).getPosition().y;
             }
 
-            animT = new javax.swing.Timer(animDelay, new ActionListener() {
-
-                @Override
-                public void actionPerformed(ActionEvent e) {
-                    if (animDuration - animDelay > 0 && animCps.size() > 1) {
-                        for (AbstractCpsObject animCpObject : animCps) {
-                            double x1 = animCpObject.getPosition().x - unPos.x;
-                            double y1 = animCpObject.getPosition().y - unPos.y;
-                            animCpObject.getPosition().x -= x1 / animSteps;
-                            animCpObject.getPosition().y -= y1 / animSteps;
-                        }
-                        repaint();
-                        animDuration -= animDelay;
-                        animSteps--;
-                    } else {
-                        animDuration = ANIMTIME;
-                        animSteps = animDuration / animDelay;
-                        animT.stop();
-                        for (int i = 0; i < animCps.size(); i++) {
-                            animCps.get(i).getPosition().x = savePos.get(i).x;
-                            animCps.get(i).getPosition().y = savePos.get(i).y;
-                        }
-                        controller.addUpperNode("NodeOfNode", null, animCps);
-                        controller.calculateStateForCurrentTimeStep();
-                        repaint();
+            animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
+                if (animDuration - animDelay > 0 && animCps.size() > 1) {
+                    for (AbstractCpsObject animCpObject : animCps) {
+                        double x1 = animCpObject.getPosition().x - unPos.x;
+                        double y1 = animCpObject.getPosition().y - unPos.y;
+                        animCpObject.getPosition().x -= x1 / animSteps;
+                        animCpObject.getPosition().y -= y1 / animSteps;
+                    }
+                    repaint();
+                    animDuration -= animDelay;
+                    animSteps--;
+                } else {
+                    animDuration = ANIMTIME;
+                    animSteps = animDuration / animDelay;
+                    animT.stop();
+                    for (int i = 0; i < animCps.size(); i++) {
+                        animCps.get(i).getPosition().x = savePos.get(i).x;
+                        animCps.get(i).getPosition().y = savePos.get(i).y;
                     }
+                    controller.addUpperNode("NodeOfNode", null, animCps);
+                    controller.calculateStateForCurrentTimeStep();
+                    triggerUpdateController();
+                    repaint();
                 }
             });
             animT.start();
@@ -195,32 +143,29 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                 cps.setPosition(new Position(x, y));
             }
 
-            animT = new javax.swing.Timer(animDelay, new ActionListener() {
-
-                @Override
-                public void actionPerformed(ActionEvent e) {
-                    if (animDuration - animDelay >= 0) {
-                        for (int i = 0; i < animCps.size(); i++) {
-                            double x1 = animCps.get(i).getPosition().x - savePos.get(i).x;
-                            double y1 = animCps.get(i).getPosition().y - savePos.get(i).y;
-                            animCps.get(i).getPosition().x -= x1 / animSteps;
-                            animCps.get(i).getPosition().y -= y1 / animSteps;
-                        }
-                        repaint();
-                        animDuration -= animDelay;
-                        animSteps--;
-                    } else {
-                        animDuration = ANIMTIME;
-                        animSteps = animDuration / animDelay;
-                        animT.stop();
-                        for (int i = 0; i < animCps.size(); i++) {
-                            animCps.get(i).getPosition().x = savePos.get(i).x;
-                            animCps.get(i).getPosition().y = savePos.get(i).y;
-                        }
-
-                        controller.calculateStateForCurrentTimeStep();
-                        repaint();
+            animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
+                if (animDuration - animDelay >= 0) {
+                    for (int i = 0; i < animCps.size(); i++) {
+                        double x1 = animCps.get(i).getPosition().x - savePos.get(i).x;
+                        double y1 = animCps.get(i).getPosition().y - savePos.get(i).y;
+                        animCps.get(i).getPosition().x -= x1 / animSteps;
+                        animCps.get(i).getPosition().y -= y1 / animSteps;
                     }
+                    repaint();
+                    animDuration -= animDelay;
+                    animSteps--;
+                } else {
+                    animDuration = ANIMTIME;
+                    animSteps = animDuration / animDelay;
+                    animT.stop();
+                    for (int i = 0; i < animCps.size(); i++) {
+                        animCps.get(i).getPosition().x = savePos.get(i).x;
+                        animCps.get(i).getPosition().y = savePos.get(i).y;
+                    }
+
+                    controller.calculateStateForCurrentTimeStep();
+                    triggerUpdateController();
+                    repaint();
                 }
             });
             animT.start();
@@ -305,8 +250,8 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                     }
                     // Look if the uppernode is open in a Tab
                     for (int i = 4; i < tabbedPane.getTabCount(); i++) {
-                        if (tabbedPane.getComponentAt(i) == null) {
-                        } else if (((UpperNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
+                        if (tabbedPane.getComponentAt(i) != null
+                                && ((UpperNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
                                 .getComponent(0)).upperNode.getId() == cps.getId()) {
                             ((ButtonTabComponent) tabbedPane.getTabComponentAt(i)).removeTabs();
                             break;
@@ -350,7 +295,6 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                 unitGraph.update(model.getSelectedCpsObjects());
 
             } catch (JsonParseException | UnsupportedFlavorException | IOException e1) {
-                // TODO Auto-generated catch block
                 JLabel message = new JLabel("The Clipboard information cannot be pastet into Application.");
                 JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
             }
@@ -367,7 +311,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
      * @param g Graphics
      */
     public void paintComponent(Graphics g) {
-        String maxCap;
+        String maxCap = null;
         super.paintComponent(g);
         // Rendering
         g2 = (Graphics2D) g;
@@ -416,43 +360,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
         }
 
         for (CpsEdge con : model.getEdgesOnCanvas()) {
-            if (con.getA().getId() != model.getSelectedObjectID() && con.getB().getId() != model.getSelectedObjectID()
-                    && con != edgeHighlight) {
-                if (con.getConnected() == 0) {
-                    if (con.getState()) {
-                        g2.setColor(Color.GREEN);
-                        if (con.getCapacity() != -1) {
-                            g2.setStroke(new BasicStroke(Math.min(((con.getFlow() / con.getCapacity() * 3) + 1), 4)));
-                        }
-                    } else {
-                        g2.setColor(Color.RED);
-                        g2.setStroke(new BasicStroke(2));
-                    }
-                } else {
-                    g2.setColor(Color.DARK_GRAY);
-                    g2.setStroke(new BasicStroke(2));
-                }
-                g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
-                        con.getB().getPosition().y);
-
-                if (con.getCapacity() == -1) {
-                    maxCap = Character.toString('\u221e');
-                } else if (con.getCapacity() == -2) {
-                    maxCap = "???";
-                } else {
-                    maxCap = String.valueOf(con.getCapacity());
-                }
-                if (showedInformation[0]) {
-                    if (con.getConnected() == 0 || con.getConnected() == 1) {
-                        g2.drawString(con.getFlow() + "/" + maxCap,
-                                (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-                                (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-                    } else {
-                        g2.drawString("not connected", (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-                                (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-                    }
-                }
-            }
+            maxCap = paintEdge(con, maxCap);
         }
 
         // Highlighted Edge
@@ -464,33 +372,8 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                 } else {
                     g2.setStroke(new BasicStroke(2));
                 }
-                if (con.getA().getId() == model.getSelectedObjectID()
-                        || model.getSelectedCpsObjects().contains(con.getA()) || tempSelected.contains(con.getA())
-                        || con.getB().getId() == model.getSelectedObjectID()
-                        || model.getSelectedCpsObjects().contains(con.getB())
-                        || tempSelected.contains(con.getB()) && con != edgeHighlight) {
-                    g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
-                            con.getB().getPosition().y);
-
-                    if (con.getCapacity() == -1) {
-                        maxCap = Character.toString('\u221e');
-                    } else if (con.getCapacity() == -2) {
-                        maxCap = "???";
-                    } else {
-                        maxCap = String.valueOf(con.getCapacity());
-                    }
-                    if (showedInformation[0]) {
-                        if (con.getConnected() == 0 || con.getConnected() == 1) {
-                            g2.drawString(con.getFlow() + "/" + maxCap,
-                                    (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-                                    (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-                        } else {
-                            g2.drawString("not connected",
-                                    (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-                                    (con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-                        }
-                    }
-                }
+
+                maxCap = drawEdgeLine(con, maxCap);
             }
         } else if (edgeHighlight != null) {
             g2.setColor(Color.BLUE);
@@ -503,13 +386,8 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
             g2.drawLine(edgeHighlight.getA().getPosition().x, edgeHighlight.getA().getPosition().y,
                     edgeHighlight.getB().getPosition().x, edgeHighlight.getB().getPosition().y);
 
-            if (edgeHighlight.getCapacity() == -1) {
-                maxCap = Character.toString('\u221e');
-            } else if (edgeHighlight.getCapacity() == -2) {
-                maxCap = "???";
-            } else {
-                maxCap = String.valueOf(edgeHighlight.getCapacity());
-            }
+            maxCap = setCapacityString(edgeHighlight, maxCap);
+
             if (showedInformation[0]) {
                 g2.drawString(edgeHighlight.getFlow() + "/" + maxCap,
                         (edgeHighlight.getA().getPosition().x + edgeHighlight.getB().getPosition().x) / 2,
@@ -529,55 +407,9 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                             (int) (controller.getScale() + ((scalediv20 + 3) * 2)));
                 }
             }
-            // node image
-            if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
-                    || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
-                img = new ImageIcon(this.getClass().getResource("/Images/node_selected.png")).getImage();
-            } else {
-                if (cps instanceof HolonSwitch) {
-                    if (((HolonSwitch) cps).getActiveAt()[model.getCurIteration()]) {
-                        ((HolonSwitch) cps).setAutoState(true);
-                    } else {
-                        ((HolonSwitch) cps).setAutoState(false);
-                    }
-                }
-                // Highlighting
-                if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
-                        || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
-                    g2.setColor(Color.BLUE);
-                    g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20),
-                            (int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20),
-                            (int) (controller.getScale() + (scalediv20 * 2)),
-                            (int) (controller.getScale() + (scalediv20 * 2)));
-                    if (showedInformation[1] && cps instanceof HolonObject) {
-                        g2.setColor(Color.BLACK);
-                        float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
-                        g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - controller.getScaleDiv2(),
-                                cps.getPosition().y - controller.getScaleDiv2() - 10);
-                    }
-                } else if (cps instanceof HolonObject) {
-                    g2.setColor(((HolonObject) cps).getColor());
-
-                    g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20),
-                            (int) (cps.getPosition().y - controller.getScaleDiv2() - scalediv20),
-                            (int) (controller.getScale() + (scalediv20 * 2)),
-                            (int) (controller.getScale() + (scalediv20 * 2)));
-
-                    if (showedInformation[1]) {
-                        g2.setColor(Color.BLACK);
-                        float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
-                        g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - controller.getScaleDiv2(),
-                                cps.getPosition().y - controller.getScaleDiv2() - 10);
-                    }
-                }
-                // draw image
-                File checkPath = new File(cps.getImage());
-                if (checkPath.exists()) {
-                    img = new ImageIcon(cps.getImage()).getImage();
-                } else {
-                    img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage();
-                }
-            }
+
+            setEdgePictureAndHighlighting(cps);
+
             g2.drawImage(img, cps.getPosition().x - controller.getScaleDiv2(),
                     cps.getPosition().y - controller.getScaleDiv2(), controller.getScale(), controller.getScale(),
                     null);
@@ -588,40 +420,10 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
         if (doMark) {
             g2.setColor(Color.BLACK);
             g2.setStroke(new BasicStroke(1));
-            if (sx > x && sy > y) {
-                g2.drawRect(x, y, sx - x, sy - y);
-            } else if (sx < x && sy < y) {
-                g2.drawRect(sx, sy, x - sx, y - sy);
-            } else if (sx >= x) {
-                g2.drawRect(x, sy, sx - x, y - sy);
-            } else if (sy >= y) {
-                g2.drawRect(sx, y, x - sx, sy - y);
-            }
+            drawMarker();
         }
         // Tooltip
-        if (toolTip) {
-            g2.setColor(new Color(255, 225, 150));
-            g2.setStroke(new BasicStroke(1));
-            int textWidth = g.getFontMetrics().stringWidth(toolTipText) + 2; // Text
-            // width
-
-            // fixed x and y Position to the screen
-            int fixXPos = toolTipPos.x - (textWidth >> 1) + model.getScaleDiv2();
-            int fixYPos = toolTipPos.y;
-
-            if (fixXPos < 0) {
-                fixXPos = 0;
-            } else if (fixXPos + textWidth + 1 > this.getWidth()) {
-                fixXPos -= (fixXPos + textWidth + 1) - this.getWidth();
-            }
-            if (fixYPos + 16 > this.getHeight()) {
-                fixYPos -= (fixYPos + 16) - this.getHeight();
-            }
-            g2.fillRect(fixXPos, fixYPos, textWidth, 15);
-            g2.setColor(Color.BLACK);
-            g2.drawRect(fixXPos, fixYPos, textWidth, 15);
-            g2.drawString(toolTipText, fixXPos + 2, fixYPos + 12);
-        }
+        showTooltip(g);
     }
 
     @Override
@@ -632,9 +434,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                     model.getPropertyTable().removeRow(i);
                 }
             }
-            updCon.paintProperties(tempCps);
-            updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-            updCon.refreshTableProperties(model.getPropertyTable());
+            triggerUpdateController();
         }
     }
 
@@ -657,12 +457,9 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
             cy = cps.getPosition().y - controller.getScaleDiv2();
             if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
                 tempCps = cps;
-                if (model.getShowConsoleLog()) {
-                    controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
-                    controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
-                    controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-                    controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
-                }
+
+                setConsoleTextAfterSelect(cps);
+
                 dragging = true;
                 if (e.isControlDown() && tempCps != null) {
                     if (model.getSelectedCpsObjects().contains(tempCps)) {
@@ -720,7 +517,6 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
             try {
                 controller.autoSave();
             } catch (IOException ex) {
-                // TODO Auto-generated catch block
                 ex.printStackTrace();
             }
         }
@@ -733,46 +529,9 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
         dragged = false;
 
         // Rightclick List
-        if (e.getButton() == MouseEvent.BUTTON3) {
-            if (e.getButton() == MouseEvent.BUTTON3 && tempCps != null) {
-                itemDelete.setEnabled(true);
-                itemCut.setEnabled(true);
-                itemCopy.setEnabled(true);
-                if (tempCps != null) {
-                    itemGroup.setEnabled(true);
-                    itemTrack.setEnabled(true);
-                    itemUntrack.setEnabled(true);
-                }
-                if (tempCps instanceof CpsUpperNode)
-                    itemUngroup.setEnabled(true);
-                else
-                    itemUngroup.setEnabled(false);
-                if (model.getSelectedCpsObjects().size() == 0) {
-                    controller.addSelectedObject(tempCps);
-                }
-            } else {
-                itemCut.setEnabled(false);
-                itemCopy.setEnabled(false);
-                itemDelete.setEnabled(false);
-                itemGroup.setEnabled(false);
-                itemUngroup.setEnabled(false);
-                itemTrack.setEnabled(false);
-                itemUntrack.setEnabled(false);
-            }
-            mousePosition = this.getMousePosition();
-            popmenu.show(e.getComponent(), e.getX(), e.getY());
-        }
+        setRightClickMenu(e);
 
-        if (doMark) {
-            doMark = false;
-            for (AbstractCpsObject cps : tempSelected) {
-                if (!model.getSelectedCpsObjects().contains(cps)) {
-                    controller.addSelectedObject(cps);
-                }
-            }
-            controller.getObjectsInDepth();
-            tempSelected.clear();
-        }
+        markObjects();
 
         if (doubleClick() && tempCps != null && tempCps instanceof HolonSwitch && MouseEvent.BUTTON3 != e.getButton()) {
             ((HolonSwitch) tempCps).switchState();
@@ -780,8 +539,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
 
         controller.calculateStateForTimeStep(model.getCurIteration());
 
-        updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-        updCon.refreshTableProperties(model.getPropertyTable());
+        triggerUpdateController();
 
         repaint();
 
@@ -848,7 +606,6 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                 }
                 repaint();
             } catch (Exception eex) {
-
             }
         }
 
@@ -883,17 +640,13 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
         x = e.getX();
         y = e.getY();
 
-        // Everytghing for the tooltip :)
+        // Everything for the tooltip :)
         boolean on = false;
         for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
             cx = cps.getPosition().x - controller.getScaleDiv2();
             cy = cps.getPosition().y - controller.getScaleDiv2();
-            if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
-                on = true;
-                toolTipPos.x = cps.getPosition().x - controller.getScaleDiv2();
-                toolTipPos.y = cps.getPosition().y + controller.getScaleDiv2();
-                toolTipText = cps.getName() + ", " + cps.getId();
-            }
+
+            on = setToolTipInfoAndPosition(on, cps);
         }
         toolTip = on;
         repaint();
@@ -902,17 +655,20 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
     /**
      * Draws or Deletes an Edge.
      */
-    private void drawDeleteEdge() {
+    void drawDeleteEdge() {
         if (getMousePosition() != null) {
             boolean node = true;
             boolean newEdge = true;
             boolean onEdge = true;
             boolean deleteNode = false;
             CpsEdge e = null;
+
             for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
                 cx = cps.getPosition().x - controller.getScaleDiv2();
                 cy = cps.getPosition().y - controller.getScaleDiv2();
-                if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
+                if (x - controller.getScale() <= cx
+                        && y - controller.getScale() <= cy
+                        && x >= cx && y >= cy
                         && cps != tempCps) {
                     node = false;
                     onEdge = false;
@@ -932,8 +688,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
                         if (e.getB().getClass() == CpsNode.class && e.getB().getConnections().isEmpty()) {
                             deleteNode = true;
                         }
-                    }
-                    if (newEdge) {
+                    } else {
                         e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
                         controller.addEdgeOnCanvas(e);
                     }
@@ -1000,24 +755,15 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
     private CpsEdge mousePositionOnEdge(int x, int y) {
         x += controller.getScaleDiv2();
         y += controller.getScaleDiv2();
-        int lx, ly, hx, hy;
         for (CpsEdge p : model.getEdgesOnCanvas()) {
             Line2D l = new Line2D.Float(p.getA().getPosition().x, p.getA().getPosition().y, p.getB().getPosition().x,
                     p.getB().getPosition().y);
-            if (p.getA().getPosition().x > p.getB().getPosition().x) {
-                hx = p.getA().getPosition().x + model.getScaleDiv2() + 7;
-                lx = p.getB().getPosition().x + model.getScaleDiv2() - 7;
-            } else {
-                lx = p.getA().getPosition().x + model.getScaleDiv2() - 7;
-                hx = p.getB().getPosition().x + model.getScaleDiv2() + 7;
-            }
-            if (p.getA().getPosition().y > p.getB().getPosition().y) {
-                hy = p.getA().getPosition().y + model.getScaleDiv2() + 7;
-                ly = p.getB().getPosition().y + model.getScaleDiv2() - 7;
-            } else {
-                ly = p.getA().getPosition().y + model.getScaleDiv2() - 7;
-                hy = p.getB().getPosition().y + model.getScaleDiv2() + 7;
-            }
+
+            int[] positions = determineMousePositionOnEdge(p);
+            int lx = positions[0];
+            int ly = positions[1];
+            int hx = positions[2];
+            int hy = positions[3];
 
             // distance from a point to a line and between both Objects
             if (l.ptLineDistSq(x - model.getScaleDiv2(), y - model.getScaleDiv2()) < 20 && x > lx && x < hx && y > ly
@@ -1028,7 +774,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
         return null;
     }
 
-    public void updateLanguages() {
+    void updateLanguages() {
         itemCut.setText(Languages.getLanguage()[95]);
         itemCopy.setText(Languages.getLanguage()[96]);
         itemPaste.setText(Languages.getLanguage()[97]);
@@ -1039,28 +785,6 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
         itemUntrack.setText(Languages.getLanguage()[102]);
     }
 
-    /**
-     * Checks if a double click was made.
-     *
-     * @return true if doublecklick, false if not
-     */
-    private boolean doubleClick() {
-        if (click) {
-            click = false;
-            return true;
-        } else {
-            click = true;
-            Timer t = new Timer("doubleclickTimer", false);
-            t.schedule(new TimerTask() {
-                @Override
-                public void run() {
-                    click = false;
-                }
-            }, 500);
-        }
-        return false;
-    }
-
     /**
      * Set if Information should be shown.
      *
@@ -1068,7 +792,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
      * @param object     boolean for objects
      * @param nodeOfnode
      */
-    public void setShowedInformation(boolean connection, boolean object, boolean border, boolean nodeOfnode) {
+    void setShowedInformation(boolean connection, boolean object, boolean border, boolean nodeOfnode) {
         showedInformation[0] = connection;
         showedInformation[1] = object;
         showedInformation[3] = border;
@@ -1080,7 +804,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
      *
      * @return Array of boolean [0] = connection, [1] = objects
      */
-    public boolean[] getShowedInformation() {
+    boolean[] getShowedInformation() {
         return showedInformation;
     }
 
@@ -1089,7 +813,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
      *
      * @param bool
      */
-    public void setToolTip(boolean bool) {
+    void setToolTip(boolean bool) {
         this.toolTip = bool;
     }
 
@@ -1099,7 +823,7 @@ public class MyCanvas extends JPanel implements MouseListener, MouseMotionListen
      * @param x
      * @param y
      */
-    public void setXY(int x, int y) {
+    void setXY(int x, int y) {
         this.x = x;
         this.y = y;
     }

+ 104 - 59
src/ui/view/StatisticGraph.java

@@ -17,21 +17,24 @@ public class StatisticGraph extends JPanel {
     private static final long serialVersionUID = 1L;
 
     // Maximum y Value
-    float maximum = 0;
+    private float maximum = 0;
 
     // is the Simulation running?
 //	private boolean isSimRunning;
-    GeneralPath path = new GeneralPath();
+    private GeneralPath path = new GeneralPath();
     // model and controller
     private Model model;
     private Control controller;
     // Graphics2D
     private Graphics2D g2;
+
     // Data
     private ArrayList<TrackedDataSet> dataSets = new ArrayList<>();
 
     private boolean showGrid = true;
 
+    private float DISTANCE_IN_GRAPH = 1.0f;
+
 //	private JTable table = new JTable();
 //	private ArrayList<Line2D> gridLines = new ArrayList<>();
 
@@ -41,7 +44,7 @@ public class StatisticGraph extends JPanel {
      * @param model   the Model
      * @param control the Controller
      */
-    public StatisticGraph(final Model model, Control control) {
+    StatisticGraph(final Model model, Control control) {
         this.controller = control;
         this.model = model;
         this.setBackground(Color.WHITE);
@@ -90,6 +93,7 @@ public class StatisticGraph extends JPanel {
                 case TrackedDataSet.ACTIVATED_ELEMENTS:
                 case TrackedDataSet.TOTAL_PRODUCTION:
                 case TrackedDataSet.TOTAL_CONSUMPTION:
+                case TrackedDataSet.WASTED_ENERGY:
                 case TrackedDataSet.AMOUNT_HOLONS:
                 case TrackedDataSet.GROUP_CONSUMPTION:
                 case TrackedDataSet.GROUP_PRODUCTION:
@@ -147,7 +151,7 @@ public class StatisticGraph extends JPanel {
      * @param d the number to convert
      * @return the converted number
      */
-    public double convertToCanvasY(float d) {
+    private double convertToCanvasY(float d) {
         return Math.abs((this.getHeight() - (d * (this.getHeight() / maximum))));
     }
 
@@ -160,8 +164,8 @@ public class StatisticGraph extends JPanel {
     public float getEnergyAtCurrentTimeStep(HolonObject obj) {
         float temp = 0;
         for (HolonElement e : obj.getElements()) {
-            if (e.getActive()) {
-                temp = temp + e.getEnergyAt()[model.getCurIteration()];
+            if (e.isActive()) {
+                temp = temp + e.getAvailableEnergyPerElementAt()[model.getCurIteration()];
             }
         }
         return temp;
@@ -170,23 +174,23 @@ public class StatisticGraph extends JPanel {
     /**
      * Calculate the Max Value of the Graph
      */
-    public void calcMaximum() {
+    void calcMaximum() {
         maximum = 0;
         for (TrackedDataSet set : dataSets) {
             float val = 0;
             switch (set.getProperty()) {
                 case TrackedDataSet.CONSUMPTION:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getEnergy() < 0) {
-                            val += (h.getEnergy() + h.getFlexibility()) * h.getAmount();
+                        if (h.getEnergyPerElement() < 0) {
+                            val += (h.getEnergyPerElement() + h.getFlexibleEnergyAvailablePerElement()) * h.getAmount();
                         }
                     }
                     val *= -1;
                     break;
                 case TrackedDataSet.PRODUCTION:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getEnergy() > 0) {
-                            val += (h.getEnergy() + h.getFlexibility()) * h.getAmount();
+                        if (h.getEnergyPerElement() > 0) {
+                            val += (h.getEnergyPerElement() + h.getFlexibleEnergyAvailablePerElement()) * h.getAmount();
                         }
                     }
                     break;
@@ -205,6 +209,9 @@ public class StatisticGraph extends JPanel {
                     val = getMaxTotalConsumption(model.getObjectsOnCanvas());
                     val *= -1;
                     break;
+                case TrackedDataSet.WASTED_ENERGY:
+                    val = getMaxWastedEnergy(model.getObjectsOnCanvas());
+                    break;
                 case TrackedDataSet.PERCENT_SUPPLIED:
                 case TrackedDataSet.PERCENT_NOT_SUPPLIED:
                 case TrackedDataSet.PERCENT_PARTIAL_SUPPLIED:
@@ -258,7 +265,7 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.AVG_CONSUMED_ENERGY_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = -getMaxTotalConsumption(new ArrayList<AbstractCpsObject>(sub.getObjects()));
+                        float tempVal = -getMaxTotalConsumption(new ArrayList<>(sub.getObjects()));
                         if (val < tempVal) {
                             val = tempVal;
                         }
@@ -266,7 +273,7 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.AVG_WASTED_ENERGY_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = getMaxTotalProduction(new ArrayList<AbstractCpsObject>(sub.getObjects()));
+                        float tempVal = getMaxTotalProduction(new ArrayList<>(sub.getObjects()));
                         if (val < tempVal) {
                             val = tempVal;
                         }
@@ -290,7 +297,7 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.AVG_PRODUCED_ENERGY_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        float tempVal = getMaxTotalProduction(new ArrayList<AbstractCpsObject>(sub.getObjects()));
+                        float tempVal = getMaxTotalProduction(new ArrayList<>(sub.getObjects()));
                         if (val < tempVal) {
                             val = tempVal;
                         }
@@ -310,22 +317,22 @@ public class StatisticGraph extends JPanel {
     /**
      * Add the Current Values to each set
      */
-    public void addValues() {
+    void addValues() {
         for (TrackedDataSet set : dataSets) {
             float val = 0;
             switch (set.getProperty()) {
                 case TrackedDataSet.CONSUMPTION:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getTotalEnergyAtTimeStep(model.getCurIteration()) < 0 && h.getActive()) {
-                            val += Math.abs(h.getTotalEnergyAtTimeStep(model.getCurIteration()));
+                        if (h.getOverallEnergyAtTimeStep(model.getCurIteration()) < 0 && h.isActive()) {
+                            val += Math.abs(h.getOverallEnergyAtTimeStep(model.getCurIteration()));
                         }
                         set.setValAt(val, model.getCurIteration());
                     }
                     break;
                 case TrackedDataSet.PRODUCTION:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getTotalEnergyAtTimeStep(model.getCurIteration()) > 0 && h.getActive()) {
-                            val += Math.abs(h.getTotalEnergyAtTimeStep(model.getCurIteration()));
+                        if (h.getOverallEnergyAtTimeStep(model.getCurIteration()) > 0 && h.isActive()) {
+                            val += Math.abs(h.getOverallEnergyAtTimeStep(model.getCurIteration()));
                         }
                         set.setValAt(val, model.getCurIteration());
                     }
@@ -333,7 +340,7 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.ACTIVATED_ELEMENTS:
                     for (HolonElement h : ((HolonObject) set.getCpsObject()).getElements()) {
-                        if (h.getActive()) {
+                        if (h.isActive()) {
                             val += h.getAmount();
                         }
                         set.setValAt(val, model.getCurIteration());
@@ -362,6 +369,10 @@ public class StatisticGraph extends JPanel {
                     set.setValAt(-getTotalConsumptionAt(model.getObjectsOnCanvas(), model.getCurIteration()),
                             model.getCurIteration());
                     break;
+                case TrackedDataSet.WASTED_ENERGY:
+                    float wasted = getTotalWastedEnergyAt(model.getObjectsOnCanvas(), model.getCurIteration());
+                    set.setValAt(wasted, model.getCurIteration());
+                    break;
                 case TrackedDataSet.PERCENT_SUPPLIED:
                     set.setValAt(getPercentState(model.getObjectsOnCanvas(), HolonObject.SUPPLIED),
                             model.getCurIteration());
@@ -424,7 +435,7 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.AVG_CONSUMED_ENERGY_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += -getTotalConsumptionAt(new ArrayList<AbstractCpsObject>(sub.getObjects()),
+                        val += -getTotalConsumptionAt(new ArrayList<>(sub.getObjects()),
                                 model.getCurIteration());
                     }
                     val /= controller.getSimManager().getSubNets().size();
@@ -432,9 +443,9 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.AVG_WASTED_ENERGY_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += (getTotalProductionAt(new ArrayList<AbstractCpsObject>(sub.getObjects()),
+                        val += (getTotalProductionAt(new ArrayList<>(sub.getObjects()),
                                 model.getCurIteration())
-                                + getTotalConsumptionAt(new ArrayList<AbstractCpsObject>(sub.getObjects()),
+                                + getTotalConsumptionAt(new ArrayList<>(sub.getObjects()),
                                 model.getCurIteration()));
                     }
                     val /= controller.getSimManager().getSubNets().size();
@@ -476,7 +487,7 @@ public class StatisticGraph extends JPanel {
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
                         for (HolonObject obj : sub.getObjects()) {
                             for (HolonElement ele : obj.getElements()) {
-                                if (ele.getActive()) {
+                                if (ele.isActive()) {
                                     val++;
                                 }
                             }
@@ -489,7 +500,7 @@ public class StatisticGraph extends JPanel {
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
                         for (HolonObject obj : sub.getObjects()) {
                             for (HolonElement ele : obj.getElements()) {
-                                if (!ele.getActive()) {
+                                if (!ele.isActive()) {
                                     val++;
                                 }
                             }
@@ -500,7 +511,7 @@ public class StatisticGraph extends JPanel {
                     break;
                 case TrackedDataSet.AVG_PRODUCED_ENERGY_IN_HOLONS:
                     for (SubNet sub : controller.getSimManager().getSubNets()) {
-                        val += getTotalProductionAt(new ArrayList<AbstractCpsObject>(sub.getObjects()),
+                        val += getTotalProductionAt(new ArrayList<>(sub.getObjects()),
                                 model.getCurIteration());
                     }
                     val /= controller.getSimManager().getSubNets().size();
@@ -515,7 +526,7 @@ public class StatisticGraph extends JPanel {
     /**
      * create Path with floats
      *
-     * @param set
+     * @param set tracked data
      */
     private void createPathFloats(TrackedDataSet set) {
         int range = model.getCurIteration(); //to which iteration
@@ -525,7 +536,7 @@ public class StatisticGraph extends JPanel {
         if (set.getValues()[0] != -1) {
             path.moveTo(0, convertToCanvasY(set.getValues()[0]));
         } else {
-            path.moveTo(1 * this.getWidth() / model.getIterations(), convertToCanvasY(set.getValues()[1]));
+            path.moveTo(DISTANCE_IN_GRAPH * this.getWidth() / model.getIterations(), convertToCanvasY(set.getValues()[1]));
         }
         for (int i = 0; i < range; i++) {
             if (set.getValues()[i + 1] != -1) {
@@ -543,24 +554,24 @@ public class StatisticGraph extends JPanel {
     /**
      * create Path with booleans(0 and 1)
      *
-     * @param set
+     * @param set tracked data
      */
     private void createPathBooleans(TrackedDataSet set) {
         if (set.getValues()[0] != -1) {
-            path.moveTo(0, convertToCanvasY((float) (set.getValues()[0] * (maximum / 3 * 2)) + (maximum / 6)));
+            path.moveTo(0, convertToCanvasY((set.getValues()[0] * (maximum / 3 * 2)) + (maximum / 6)));
         } else {
-            path.moveTo(1 * this.getWidth() / model.getIterations(),
-                    convertToCanvasY((float) (set.getValues()[1] * (maximum / 3 * 2)) + (maximum / 6)));
+            path.moveTo(DISTANCE_IN_GRAPH * this.getWidth() / model.getIterations(),
+                    convertToCanvasY((set.getValues()[1] * (maximum / 3 * 2)) + (maximum / 6)));
         }
         for (int i = 0; i < model.getCurIteration(); i++) {
             controller.addTextToConsole(set.getValues()[i] + "");
             if (set.getValues()[i + 1] != -1) {
                 path.lineTo((i + 1) * this.getWidth() / model.getIterations(),
-                        convertToCanvasY((float) (set.getValues()[i + 1] * (maximum / 3 * 2)) + (maximum / 6)));
+                        convertToCanvasY((set.getValues()[i + 1] * (maximum / 3 * 2)) + (maximum / 6)));
             } else {
                 if (i + 2 < model.getCurIteration()) {
                     path.moveTo((i + 2) * this.getWidth() / model.getIterations(),
-                            convertToCanvasY((float) (set.getValues()[i + 2] * (maximum / 3 * 2)) + (maximum / 6)));
+                            convertToCanvasY((set.getValues()[i + 2] * (maximum / 3 * 2)) + (maximum / 6)));
                 }
             }
         }
@@ -569,13 +580,13 @@ public class StatisticGraph extends JPanel {
     /**
      * create Path for percent values
      *
-     * @param set
+     * @param set tracked data
      */
     private void createPathPercent(TrackedDataSet set) {
         if (set.getValues()[0] != -1) {
             path.moveTo(0, convertToCanvasY(set.getValues()[0] * maximum));
         } else {
-            path.moveTo(1 * this.getWidth() / model.getIterations(), convertToCanvasY(set.getValues()[1] * maximum));
+            path.moveTo(DISTANCE_IN_GRAPH * this.getWidth() / model.getIterations(), convertToCanvasY(set.getValues()[1] * maximum));
         }
         for (int i = 0; i < model.getCurIteration(); i++) {
             if (set.getValues()[i + 1] != -1) {
@@ -593,8 +604,6 @@ public class StatisticGraph extends JPanel {
 
     /**
      * get the max total production of the given Objects
-     *
-     * @param objects List of Objects
      */
     private float getMaxTotalProduction(ArrayList<AbstractCpsObject> objects) {
         float val = 0;
@@ -602,8 +611,8 @@ public class StatisticGraph extends JPanel {
         for (AbstractCpsObject obj : objects) {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergy() > 0) {
-                        val += (ele.getEnergy() + ele.getFlexibility()) * ele.getAmount();
+                    if (ele.getEnergyPerElement() > 0) {
+                        val += (ele.getEnergyPerElement() + ele.getFlexibleEnergyAvailablePerElement()) * ele.getAmount();
                     }
                 }
             } else if (obj instanceof CpsUpperNode) {
@@ -615,8 +624,6 @@ public class StatisticGraph extends JPanel {
 
     /**
      * get the max total consumption of the given Objects
-     *
-     * @param objects List of Objects
      */
     private float getMaxTotalConsumption(ArrayList<AbstractCpsObject> objects) {
         float val = 0;
@@ -624,8 +631,8 @@ public class StatisticGraph extends JPanel {
         for (AbstractCpsObject obj : objects) {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergy() < 0) {
-                        val += (ele.getEnergy() + ele.getFlexibility()) * ele.getAmount();
+                    if (ele.getEnergyPerElement() < 0) {
+                        val += (ele.getEnergyPerElement() + ele.getFlexibleEnergyAvailablePerElement()) * ele.getAmount();
                     }
                 }
             } else if (obj instanceof CpsUpperNode) {
@@ -635,11 +642,30 @@ public class StatisticGraph extends JPanel {
         return val;
     }
 
+
     /**
-     * get the max total production of the given Objects
-     *
-     * @param objects List of Objects
-     * @param tStep
+     * get the max total wasted energy of the given Objects
+     * if it is smaller than 0, return 0
+     */
+    private float getMaxWastedEnergy(ArrayList<AbstractCpsObject> objects) {
+        float val = 0;
+
+        for (AbstractCpsObject obj : objects) {
+            if (obj instanceof HolonObject) {
+                for (HolonElement ele : ((HolonObject) obj).getElements()) {
+                    val += (ele.getEnergyPerElement() + ele.getFlexibleEnergyAvailablePerElement()) * ele.getAmount();
+                }
+            } else if (obj instanceof CpsUpperNode) {
+                val += getMaxWastedEnergy(((CpsUpperNode) obj).getNodes());
+            }
+        }
+
+        return val < 0 ? 0 : val;
+    }
+
+
+    /**
+     * get the max total production of the given objects at the given timestep
      */
     private float getTotalProductionAt(ArrayList<AbstractCpsObject> objects, int tStep) {
         float val = 0;
@@ -647,8 +673,8 @@ public class StatisticGraph extends JPanel {
         for (AbstractCpsObject obj : objects) {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getTotalEnergyAtTimeStep(tStep) > 0 && ele.getActive()) {
-                        val += ele.getTotalEnergyAtTimeStep(tStep);
+                    if (ele.getOverallEnergyAtTimeStep(tStep) > 0 && ele.isActive()) {
+                        val += ele.getOverallEnergyAtTimeStep(tStep);
                     }
                 }
             } else if (obj instanceof CpsUpperNode) {
@@ -659,10 +685,7 @@ public class StatisticGraph extends JPanel {
     }
 
     /**
-     * get the total consumption of the given Objects at the given timestep
-     *
-     * @param objects List of Objects
-     * @param tStep
+     * get the total consumption of the given objects at the given timestep
      */
     private float getTotalConsumptionAt(ArrayList<AbstractCpsObject> objects, int tStep) {
         float val = 0;
@@ -670,8 +693,8 @@ public class StatisticGraph extends JPanel {
         for (AbstractCpsObject obj : objects) {
             if (obj instanceof HolonObject) {
                 for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergyAt()[tStep] < 0 && ele.getActive()) {
-                        val += ele.getTotalEnergyAtTimeStep(tStep);
+                    if (ele.getAvailableEnergyPerElementAt()[tStep] < 0 && ele.isActive()) {
+                        val += ele.getOverallEnergyAtTimeStep(tStep);
                     }
                 }
             } else if (obj instanceof CpsUpperNode) {
@@ -681,6 +704,28 @@ public class StatisticGraph extends JPanel {
         return val;
     }
 
+    /**
+     * get the total wasted energy of the given objects at the given timestep
+     */
+    private float getTotalWastedEnergyAt(ArrayList<AbstractCpsObject> objects, int tStep) {
+        float val = 0;
+
+        for (AbstractCpsObject obj : objects) {
+            if (obj instanceof HolonObject) {
+                for (HolonElement ele : ((HolonObject) obj).getElements()) {
+                    if (ele.isActive()) {
+                        val += ele.getOverallEnergyAtTimeStep(tStep);
+                    }
+                }
+            } else if (obj instanceof CpsUpperNode) {
+                val += getTotalWastedEnergyAt(((CpsUpperNode) obj).getNodes(), tStep);
+            }
+        }
+
+        return val;
+    }
+
+
     /**
      * get the Percentage of how many objects with the given state are in the
      * given List
@@ -706,13 +751,13 @@ public class StatisticGraph extends JPanel {
     /**
      * Reset the Graph. Delete all calculated values.
      */
-    public void resetGraph() {
+    void resetGraph() {
         for (TrackedDataSet s : dataSets) {
             s.resetValues();
         }
     }
 
-    protected void hideGrid() {
+    void hideGrid() {
         Graphics g = this.getGraphics();
         showGrid = false;
         // clear the area
@@ -720,7 +765,7 @@ public class StatisticGraph extends JPanel {
         paintComponent(g);
     }
 
-    protected void showGrid() {
+    void showGrid() {
         Graphics g = this.getGraphics();
         showGrid = true;
         paintComponent(g);

+ 28 - 34
src/ui/view/StatisticGraphPanel.java

@@ -19,26 +19,15 @@ public class StatisticGraphPanel extends JSplitPane {
 
     private static final long serialVersionUID = 1L;
 
-    // Model/Controller
-//    private Model model;
-//    private Control controller;
-    private final JLabel graphNameLabel;
     private final JLabel maximumLabel = new JLabel("0");
     private final JPanel legendPanel = new JPanel();
-    String[] backgroundColors = {"White", "Dark", "Red", "Blue"};
+    private String[] backgroundColors = {"White", "Dark", "Red", "Blue"};
     // Variables
-    String graphName;
+    private String graphName;
     // Components
     private StatisticGraph sGraph;
-    private JPanel topPanel = new JPanel();
-    private JButton closeButton = new JButton("X");
-    private JPanel graphOptionsContainer = new JPanel();
     private JToggleButton toggleGridButton = new JToggleButton("Hide Grid");
-    private JLabel backgroundColorLabel = new JLabel("Background: ");
     private JComboBox backgroundColorSelector = new JComboBox(backgroundColors);
-    private JButton savImgButton = new JButton("Save as Image");
-    private JPanel topContainer = new JPanel();
-    private JPanel buttomContainer = new JPanel();
     private JSplitPane that;
     private Hashtable<String, StatisticGraphPanel> graphHashtable;
 
@@ -48,7 +37,7 @@ public class StatisticGraphPanel extends JSplitPane {
      * @param mod  the Model
      * @param cont the Controller
      */
-    public StatisticGraphPanel(Model mod, Control cont, String name, Hashtable<String, StatisticGraphPanel> gHt) {
+    StatisticGraphPanel(Model mod, Control cont, String name, Hashtable<String, StatisticGraphPanel> gHt) {
         super();
         setDividerSize(0);
         setPreferredSize(new Dimension(600, 300));
@@ -61,7 +50,9 @@ public class StatisticGraphPanel extends JSplitPane {
         this.sGraph = new StatisticGraph(mod, cont);
         this.graphName = name;
         this.graphHashtable = gHt;
+        JPanel topContainer = new JPanel();
         topContainer.setLayout(new BorderLayout(0, 0));
+        JPanel buttomContainer = new JPanel();
         buttomContainer.setPreferredSize(new Dimension(0, 0));
         buttomContainer.setMinimumSize(new Dimension(0, 0));
         buttomContainer.setAlignmentX(Component.LEFT_ALIGNMENT);
@@ -76,7 +67,7 @@ public class StatisticGraphPanel extends JSplitPane {
         sGraph.setMinimumSize(new Dimension(100, 150));
 
         // Graph Name
-        graphNameLabel = new JLabel(graphName);
+        JLabel graphNameLabel = new JLabel(graphName);
         graphNameLabel.setHorizontalTextPosition(JLabel.CENTER);
         // set font bold and font size slightly bigger than the rest
         graphNameLabel.setFont(new Font(graphNameLabel.getFont().getName(), Font.BOLD, 14));
@@ -93,19 +84,24 @@ public class StatisticGraphPanel extends JSplitPane {
         });
 
         // Panel on top (Name and Close Button)
+        JPanel topPanel = new JPanel();
         topPanel.setLayout(new BorderLayout(0, 0));
         JPanel topPanelHelp = new JPanel(new BorderLayout(0, 0));
         topPanelHelp.add(graphNameLabel, BorderLayout.CENTER);
         // graph options
+        JPanel graphOptionsContainer = new JPanel();
         graphOptionsContainer.add(toggleGridButton);
         graphOptionsContainer.add(new JLabel("  "));    // spacer
+        JLabel backgroundColorLabel = new JLabel("Background: ");
         graphOptionsContainer.add(backgroundColorLabel);
         graphOptionsContainer.add(backgroundColorSelector);
         graphOptionsContainer.add(new JLabel("  "));    // spacer
+        JButton savImgButton = new JButton("Save as Image");
         graphOptionsContainer.add(savImgButton);
         topPanelHelp.add(graphOptionsContainer, BorderLayout.EAST);
         //
         topPanel.add(topPanelHelp, BorderLayout.CENTER);
+        JButton closeButton = new JButton("X");
         topPanel.add(closeButton, BorderLayout.EAST);
         savImgButton.addActionListener(actionEvent -> {
             BufferedImage img = new BufferedImage(that.getWidth(), that.getHeight(), BufferedImage.TYPE_INT_RGB);
@@ -117,7 +113,6 @@ public class StatisticGraphPanel extends JSplitPane {
                     ImageIO.write(img, "jpg", new File(file + ".jpg"));
                 }
             } catch (IOException e1) {
-                // TODO Auto-generated catch block
                 e1.printStackTrace();
             }
 
@@ -180,8 +175,6 @@ public class StatisticGraphPanel extends JSplitPane {
 
     /**
      * Adds the Set to the Graph.
-     *
-     * @param set
      */
 
     public void addObject(TrackedDataSet set) {
@@ -197,6 +190,9 @@ public class StatisticGraphPanel extends JSplitPane {
                 property = "consumption";
                 break;
             case TrackedDataSet.PRODUCTION:
+            case TrackedDataSet.WASTED_ENERGY:
+                property = "wasted energy";
+                break;
             case TrackedDataSet.GROUP_PRODUCTION:
                 property = "production";
                 break;
@@ -298,33 +294,31 @@ public class StatisticGraphPanel extends JSplitPane {
 
     /**
      * Set the Maximum Label
-     *
-     * @param max
      */
-    public void setMaximumLabel(double max) {
+    void setMaximumLabel(double max) {
         maximumLabel.setText(Double.toString(max));
     }
 
-    /**
-     * Get the name of the Graph.
-     *
-     * @return the name of the Graph
-     */
-    public String getGraphName() {
-        return this.graphName;
-    }
+//    /**
+//     * Get the name of the Graph.
+//     *
+//     * @return the name of the Graph
+//     */
+//    public String getGraphName() {
+//        return this.graphName;
+//    }
 
     /**
      * Calls the addValue function of the sGraph
      */
-    public void addValues() {
+    void addValues() {
         sGraph.addValues();
     }
 
     /**
      * Calls the calcMaximum function of the sGraph
      */
-    public void calcMaximum() {
+    void calcMaximum() {
         sGraph.calcMaximum();
     }
 
@@ -332,9 +326,9 @@ public class StatisticGraphPanel extends JSplitPane {
         return sGraph;
     }
 
-    public void setStatisticGraph(StatisticGraph sG) {
-        this.sGraph = sG;
-    }
+//    public void setStatisticGraph(StatisticGraph sG) {
+//        this.sGraph = sG;
+//    }
 
     /**
      * Reset the Graph. Delete all calculated values.

+ 37 - 35
src/ui/view/StatisticPanel.java

@@ -19,37 +19,36 @@ import java.util.Hashtable;
 import java.util.Random;
 
 public class StatisticPanel extends JSplitPane implements GraphListener {
-    public static final String MAIN_GRID = "Main Grid";
-    public static final String HOLON = "Holons";
-
-    // Property Strings
-    public static final String TOT_PROD_HOLON = "total production";
-    public static final String TOT_CONS_HOLON = "total consumption";
-    public static final String SUPPLIED_OBJ = "supplied objects' percentage";
-    public static final String NOT_SUPPLIED_OBJ = "not supplied objects' percentage";
-    public static final String PART_SUPPLIED_OBJ = "partially supplied objects' percentage";
-    public static final String NR_HOLONS = "nr. of Holons";
-    public static final String NR_CLOSED_SWITCHES = "nr. of closed switches";
-    public static final String AVG_OBJ_IN_HOLONS = "average amount of objects";
-    public static final String AVG_ELEM_IN_HOLONS = "average amount of elements";
-    public static final String AVG_PRODS_IN_HOLONS = "average amount of producers";
-    public static final String AVG_CONS_ENERGY_IN_HOLONS = "average consumed energy";
-    public static final String AVG_WASTED_ENERGY_HOLONS = "average wasted energy";
-    public static final String NR_BROKEN_EDGES = "nr. of broken eedges";
-    public static final String PROD_CONS_RATIO = "producer/consumer ratio";
-    public static final String AVG_CLOSED_SW_HOLON = "average of closed switches per Holon";
-    public static final String AVG_ACTIVE_ELEMENTS_HOLON = "average of active elements per Holon";
     public static final String AVG_INACTIVE_ELEMENTS_HOLON = "average of inactive elements per Holon";
     public static final String AVG_PRODUCTION_HOLON = "average production per Holon";
-
+    // for tracked objects
     public static final String TOT_PROD_OBJ = "total production";
     public static final String TOT_CONS_OBJ = "total consumption";
     public static final String NR_ACTIVE_ELEMENTS = "active elements";
-
     public static final String SW_ACTIVE = "active";
-
     public static final String TOT_PROD_GRID = "total Grid production";
     public static final String TOT_CONS_GRID = "total Grid consumption";
+    private static final String MAIN_GRID = "Main Grid";
+    private static final String HOLON = "Holons";
+    // Property Strings
+    // for whole grid
+    private static final String TOT_PROD_HOLON = "total production";
+    private static final String TOT_CONS_HOLON = "total consumption";
+    private static final String TOT_WASTED_HOLON = "total wasted energy";
+    private static final String SUPPLIED_OBJ = "supplied objects' percentage";
+    private static final String NOT_SUPPLIED_OBJ = "not supplied objects' percentage";
+    private static final String PART_SUPPLIED_OBJ = "partially supplied objects' percentage";
+    private static final String NR_HOLONS = "nr. of Holons";
+    private static final String NR_CLOSED_SWITCHES = "nr. of closed switches";
+    private static final String AVG_OBJ_IN_HOLONS = "average amount of objects";
+    private static final String AVG_ELEM_IN_HOLONS = "average amount of elements";
+    private static final String AVG_PRODS_IN_HOLONS = "average amount of producers";
+    private static final String AVG_CONS_ENERGY_IN_HOLONS = "average consumed energy";
+    private static final String AVG_WASTED_ENERGY_HOLONS = "average wasted energy";
+    private static final String NR_BROKEN_EDGES = "nr. of broken edges";
+    private static final String PROD_CONS_RATIO = "producer/consumer ratio";
+    private static final String AVG_CLOSED_SW_HOLON = "average of closed switches per Holon";
+    private static final String AVG_ACTIVE_ELEMENTS_HOLON = "average of active elements per Holon";
     private DefaultTreeModel treeModel;
     private DefaultMutableTreeNode objectsNode;
     private DefaultMutableTreeNode mainGrid;
@@ -96,6 +95,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         holonHashtable = new Hashtable<>();
         holonHashtable.put(TOT_PROD_HOLON, new PropertyDataSet("", defaultGraphColor));
         holonHashtable.put(TOT_CONS_HOLON, new PropertyDataSet("", defaultGraphColor));
+        holonHashtable.put(TOT_WASTED_HOLON, new PropertyDataSet("", defaultGraphColor));
         holonHashtable.put(SUPPLIED_OBJ, new PropertyDataSet("", defaultGraphColor));
         holonHashtable.put(NOT_SUPPLIED_OBJ, new PropertyDataSet("", defaultGraphColor));
         holonHashtable.put(PART_SUPPLIED_OBJ, new PropertyDataSet("", defaultGraphColor));
@@ -118,6 +118,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         propValTable = new Hashtable<>();
         propValTable.put(TOT_PROD_OBJ, TrackedDataSet.PRODUCTION);
         propValTable.put(TOT_CONS_OBJ, TrackedDataSet.CONSUMPTION);
+        propValTable.put(TOT_WASTED_HOLON, TrackedDataSet.WASTED_ENERGY);
         propValTable.put(NR_ACTIVE_ELEMENTS, TrackedDataSet.ACTIVATED_ELEMENTS);
         propValTable.put(SW_ACTIVE, TrackedDataSet.ON_OFF);
         propValTable.put(TOT_PROD_HOLON, TrackedDataSet.TOTAL_PRODUCTION);
@@ -171,6 +172,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         mainGrid = new DefaultMutableTreeNode(MAIN_GRID);
         mainGrid.add(new DefaultMutableTreeNode(TOT_PROD_HOLON));
         mainGrid.add(new DefaultMutableTreeNode(TOT_CONS_HOLON));
+        mainGrid.add(new DefaultMutableTreeNode(TOT_WASTED_HOLON));
         mainGrid.add(new DefaultMutableTreeNode(SUPPLIED_OBJ));
         mainGrid.add(new DefaultMutableTreeNode(NOT_SUPPLIED_OBJ));
         mainGrid.add(new DefaultMutableTreeNode(PART_SUPPLIED_OBJ));
@@ -540,12 +542,12 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         btnAdd.addActionListener(actionEvent -> {
             DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) objectTree
                     .getLastSelectedPathComponent();
-            if (selectedNode == null) {
-                return;
-            } else {
-                if (selectedNode.getLevel() == 3 || (selectedNode.getLevel() == 2 &&
-                        (selectedNode.getParent().toString().equals(HOLON) || selectedNode.getParent().toString().equals(MAIN_GRID)))) {
-                    StatisticGraphPanel tmp = null;
+            if (selectedNode != null) {
+                int nodeLevel = selectedNode.getLevel();
+                String parentString = selectedNode.getParent().toString();
+                if (nodeLevel == 3 ||
+                        (nodeLevel == 2 && (parentString.equals(HOLON) || parentString.equals(MAIN_GRID)))) {
+                    StatisticGraphPanel tmp;
                     if (graphNrTxtField.getText().length() > 0) {
                         if (!graphHashtable.containsKey(graphNrTxtField.getText())
                                 && graphNrTxtField.getText().length() > 0) {
@@ -721,11 +723,11 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
 
     }
 
-    public void colorChanged(Color color) {
+    private void colorChanged(Color color) {
         colorPanel.setBackground(color);
     }
 
-    public void resetFields() {
+    private void resetFields() {
         colorPanel.setBackground(defaultGraphColor);
         redField.setText("");
         greenField.setText("");
@@ -733,7 +735,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         colorComboBox.setSelectedIndex(0);
     }
 
-    public void disableFields() {
+    private void disableFields() {
         redField.setEnabled(false);
         greenField.setEnabled(false);
         blueField.setEnabled(false);
@@ -742,7 +744,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         colorPanel.setBackground(Color.LIGHT_GRAY);
     }
 
-    public void enableFields() {
+    private void enableFields() {
         redField.setEnabled(true);
         greenField.setEnabled(true);
         blueField.setEnabled(true);
@@ -751,7 +753,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         colorPanel.setBackground(defaultGraphColor);
     }
 
-    public void repaintGraphs() {
+    void repaintGraphs() {
         for (StatisticGraphPanel sg : graphHashtable.values()) {
             sg.calcMaximum();
             sg.addValues();
@@ -759,7 +761,7 @@ public class StatisticPanel extends JSplitPane implements GraphListener {
         }
     }
 
-    public JPanel getGraphPanel() {
+    JPanel getGraphPanel() {
         return graphPanel;
     }
 

+ 11 - 22
src/ui/view/StatisticsTab.java

@@ -1,67 +1,56 @@
 package ui.view;
 
-import java.awt.Image;
+import javax.swing.*;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
-import javax.swing.JPanel;
-
-import ui.controller.Control;
-import ui.model.Model;
 
 public class StatisticsTab extends JPanel implements MouseListener, MouseMotionListener {
 
 	private static final long serialVersionUID = 1L;
-	private Image img = null;
-	private int x = 0;
-	private int y = 0;
-	private Model model;
-	private final Control controller;
-
-	public StatisticsTab(Model mod, Control control) {
-		this.model = mod;
-		this.controller = control;
-	}
+//	private Image img = null;
+//	private int x = 0;
+//	private int y = 0;
+//	private Model model;
+//	private final Control controller;
+
+//	public StatisticsTab(Model mod, Control control) {
+//		this.model = mod;
+//		this.controller = control;
+//	}
 
 	@Override
 	public void mouseDragged(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseMoved(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseClicked(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mousePressed(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseReleased(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseEntered(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 
 	@Override
 	public void mouseExited(MouseEvent e) {
-		// TODO Auto-generated method stub
 
 	}
 

+ 21 - 46
src/ui/view/TimePanel.java

@@ -1,31 +1,14 @@
 package ui.view;
 
-import java.awt.BorderLayout;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.Image;
-import java.awt.Point;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.KeyEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import javax.swing.AbstractAction;
-import javax.swing.Box;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JLabel;
-import javax.swing.JPanel;
-import javax.swing.JSlider;
-import javax.swing.KeyStroke;
-import javax.swing.Timer;
+import ui.controller.Control;
+import ui.model.Model;
+
+import javax.swing.*;
 import javax.swing.event.ChangeEvent;
 import javax.swing.event.ChangeListener;
 import javax.swing.plaf.basic.BasicSliderUI;
-
-import ui.controller.Control;
-import ui.model.Model;
+import java.awt.*;
+import java.awt.event.*;
 
 /**
  * This Class represents a Panel where the User can start and stop the
@@ -36,13 +19,18 @@ import ui.model.Model;
  */
 public class TimePanel extends JPanel {
 
-	private Model model;
-	private Control controller;
-	private int dragResetIteration = 0;
-
+	private static final long serialVersionUID = 1L;
+	final JButton playBtn = new JButton();
+	final JButton timeResetBtn = new JButton();
+	final JButton timeForwardBtn = new JButton();
+	;
+	final JButton timeBackwardBtn = new JButton();
+	private final JPanel btnAndSpeedPanel = new JPanel();
+	private final JPanel speedPanel = new JPanel();
+	private final JPanel timeBtnPanel = new JPanel();
 	JSlider timeSlider = new JSlider() {
 		/**
-		 * 
+		 *
 		 */
 		private static final long serialVersionUID = 1L;
 
@@ -70,23 +58,15 @@ public class TimePanel extends JPanel {
 			};
 			addMouseListener(tl);
 		}
-	};;
-
+	};
+	private Model model;
+	private Control controller;
+	private int dragResetIteration = 0;
 	private JLabel simSpeedLabel = new JLabel("Speed:");
 	private JSlider speedSlider = new JSlider();
-
-	private final JPanel btnAndSpeedPanel = new JPanel();
-	private final JPanel speedPanel = new JPanel();
-	private final JPanel timeBtnPanel = new JPanel();
-	final JButton playBtn = new JButton();
-	final JButton timeResetBtn = new JButton();
-	final JButton timeForwardBtn = new JButton();
-	final JButton timeBackwardBtn = new JButton();
 	private Timer timer;
 	private boolean running = false;
 
-	private static final long serialVersionUID = 1L;
-
 	/**
 	 * Constructor.
 	 * 
@@ -127,12 +107,7 @@ public class TimePanel extends JPanel {
 		timeSlider.setToolTipText(Languages.getLanguage()[93]);
 		timeSlider.setMaximum(model.getIterations() - 1);
 		timeSlider.setValue(0);
-		timeSlider.addChangeListener(new ChangeListener() {
-			@Override
-			public void stateChanged(ChangeEvent e) {
-				controller.setCurIteration(timeSlider.getValue());
-			}
-		});
+		timeSlider.addChangeListener(changeEvent -> controller.setCurIteration(timeSlider.getValue()));
 
 		timeSlider.addMouseListener(new MouseAdapter() {
 			@Override

+ 796 - 827
src/ui/view/UnitGraph.java

@@ -1,191 +1,164 @@
 package ui.view;
 
-import java.awt.BasicStroke;
-import java.awt.Color;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
-import java.awt.event.ComponentEvent;
-import java.awt.event.ComponentListener;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
+import classes.*;
+import ui.controller.Control;
+import ui.model.Model;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.*;
 import java.awt.geom.CubicCurve2D;
 import java.awt.geom.GeneralPath;
 import java.awt.geom.Line2D;
 import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.LinkedList;
-import java.awt.Point;
-
-import javax.swing.JPanel;
-
-import classes.AbstractCpsObject;
-import classes.CpsUpperNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import ui.controller.Control;
-import ui.model.Model;
-import classes.HolonSwitch;
-
-import java.awt.Cursor;
 
 /**
  * This Class represents a Graph where the User can model the behavior of
  * elements and switches over time.
- * 
+ *
  * @author Gruppe14
  */
 public class UnitGraph extends JPanel implements MouseListener, MouseMotionListener, ComponentListener {
 
-	private static final long serialVersionUID = 1L;
-	private float maximum = 0;
-
-	// Information shown when a Point is Dragged
-	private String dragInformation = "";
-
-	// Points
-	private Point recSize = new Point(8, 8); // Point Size
-	private Graphics2D g2;
-	private CubicCurve2D c = new CubicCurve2D.Double();
-	private CubicCurve2D cr = new CubicCurve2D.Double();
-	private CubicCurve2D cl = new CubicCurve2D.Double();
-	private LinkedList<Point> pointList;
-	// Scale for the Graph
-	private double scaleX;
-	private double scaleY;
-
-	private float[] arrayOfFloats = null;
-	private boolean[] arrayOfBooleans = null;
-
-	private double width = -1;
-	private double height = -1;
-
-	private boolean isElement = false;
-	private boolean isSwitch = false;
-
-	private ArrayList<HolonElement> tempElements = new ArrayList<>();
-	private Model model;
-	private Control controller;
-	private Line2D.Double line = null;
-	GeneralPath graphCurve = new GeneralPath();
-
-	private boolean pointDrag = false;
-	private boolean init = true;
-	private Point tempP = null;
-	private double x = 0, y = 0;
-	private int x1, x2, y1, y2, ctrlx1, ctrly1, ctrlx2, ctrly2;
-
-	private int border = 4;
-	private int textWidth = 0;
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param model
-	 *            the Model
-	 * @param control
-	 *            the Controller
-	 */
-	public UnitGraph(final Model model, Control control) {
-		setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
-		this.controller = control;
-		this.model = model;
-
-		this.pointList = new LinkedList<>();
-		this.setBackground(Color.WHITE);
-
-		this.addMouseListener(this);
-		this.addMouseMotionListener(this);
-		this.addComponentListener(this);
-	}
-
-	/**
-	 * Paints all Components on the Canvas.
-	 * 
-	 * @param g
-	 *            Graphics
-	 * 
-	 */
-	public void paintComponent(Graphics g) {
-		super.paintComponent(g);
-		g2 = (Graphics2D) g;
-		RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-		g2.setRenderingHints(rh);
-		g2.setStroke(new BasicStroke(0));
-
-		graphCurve.reset();
-
-		border = (int) recSize.getX() >> 1;
-		// Draw the Vertical Lines
-		g2.setColor(Color.BLACK);
-		for (int i = border; i < this.getWidth() - border; i += border * 2) {
-			g2.drawLine(i, border, i, this.getHeight() - border);
-		}
-		g2.drawLine(this.getWidth() - border, border, this.getWidth() - border, this.getHeight() - border);
-
-		for (int i = border; i < this.getHeight() - border; i += border * 2) {
-			g2.drawLine(border, i, this.getWidth() - border, i);
-		}
-		g2.drawLine(border, this.getHeight() - border, this.getWidth() - border, this.getHeight() - border);
-
-		if (isElement) {
-			// array fillen
-			fillArrayofValue();
-
-			if (arrayOfFloats != null) {
-				// Draw the Lines
-				g2.setStroke(new BasicStroke(2));
-				g2.setColor(Color.BLACK);
-				for (int i = 0; i < pointList.size() - 1; i++) {
-					c = buildCurve(pointList.get(i), pointList.get(i + 1));
-					c.setCurve((x1 * scaleX) + border, (y1 * scaleY) + border, (ctrlx1 * scaleX) + border,
-							(ctrly1 * scaleY) + border, (ctrlx2 * scaleX) + border, (ctrly2 * scaleY) + border,
-							(x2 * scaleX) + border, (y2 * scaleY) + border);
-					graphCurve.append(c, true);
-				}
-				g2.draw(graphCurve);
-
-				// Draw the Points
-				g2.setColor(Color.BLUE);
-				for (int i = 0; i < pointList.size() - 0; i++) {
-					g2.fillOval((int) (pointList.get(i).getX() * scaleX - recSize.getX() / 2) + border,
-							(int) (pointList.get(i).getY() * scaleY - recSize.getY() / 2) + border,
-							(int) recSize.getX(), (int) recSize.getY());
-				}
-
-				// Iteration Value
-				textWidth = g.getFontMetrics().stringWidth("" + arrayOfFloats[model.getCurIteration()]) + 2;
-				if (textWidth
-						+ (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1) + 2
-						+ border <= this.getWidth()) {
-					g2.drawString("" + arrayOfFloats[model.getCurIteration()],
-							(model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
-									+ 2 + border,
-							this.getHeight() - 10);
-				} else {
-					g2.drawString("" + arrayOfFloats[model.getCurIteration()],
-							(model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
-									+ border - textWidth,
-							this.getHeight() - 10);
-				}
-
-			}
-			// drag Information
-			if (tempP != null && pointDrag) {
-				dragInformation = "" + convertToValueY(getYValueAt((int) tempP.getX()));
-				textWidth = g.getFontMetrics().stringWidth("" + convertToValueY(getYValueAt((int) tempP.getX()))) + 2;
-				if (textWidth + (tempP.getX() * scaleX) + 10 + border <= this.getWidth()) {
-					g2.drawString(dragInformation, (int) (tempP.getX() * scaleX) + 10 + border,
-							(int) (tempP.getY() * scaleY) + 10);
-				} else {
-					g2.drawString(dragInformation, (int) (tempP.getX() * scaleX) - textWidth,
-							(int) (tempP.getY() * scaleY) + 10);
-				}
-			}
+    private static final long serialVersionUID = 1L;
+    private GeneralPath graphCurve = new GeneralPath();
+    private float maximum = 0;
+    // Information shown when a Point is Dragged
+    private String dragInformation = "";
+    // Points
+    private Point recSize = new Point(8, 8); // Point Size
+    private Graphics2D g2;
+    private CubicCurve2D c = new CubicCurve2D.Double();
+    private CubicCurve2D cr = new CubicCurve2D.Double();
+    private CubicCurve2D cl = new CubicCurve2D.Double();
+    private LinkedList<Point> pointList;
+    // Scale for the Graph
+    private double scaleX;
+    private double scaleY;
+    private float[] arrayOfFloats = null;
+    private boolean[] arrayOfBooleans = null;
+    private double width = -1;
+    private double height = -1;
+    private boolean isElement = false;
+    private boolean isSwitch = false;
+    private ArrayList<HolonElement> tempElements = new ArrayList<>();
+    private Model model;
+    private Control controller;
+    private Line2D.Double line = null;
+    private boolean pointDrag = false;
+    private boolean init = true;
+    private Point tempP = null;
+    private double x = 0, y = 0;
+    private int x1, x2, y1, y2, ctrlx1, ctrly1, ctrlx2, ctrly2;
+
+    private int border = 4;
+    private int textWidth = 0;
+
+    /**
+     * Constructor.
+     *
+     * @param model   the Model
+     * @param control the Controller
+     */
+    public UnitGraph(final Model model, Control control) {
+        setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
+        this.controller = control;
+        this.model = model;
+
+        this.pointList = new LinkedList<>();
+        this.setBackground(Color.WHITE);
+
+        this.addMouseListener(this);
+        this.addMouseMotionListener(this);
+        this.addComponentListener(this);
+    }
+
+    /**
+     * Paints all Components on the Canvas.
+     *
+     * @param g Graphics
+     */
+    public void paintComponent(Graphics g) {
+        super.paintComponent(g);
+        g2 = (Graphics2D) g;
+        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+        g2.setRenderingHints(rh);
+        g2.setStroke(new BasicStroke(0));
+
+        graphCurve.reset();
+
+        border = (int) recSize.getX() >> 1;
+        // Draw the Vertical Lines
+        g2.setColor(Color.BLACK);
+        for (int i = border; i < this.getWidth() - border; i += border * 2) {
+            g2.drawLine(i, border, i, this.getHeight() - border);
+        }
+        g2.drawLine(this.getWidth() - border, border, this.getWidth() - border, this.getHeight() - border);
+
+        for (int i = border; i < this.getHeight() - border; i += border * 2) {
+            g2.drawLine(border, i, this.getWidth() - border, i);
+        }
+        g2.drawLine(border, this.getHeight() - border, this.getWidth() - border, this.getHeight() - border);
+
+        if (isElement) {
+            // fill array with values from the pointList in a HolonElement
+            fillArrayofValue();
+
+            if (arrayOfFloats != null) {
+                // Draw the Lines
+                g2.setStroke(new BasicStroke(2));
+                g2.setColor(Color.BLACK);
+                for (int i = 0; i < pointList.size() - 1; i++) {
+                    c = buildCurve(pointList.get(i), pointList.get(i + 1));
+                    c.setCurve((x1 * scaleX) + border, (y1 * scaleY) + border, (ctrlx1 * scaleX) + border,
+                            (ctrly1 * scaleY) + border, (ctrlx2 * scaleX) + border, (ctrly2 * scaleY) + border,
+                            (x2 * scaleX) + border, (y2 * scaleY) + border);
+                    graphCurve.append(c, true);
+                }
+                g2.draw(graphCurve);
+
+                // Draw the Points
+                g2.setColor(Color.BLUE);
+                for (Point aPointList : pointList) {
+                    g2.fillOval((int) (aPointList.getX() * scaleX - recSize.getX() / 2) + border,
+                            (int) (aPointList.getY() * scaleY - recSize.getY() / 2) + border,
+                            (int) recSize.getX(), (int) recSize.getY());
+                }
+
+                // Iteration Value
+                textWidth = g.getFontMetrics().stringWidth("" + arrayOfFloats[model.getCurIteration()]) + 2;
+                if (textWidth
+                        + (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1) + 2
+                        + border <= this.getWidth()) {
+                    g2.drawString("" + arrayOfFloats[model.getCurIteration()],
+                            (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
+                                    + 2 + border,
+                            this.getHeight() - 10);
+                } else {
+                    g2.drawString("" + arrayOfFloats[model.getCurIteration()],
+                            (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
+                                    + border - textWidth,
+                            this.getHeight() - 10);
+                }
+
+            }
+            // drag Information
+            if (tempP != null && pointDrag) {
+                dragInformation = "" + convertToValueY(getYValueAt((int) tempP.getX()));
+                textWidth = g.getFontMetrics().stringWidth("" + convertToValueY(getYValueAt((int) tempP.getX()))) + 2;
+                if (textWidth + (tempP.getX() * scaleX) + 10 + border <= this.getWidth()) {
+                    g2.drawString(dragInformation, (int) (tempP.getX() * scaleX) + 10 + border,
+                            (int) (tempP.getY() * scaleY) + 10);
+                } else {
+                    g2.drawString(dragInformation, (int) (tempP.getX() * scaleX) - textWidth,
+                            (int) (tempP.getY() * scaleY) + 10);
+                }
+            }
 
 			/*
-			 * // Actual Iteration Point Visualization g2.setColor(Color.RED);
+             * // Actual Iteration Point Visualization g2.setColor(Color.RED);
 			 * if (arrayOfFloats != null) { for (int i = 0; i <
 			 * arrayOfFloats.length; i++) { g2.fillOval((int) (i * width /
 			 * (model.getIterations() - 1) * scaleX - recSize.getX() /
@@ -194,39 +167,39 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 			 * recSize.getY()); } }
 			 */
 
-		} else if (isSwitch) {
-			if (arrayOfBooleans != null) {
-				// array fillen
-				fillArrayofBooleans();
-
-				// Draw the Lines
-				g2.setStroke(new BasicStroke(2));
-				g2.setColor(Color.BLACK);
-				for (int i = 0; i < pointList.size() - 1; i++) {
-					// Left out of bounce
-					if ((i == 1 || i == 2) && pointList.get(i).getX() < 0) {
-						line = new Line2D.Double(border, pointList.get(i).getY() * scaleY, border,
-								pointList.get(i + 1).getY() * scaleY);
-					}
-					// Right out of bounce
-					else if (i == pointList.size() - 4 && pointList.get(pointList.size() - 3).getX() > width) {
-						line = new Line2D.Double(pointList.get(i).getX() * scaleX + border,
-								pointList.get(i).getY() * scaleY, this.getWidth() - border,
-								pointList.get(i + 1).getY() * scaleY);
-					} else if (i == pointList.size() - 3 && pointList.get(pointList.size() - 3).getX() > width) {
-						line = new Line2D.Double(this.getWidth() - border, pointList.get(i).getY() * scaleY,
-								this.getWidth() - border, pointList.get(i + 1).getY() * scaleY);
-					} else if (i == pointList.size() - 2 && pointList.get(pointList.size() - 2).getX() > width) {
-						line = new Line2D.Double(this.getWidth() - border, pointList.get(i).getY() * scaleY,
-								pointList.get(i + 1).getX() * scaleX + border, pointList.get(i + 1).getY() * scaleY);
-					} else {
-						line = new Line2D.Double(pointList.get(i).getX() * scaleX + border,
-								pointList.get(i).getY() * scaleY, pointList.get(i + 1).getX() * scaleX + border,
-								pointList.get(i + 1).getY() * scaleY);
-					}
-					graphCurve.append(line, true);
-				}
-				g2.draw(graphCurve);
+        } else if (isSwitch) {
+            if (arrayOfBooleans != null) {
+                // array fillen
+                fillArrayofBooleans();
+
+                // Draw the Lines
+                g2.setStroke(new BasicStroke(2));
+                g2.setColor(Color.BLACK);
+                for (int i = 0; i < pointList.size() - 1; i++) {
+                    // Left out of bounce
+                    if ((i == 1 || i == 2) && pointList.get(i).getX() < 0) {
+                        line = new Line2D.Double(border, pointList.get(i).getY() * scaleY, border,
+                                pointList.get(i + 1).getY() * scaleY);
+                    }
+                    // Right out of bounce
+                    else if (i == pointList.size() - 4 && pointList.get(pointList.size() - 3).getX() > width) {
+                        line = new Line2D.Double(pointList.get(i).getX() * scaleX + border,
+                                pointList.get(i).getY() * scaleY, this.getWidth() - border,
+                                pointList.get(i + 1).getY() * scaleY);
+                    } else if (i == pointList.size() - 3 && pointList.get(pointList.size() - 3).getX() > width) {
+                        line = new Line2D.Double(this.getWidth() - border, pointList.get(i).getY() * scaleY,
+                                this.getWidth() - border, pointList.get(i + 1).getY() * scaleY);
+                    } else if (i == pointList.size() - 2 && pointList.get(pointList.size() - 2).getX() > width) {
+                        line = new Line2D.Double(this.getWidth() - border, pointList.get(i).getY() * scaleY,
+                                pointList.get(i + 1).getX() * scaleX + border, pointList.get(i + 1).getY() * scaleY);
+                    } else {
+                        line = new Line2D.Double(pointList.get(i).getX() * scaleX + border,
+                                pointList.get(i).getY() * scaleY, pointList.get(i + 1).getX() * scaleX + border,
+                                pointList.get(i + 1).getY() * scaleY);
+                    }
+                    graphCurve.append(line, true);
+                }
+                g2.draw(graphCurve);
 
 				/*
 				 * // Draw the Points g2.setColor(Color.BLUE); for (int i = 0; i
@@ -237,631 +210,627 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
 				 * recSize.getY()); }
 				 */
 
-				// Iteration Value
-				g2.setColor(Color.BLUE);
-				textWidth = g.getFontMetrics().stringWidth("" + arrayOfBooleans[model.getCurIteration()]) + 2;
-				if (textWidth
-						+ (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1) + 2
-						+ border <= this.getWidth()) {
-					g2.drawString("" + arrayOfBooleans[model.getCurIteration()],
-							(model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
-									+ 2 + border,
-							this.getHeight() - 10);
-				} else {
-					g2.drawString("" + arrayOfBooleans[model.getCurIteration()],
-							(model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
-									+ border - textWidth,
-							this.getHeight() - 10);
-				}
-
-			}
-			// When the switch graph is dragged
-			if (tempP != null && pointDrag)
-
-			{
-				try {
-					int i;
-					for (i = 0; (i * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
-							+ border < getMousePosition().getX()); i++) {
-					}
-					dragInformation = "" + i;
-					textWidth = g.getFontMetrics().stringWidth("" + convertToValueY(getYValueAt((int) tempP.getX())))
-							+ 2;
-					if (textWidth + (tempP.getX() * scaleX) + 10 + border <= this.getWidth()) {
-						g2.drawString(dragInformation, (int) (getMousePosition().getX()) + 10 + border,
-								(int) (getMousePosition().getY() * scaleY) + 10);
-					} else {
-						g2.drawString(dragInformation, (int) (getMousePosition().getX()) - textWidth,
-								(int) (getMousePosition().getY() * scaleY) + 10);
-					}
-				} catch (Exception e) {
-				}
-			}
-		}
-
-		// Iteration Line
-		g2.setColor(Color.BLUE);
-		g2.setStroke(new BasicStroke(1));
-		g2.drawLine(border + (model.getCurIteration()) * (this.getWidth() - border * 2) / (model.getIterations() - 1),
-				0, border + (model.getCurIteration()) * (this.getWidth() - border * 2) / (model.getIterations() - 1),
-				this.getHeight());
-
-		// algorithmus
-		controller.calculateStateForTimeStep(model.getCurIteration());
-	}
-
-	@Override
-	public void mouseDragged(MouseEvent e) {
-		if (isElement) {
-			elementDragged(e);
-		} else if (isSwitch) {
-			switchDragged(e);
-		}
-	}
-
-	/**
-	 * When a Point of a Holon Element is dragged.
-	 * 
-	 * @param e
-	 *            MouseEvent
-	 */
-	public void elementDragged(MouseEvent e) {
-		if (pointDrag && tempP != null) {
-			// Out of Bounds verhindern
-			int i = pointList.indexOf(tempP);
-			x = (e.getX() - border) / scaleX;
-			y = (e.getY() - border) / scaleY;
-			// y
-			if (e.getY() <= border) {
-				y = 0;
-			} else if (this.getHeight() - border <= e.getY()) {
-				y = (this.getHeight() - border * 2) / scaleY;
-			}
-			// x
-			if (tempP == pointList.getFirst() || tempP == pointList.getLast() || pointList.get(i + 1).getX() < x + 2
-					|| pointList.get(i - 1).getX() > x - 2 || pointList.getFirst().getX() > x - 2
-					|| pointList.getLast().getX() < x + 2) {
-				x = tempP.getX();
-			}
-			tempP.setLocation(x, y);
-
-			repaint();
-		}
-	}
-
-	/**
-	 * When a Point of a switch is dragged.
-	 * 
-	 * @param e
-	 *            MouseEvent
-	 */
-	public void switchDragged(MouseEvent e) {
-		if (pointDrag && tempP != null && tempP != pointList.getFirst() && tempP != pointList.getLast()) {
-			int i = pointList.indexOf(tempP);
-			x = (e.getX() - border) / scaleX;
-
-			if (pointList.get(i + 1).getY() == tempP.getY()) {
-				// x
-				if (pointList.get(i + 1).getX() <= x + 1 || pointList.get(i - 2).getX() >= x - 1) {
-					x = tempP.getX();
-				}
-				pointList.get(i - 1).setLocation(x, pointList.get(i - 1).getY());
-			} else {
-				// x
-				if (pointList.get(i + 2).getX() <= x + 1 || pointList.get(i - 1).getX() >= x - 1) {
-					x = tempP.getX();
-				}
-				pointList.get(i + 1).setLocation(x, pointList.get(i + 1).getY());
-			}
-			tempP.setLocation(x, tempP.getY());
-			repaint();
-		}
-	}
-
-	@Override
-	public void mouseMoved(MouseEvent e) {
-	}
-
-	@Override
-	public void mouseClicked(MouseEvent e) {
-	}
-
-	@Override
-	public void mouseEntered(MouseEvent e) {
-	}
-
-	@Override
-	public void mouseExited(MouseEvent e) {
-	}
-
-	@Override
-	public void mousePressed(MouseEvent e) {
-		if (isElement) {
-			elementPressed(e);
-		} else if (isSwitch) {
-			switchPressed(e);
-		}
-
-	}
-
-	/**
-	 * When a point of a Holon Element is pressed.
-	 * 
-	 * @param e
-	 *            MouseEvent
-	 */
-	public void elementPressed(MouseEvent e) {
-		boolean added = false;
-		boolean deletePoint = false;
-
-		int x = (int) ((e.getX() - border) / scaleX);
-		double y = (e.getY() - border) / scaleY;
-
-		// Click on Point
-		tempP = null;
-		if (pointList != null) {
-			// look if a point was clicked
-			for (Point p : pointList) {
-				if (x >= p.getX() - recSize.getX() / 2 && y >= p.getY() - recSize.getY() / 2
-						&& x <= p.getX() + recSize.getX() / 2 && y <= p.getY() * scaleY + recSize.getY() / 2) {
-					if (e.getButton() == MouseEvent.BUTTON3) {
-						tempP = p;
-						deletePoint = true;
-					} else {
-						pointDrag = true;
-						tempP = p;
-					}
-				}
-			}
-			// New Point
-			if (!pointDrag && e.getButton() != MouseEvent.BUTTON3 && e.getX() != 0
-					&& e.getX() != this.getWidth() / scaleX) {
-				for (int i = 0; i < pointList.size(); i++) {
-					// When a point already exist on this x position
-					if (x == pointList.get(i).getX() || x == width || x == 0) {
-						break;
-					}
-					if (x < pointList.get(i).getX() && !added) {
-						if (e.getY() <= border) {
-							pointList.add(i, new Point((int) (x), 0));
-						} else {
-							pointList.add(i, new Point((int) (x), (int) y));
-						}
-						added = true;
-						pointDrag = true;
-						tempP = pointList.get(i);
-					}
-				}
-			}
-			// Delete a Point
-			if (deletePoint && tempP.getX() != 0
-					&& (tempP.getX() != this.getWidth() / scaleX || tempP != pointList.getLast())) {
-				pointList.remove(tempP);
-			}
-
-			repaint();
-		}
-	}
-
-	/**
-	 * When a point of a Switch is pressed.
-	 * 
-	 * @param e
-	 *            MouseEvent
-	 */
-	public void switchPressed(MouseEvent e) {
-		boolean added = false;
-		boolean deletePoint = false;
-
-		double x = (e.getX() - border) / scaleX;
-		e.getY();
-
-		// Halbe Iterations Distanz
-		double dist = (width / (model.getIterations() - 1)) / 2;
-
-		// Click on Point
-		tempP = null;
-		if (pointList != null) {
-			for (Point p : pointList) {
-				if (x >= p.getX() - dist * 2 && x <= p.getX() + dist * 2) {
-					if (e.getButton() == MouseEvent.BUTTON3) {
-						tempP = p;
-						deletePoint = true;
-					} else {
-						pointDrag = true;
-						tempP = p;
-					}
-				}
-			}
-			// New Point
-			if (!pointDrag && e.getButton() != MouseEvent.BUTTON3 && x != 0 && x != width) {
-				for (int i = 0; i < pointList.size() && !added; i++) {
-					if (x < pointList.get(i).getX() - dist) {
-						// double p1, p2 um location der points zu bestimmen
-						double p1 = pointList.get(i - 1).getX();
-						double p2 = pointList.get(i).getX();
-						// Punkte hinzufügen, je nachdem ob true oder false
-						if (pointList.get(i - 1).getY() != (int) (height / 6)
-								&& pointList.get(i).getY() != (int) (height / 6)) {
-							pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height - height / 6)));
-							pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height / 6)));
-							pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height / 6)));
-							pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height - height / 6)));
-							added = true;
-						} else if (pointList.get(i - 1).getY() == (int) (height / 6)
-								&& pointList.get(i).getY() == (int) (height / 6)) {
-							pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height / 6)));
-							pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height - height / 6)));
-							pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height - height / 6)));
-							pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height / 6)));
-							added = true;
-						}
-					}
-				}
-			}
-
-			// Delete a Point
-			if (deletePoint && tempP != pointList.getFirst() && tempP != pointList.getLast()) {
-				int i = pointList.indexOf(tempP);
-				// If Right, else if Left
-				if (tempP.getY() == (int) (height / 6) && i < pointList.size() - 1 && i > 0) {
-					pointList.remove(i);
-					pointList.remove(i - 1);
-					pointList.remove(i - 2);
-					pointList.remove(i - 3);
-				} else if (tempP.getY() == (int) (height - height / 6)) {
-					pointList.remove(i + 2);
-					pointList.remove(i + 1);
-					pointList.remove(i);
-					pointList.remove(i - 1);
-				}
-			}
-
-			repaint();
-		}
-	}
-
-	@Override
-	public void mouseReleased(MouseEvent e) {
-		if (pointDrag) {
-			pointDrag = false;
-			tempP = null;
-		}
-		/**
-		 * reset the dragInformation.
-		 */
-		dragInformation = "";
-		repaint();
-	}
-
-	/**
-	 * When the Component is Resized.
-	 * 
-	 * @param e
-	 *            ComponentEvent
-	 */
-	public void componentResized(ComponentEvent e) {
-		// Wenn ein anderes Element genommen wird
-		if (init) {
-			init = false;
-			// for scale on the first initialisation
-			if (width == -1 && height == -1) {
-				width = this.getWidth() - (border * 2);
-				height = this.getHeight() - (border * 2);
-			}
-			// Scale
-			scaleX = (this.getWidth() - (border * 2)) / width;
-			scaleY = (this.getHeight() - (border * 2)) / height;
+                // Iteration Value
+                g2.setColor(Color.BLUE);
+                textWidth = g.getFontMetrics().stringWidth("" + arrayOfBooleans[model.getCurIteration()]) + 2;
+                if (textWidth
+                        + (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1) + 2
+                        + border <= this.getWidth()) {
+                    g2.drawString("" + arrayOfBooleans[model.getCurIteration()],
+                            (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
+                                    + 2 + border,
+                            this.getHeight() - 10);
+                } else {
+                    g2.drawString("" + arrayOfBooleans[model.getCurIteration()],
+                            (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
+                                    + border - textWidth,
+                            this.getHeight() - 10);
+                }
+
+            }
+            // When the switch graph is dragged
+            if (tempP != null && pointDrag)
+
+            {
+                try {
+                    int i;
+                    for (i = 0; (i * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
+                            + border < getMousePosition().getX()); i++) {
+                    }
+                    dragInformation = "" + i;
+                    textWidth = g.getFontMetrics().stringWidth("" + convertToValueY(getYValueAt((int) tempP.getX())))
+                            + 2;
+                    if (textWidth + (tempP.getX() * scaleX) + 10 + border <= this.getWidth()) {
+                        g2.drawString(dragInformation, (int) (getMousePosition().getX()) + 10 + border,
+                                (int) (getMousePosition().getY() * scaleY) + 10);
+                    } else {
+                        g2.drawString(dragInformation, (int) (getMousePosition().getX()) - textWidth,
+                                (int) (getMousePosition().getY() * scaleY) + 10);
+                    }
+                } catch (Exception e) {
+                }
+            }
+        }
+
+        // Iteration Line
+        g2.setColor(Color.BLUE);
+        g2.setStroke(new BasicStroke(1));
+        g2.drawLine(border + (model.getCurIteration()) * (this.getWidth() - border * 2) / (model.getIterations() - 1),
+                0, border + (model.getCurIteration()) * (this.getWidth() - border * 2) / (model.getIterations() - 1),
+                this.getHeight());
+
+        // algorithmus
+        controller.calculateStateForTimeStep(model.getCurIteration());
+    }
+
+    @Override
+    public void mouseDragged(MouseEvent e) {
+        if (isElement) {
+            elementDragged(e);
+        } else if (isSwitch) {
+            switchDragged(e);
+        }
+    }
+
+    /**
+     * When a Point of a Holon Element is dragged.
+     *
+     * @param e MouseEvent
+     */
+    public void elementDragged(MouseEvent e) {
+        if (pointDrag && tempP != null) {
+            // Out of Bounds verhindern
+            int i = pointList.indexOf(tempP);
+            x = (e.getX() - border) / scaleX;
+            y = (e.getY() - border) / scaleY;
+            // y
+            if (e.getY() <= border) {
+                y = 0;
+            } else if (this.getHeight() - border <= e.getY()) {
+                y = (this.getHeight() - border * 2) / scaleY;
+            }
+            // x
+            if (tempP == pointList.getFirst() || tempP == pointList.getLast() || pointList.get(i + 1).getX() < x + 2
+                    || pointList.get(i - 1).getX() > x - 2 || pointList.getFirst().getX() > x - 2
+                    || pointList.getLast().getX() < x + 2) {
+                x = tempP.getX();
+            }
+            tempP.setLocation(x, y);
+
+            repaint();
+        }
+    }
+
+    /**
+     * When a Point of a switch is dragged.
+     *
+     * @param e MouseEvent
+     */
+    public void switchDragged(MouseEvent e) {
+        if (pointDrag && tempP != null && tempP != pointList.getFirst() && tempP != pointList.getLast()) {
+            int i = pointList.indexOf(tempP);
+            x = (e.getX() - border) / scaleX;
+
+            if (pointList.get(i + 1).getY() == tempP.getY()) {
+                // x
+                if (pointList.get(i + 1).getX() <= x + 1 || pointList.get(i - 2).getX() >= x - 1) {
+                    x = tempP.getX();
+                }
+                pointList.get(i - 1).setLocation(x, pointList.get(i - 1).getY());
+            } else {
+                // x
+                if (pointList.get(i + 2).getX() <= x + 1 || pointList.get(i - 1).getX() >= x - 1) {
+                    x = tempP.getX();
+                }
+                pointList.get(i + 1).setLocation(x, pointList.get(i + 1).getY());
+            }
+            tempP.setLocation(x, tempP.getY());
+            repaint();
+        }
+    }
+
+    @Override
+    public void mouseMoved(MouseEvent e) {
+    }
+
+    @Override
+    public void mouseClicked(MouseEvent e) {
+    }
+
+    @Override
+    public void mouseEntered(MouseEvent e) {
+    }
+
+    @Override
+    public void mouseExited(MouseEvent e) {
+    }
+
+    @Override
+    public void mousePressed(MouseEvent e) {
+        if (isElement) {
+            elementPressed(e);
+        } else if (isSwitch) {
+            switchPressed(e);
+        }
+
+    }
+
+    /**
+     * When a point of a Holon Element is pressed.
+     *
+     * @param e MouseEvent
+     */
+    public void elementPressed(MouseEvent e) {
+        boolean added = false;
+        boolean deletePoint = false;
+
+        int x = (int) ((e.getX() - border) / scaleX);
+        double y = (e.getY() - border) / scaleY;
+
+        // Click on Point
+        tempP = null;
+        if (pointList != null) {
+            // look if a point was clicked
+            for (Point p : pointList) {
+                if (x >= p.getX() - recSize.getX() / 2 && y >= p.getY() - recSize.getY() / 2
+                        && x <= p.getX() + recSize.getX() / 2 && y <= p.getY() * scaleY + recSize.getY() / 2) {
+                    if (e.getButton() == MouseEvent.BUTTON3) {
+                        tempP = p;
+                        deletePoint = true;
+                    } else {
+                        pointDrag = true;
+                        tempP = p;
+                    }
+                }
+            }
+            // New Point
+            if (!pointDrag && e.getButton() != MouseEvent.BUTTON3 && e.getX() != 0
+                    && e.getX() != this.getWidth() / scaleX) {
+                for (int i = 0; i < pointList.size(); i++) {
+                    // When a point already exist on this x position
+                    if (x == pointList.get(i).getX() || x == width || x == 0) {
+                        break;
+                    }
+                    if (x < pointList.get(i).getX() && !added) {
+                        if (e.getY() <= border) {
+                            pointList.add(i, new Point((int) (x), 0));
+                        } else {
+                            pointList.add(i, new Point((int) (x), (int) y));
+                        }
+                        added = true;
+                        pointDrag = true;
+                        tempP = pointList.get(i);
+                    }
+                }
+            }
+            // Delete a Point
+            if (deletePoint && tempP.getX() != 0
+                    && (tempP.getX() != this.getWidth() / scaleX || tempP != pointList.getLast())) {
+                pointList.remove(tempP);
+            }
+
+            repaint();
+        }
+    }
+
+    /**
+     * When a point of a Switch is pressed.
+     *
+     * @param e MouseEvent
+     */
+    public void switchPressed(MouseEvent e) {
+        boolean added = false;
+        boolean deletePoint = false;
+
+        double x = (e.getX() - border) / scaleX;
+        e.getY();
+
+        // Halbe Iterations Distanz
+        double dist = (width / (model.getIterations() - 1)) / 2;
+
+        // Click on Point
+        tempP = null;
+        if (pointList != null) {
+            for (Point p : pointList) {
+                if (x >= p.getX() - dist * 2 && x <= p.getX() + dist * 2) {
+                    if (e.getButton() == MouseEvent.BUTTON3) {
+                        tempP = p;
+                        deletePoint = true;
+                    } else {
+                        pointDrag = true;
+                        tempP = p;
+                    }
+                }
+            }
+            // New Point
+            if (!pointDrag && e.getButton() != MouseEvent.BUTTON3 && x != 0 && x != width) {
+                for (int i = 0; i < pointList.size() && !added; i++) {
+                    if (x < pointList.get(i).getX() - dist) {
+                        // double p1, p2 um location der points zu bestimmen
+                        double p1 = pointList.get(i - 1).getX();
+                        double p2 = pointList.get(i).getX();
+                        // Punkte hinzufügen, je nachdem ob true oder false
+                        if (pointList.get(i - 1).getY() != (int) (height / 6)
+                                && pointList.get(i).getY() != (int) (height / 6)) {
+                            pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height - height / 6)));
+                            pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height / 6)));
+                            pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height / 6)));
+                            pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height - height / 6)));
+                            added = true;
+                        } else if (pointList.get(i - 1).getY() == (int) (height / 6)
+                                && pointList.get(i).getY() == (int) (height / 6)) {
+                            pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height / 6)));
+                            pointList.add(i, new Point((int) ((x + p2) / 2 + dist), (int) (height - height / 6)));
+                            pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height - height / 6)));
+                            pointList.add(i, new Point((int) ((x + p1) / 2 - dist), (int) (height / 6)));
+                            added = true;
+                        }
+                    }
+                }
+            }
+
+            // Delete a Point
+            if (deletePoint && tempP != pointList.getFirst() && tempP != pointList.getLast()) {
+                int i = pointList.indexOf(tempP);
+                // If Right, else if Left
+                if (tempP.getY() == (int) (height / 6) && i < pointList.size() - 1 && i > 0) {
+                    pointList.remove(i);
+                    pointList.remove(i - 1);
+                    pointList.remove(i - 2);
+                    pointList.remove(i - 3);
+                } else if (tempP.getY() == (int) (height - height / 6)) {
+                    pointList.remove(i + 2);
+                    pointList.remove(i + 1);
+                    pointList.remove(i);
+                    pointList.remove(i - 1);
+                }
+            }
+
+            repaint();
+        }
+    }
+
+    @Override
+    public void mouseReleased(MouseEvent e) {
+        if (pointDrag) {
+            pointDrag = false;
+            tempP = null;
+        }
+        /**
+         * reset the dragInformation.
+         */
+        dragInformation = "";
+        repaint();
+    }
+
+    /**
+     * When the Component is Resized.
+     *
+     * @param e ComponentEvent
+     */
+    public void componentResized(ComponentEvent e) {
+        // Wenn ein anderes Element genommen wird
+        if (init) {
+            init = false;
+            // for scale on the first initialisation
+            if (width == -1 && height == -1) {
+                width = this.getWidth() - (border * 2);
+                height = this.getHeight() - (border * 2);
+            }
+            // Scale
+            scaleX = (this.getWidth() - (border * 2)) / width;
+            scaleY = (this.getHeight() - (border * 2)) / height;
 
             // set the scroll graph invisible
             this.getParent().getParent().setVisible(false);
-		}
-
-		// Scale
-		scaleX = (this.getWidth() - (border * 2)) / width;
-		scaleY = (this.getHeight() - (border * 2)) / height;
-		repaint();
-	}
-
-	@Override
-	public void componentHidden(ComponentEvent e) {
-	}
-
-	@Override
-	public void componentMoved(ComponentEvent e) {
-
-	}
-
-	@Override
-	public void componentShown(ComponentEvent e) {
-	}
-
-	/**
-	 * Empty the Graph.
-	 */
-	public void empty() {
-		pointList = null;
-		tempElements = null;
-		arrayOfFloats = null;
-		arrayOfBooleans = null;
-		isSwitch = false;
-		isElement = false;
-		repaint();
-	}
-
-	/**
-	 * Resets the Points for the Element.
-	 */
-	public void reset() {
-		pointList.removeAll(pointList);
-		if (isSwitch) {
-			pointList.addFirst(new Point(-border, (int) (height / 6)));
-			pointList.addLast(new Point((int) ((this.getWidth()) / scaleX), (int) (height / 6)));
-		} else {
-			pointList.addFirst(new Point(0, 0));
-			pointList.addLast(new Point((int) ((this.getWidth() - (border * 2)) / scaleX), 0));
-		}
-		repaint();
-	}
-
-	/**
-	 * converts the number to fit the canvas.
-	 * 
-	 * @param d
-	 *            the number to convert
-	 * @return the converted number
-	 */
-	public double convertToCanvasY(float d) {
-		return (height - (d * (height / maximum)));
-	}
-
-	/**
-	 * converts the number to fit the value.
-	 * 
-	 * @param d
-	 *            the number to convert
-	 * @return the converted number
-	 */
-	public float convertToValueY(double d) {
-		return (float) Math.round(((height - (height * (d / height))) / (height / maximum)) * 10) / 10;
-	}
-
-	/**
-	 * Visualize the HolonElement on the Graph.
-	 * 
-	 * @param selectedElement
-	 *            which should be visualized
-	 */
-	public void repaintWithNewElement(ArrayList<HolonElement> selectedElement) {
-		arrayOfFloats = selectedElement.get(selectedElement.size() - 1).getEnergyAt();
-		tempElements = selectedElement;
-		pointList = selectedElement.get(selectedElement.size() - 1).getGraphPoints();
-		isSwitch = false;
-		isElement = true;
-		maximum = selectedElement.get(selectedElement.size() - 1).getEnergy();
-		// First time clicked on the Element
-		if (pointList.isEmpty()) {
-			pointList.addFirst(new Point(0, 0));
-			pointList.addLast(new Point((int) ((this.getWidth() - (border * 2)) / scaleX), 0));
-		}
-		repaint();
-	}
-
-	/**
-	 * Visualize the Switch on the Graph.
-	 * 
-	 * @param s
-	 *            which should be visualized
-	 */
-	public void repaintWithNewSwitch(HolonSwitch s) {
-		arrayOfBooleans = s.getActiveAt();
-		pointList = s.getGraphPoints();
-		isSwitch = true;
-		isElement = false;
-		// First time clicked on the Element
-		if (pointList.isEmpty()) {
-			pointList.addFirst(new Point(-border, (int) (height / 6)));
-			pointList.addLast(new Point((int) ((this.getWidth()) / scaleX), (int) (height / 6)));
-		}
-		repaint();
-	}
-
-	/**
-	 * Build a Curve for the Graph.
-	 * 
-	 * @param p1
-	 *            startpoint
-	 * @param p2
-	 *            endpoint
-	 * 
-	 * @return the CubicCurve2D for the Graph
-	 */
-	public CubicCurve2D buildCurve(Point p1, Point p2) {
-		x1 = (int) p1.getX();
-		y1 = (int) p1.getY();
-		x2 = (int) p2.getX();
-		y2 = (int) p2.getY();
-
-		// calculate the controllpoints
-		ctrlx1 = x1 + (x2 - x1) / 2;
-		ctrlx2 = x2 - (x2 - x1) / 2;
-		if (y1 < y2) {
-			ctrly1 = y1 + (y2 - y1) / 10;
-			ctrly2 = y2 - (y2 - y1) / 10;
-		} else {
-			ctrly1 = y1 - (y1 - y2) / 10;
-			ctrly2 = y2 + (y1 - y2) / 10;
-		}
-
-		// set the curve
-		c.setCurve(x1 * scaleX, y1 * scaleY, ctrlx1 * scaleX, ctrly1 * scaleY, ctrlx2 * scaleX, ctrly2 * scaleY,
-				x2 * scaleX, y2 * scaleY);
-		return c;
-	}
-
-	/**
-	 * Fills the Arrays with booleans.
-	 */
-	public void fillArrayofBooleans() {
-		for (int i = 0; i < arrayOfBooleans.length; i++) {
-			int t = (int) getYValueAt((int) (i * width / (model.getIterations() - 1)));
-			if (t <= height / 2) {
-				arrayOfBooleans[i] = true;
-			} else {
-				arrayOfBooleans[i] = false;
-			}
-
-		}
-	}
-
-	/**
-	 * Fills the Arrays of each HolonElement.
-	 */
-	@SuppressWarnings("unchecked")
-	public void fillArrayofValue() {
-		for (HolonElement he : tempElements) {
-			maximum = he.getEnergy();
-			he.setGraphPoints((LinkedList<Point>) pointList.clone());
-			for (int i = 0; i < arrayOfFloats.length; i++) {
-				he.getEnergyAt()[i] = convertToValueY(getYValueAt2((int) (i * width / (model.getIterations() - 1))));
-			}
-			arrayOfFloats = he.getEnergyAt();
-		}
-	}
-
-	/**
-	 * Get the Y Value at the x Coordination.
-	 * 
-	 * @param xVal
-	 *            the x value for the y value
-	 * @return y, the value at x
-	 */
-	public float getYValueAt(int xVal) {
-		for (int i = 0; i < pointList.size() - 1; i++) {
-			// get the Points
-			if (xVal <= pointList.get(i + 1).getX()) {
-				// Curve erstellen
-				Line2D l1 = new Line2D.Double(pointList.get(i).getX(), pointList.get(i).getY(),
-						pointList.get(i + 1).getX(), pointList.get(i + 1).getY());
-				Line2D l2 = new Line2D.Double(xVal, 0, xVal, height);
-				return getIntersectionPoint(l1, l2);
-			}
-		}
-		return 0;
-	}
-
-	/**
-	 * Get y value at the x Coordination via curves.
-	 * 
-	 * @param xVal
-	 *            the x value for the y value
-	 * @return y value at x
-	 */
-	public float getYValueAt2(int xVal) {
-		for (int i = 0; i < pointList.size() - 1; i++) {
-			// get the Points
-			if (xVal >= pointList.get(i).getX()) {
-				// Curve erstellen
-				c = buildCurve(pointList.get(i), pointList.get(i + 1));
-				c.subdivide(cl, cr);
-				// Teil der Kurve aussuchen
-				if (cl.getX1() <= xVal * scaleX && cl.getX2() > xVal * scaleX) {
-					c = cl;
-					// Kurve Links von "unten"
-					if (pointList.get(i).getY() >= pointList.get(i + 1).getY()) {
-						for (float j = (float) (height - 1); j >= 0; j -= 0.1f) {
-							if (c.contains(xVal * scaleX, j * scaleY)) {
-								return (float) (j);
-							}
-						}
-					} else {// Kurve Links von "oben"
-						for (float j = 0; j < height; j += 0.1f) {
-							if (c.contains(xVal * scaleX, j * scaleY)) {
-								return (float) (j);
-							}
-						}
-					}
-				} else {
-					c = cr;
-					// Kurve Links von "unten"
-					if (pointList.get(i).getY() >= pointList.get(i + 1).getY()) {
-						for (float j = 0; j < height; j += 0.1f) {
-							if (c.contains(xVal * scaleX, j * scaleY)) {
-								return (float) (j);
-							}
-						}
-					} else {// Kurve Links von "oben"
-						for (float j = (float) (height - 1); j >= 0; j -= 0.1f) {
-							if (c.contains(xVal * scaleX, j * scaleY)) {
-								return (float) (j);
-							}
-						}
-					}
-				}
-			}
-		}
-		// else
-		return getYValueAt(xVal);
-	}
-
-	/**
-	 * Get the Intersection Point of 2 Lines.
-	 * 
-	 * @param l1
-	 *            the first Line
-	 * @param l2
-	 *            the second Line
-	 * 
-	 * @return The Intersection Point
-	 */
-	public float getIntersectionPoint(Line2D l1, Line2D l2) {
-		if (!l1.intersectsLine(l2)) {
-			return 0;// null;
-		}
-		double px = l1.getX1(), py = l1.getY1(), rx = l1.getX2() - px, ry = l1.getY2() - py;
-		double qx = l2.getX1(), qy = l2.getY1(), sx = l2.getX2() - qx, sy = l2.getY2() - qy;
-
-		double det = sx * ry - sy * rx;
-		if (det == 0) {
-			return 0;// null;
-		} else {
-			double z = (sx * (qy - py) + sy * (px - qx)) / det;
-			if (z < 0 || z > 1) {
-				return 0;// new Point(0, 0); // intersection at end point!
-			}
-			return (float) (py + z * ry);// new Point((int) (px + z * rx), (int)
-											// (py + z * ry));
-		}
-	} // end intersection line-line
-
-	public void update(ArrayList<AbstractCpsObject> obj) {
-
-		ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
-		ArrayList<HolonElement> list = new ArrayList<>();
-
-		AbstractCpsObject u = null;
-		queue.addAll(obj);
-
-		while (!queue.isEmpty()) {
-			u = queue.pop();
-			if (u instanceof HolonObject) {
-				for (HolonElement ele : ((HolonObject) u).getElements()) {
-					list.add(ele);
-					repaintWithNewElement(list);
-					fillArrayofValue();
-					list.remove(0);
-				}
-			} else if (u instanceof HolonSwitch) {
-				repaintWithNewSwitch((HolonSwitch) u);
-				fillArrayofBooleans();
-			}
-		}
-		empty();
-
-		if (u instanceof CpsUpperNode)
-			for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
-				queue.add(adjacent);
-			}
-
-	}
+        }
+
+        // Scale
+        scaleX = (this.getWidth() - (border * 2)) / width;
+        scaleY = (this.getHeight() - (border * 2)) / height;
+        repaint();
+    }
+
+    @Override
+    public void componentHidden(ComponentEvent e) {
+    }
+
+    @Override
+    public void componentMoved(ComponentEvent e) {
+
+    }
+
+    @Override
+    public void componentShown(ComponentEvent e) {
+    }
+
+    /**
+     * Empty the Graph.
+     */
+    public void empty() {
+        pointList = null;
+        tempElements = null;
+        arrayOfFloats = null;
+        arrayOfBooleans = null;
+        isSwitch = false;
+        isElement = false;
+        repaint();
+    }
+
+    /**
+     * Resets the Points for the Element.
+     */
+    public void reset() {
+        pointList.removeAll(pointList);
+        if (isSwitch) {
+            pointList.addFirst(new Point(-border, (int) (height / 6)));
+            pointList.addLast(new Point((int) ((this.getWidth()) / scaleX), (int) (height / 6)));
+        } else {
+            pointList.addFirst(new Point(0, 0));
+            pointList.addLast(new Point((int) ((this.getWidth() - (border * 2)) / scaleX), 0));
+        }
+        repaint();
+    }
+
+    /**
+     * converts the number to fit the canvas.
+     *
+     * @param d the number to convert
+     * @return the converted number
+     */
+    public double convertToCanvasY(float d) {
+        return (height - (d * (height / maximum)));
+    }
+
+    /**
+     * converts the number to fit the value.
+     *
+     * @param d the number to convert
+     * @return the converted number
+     */
+    public float convertToValueY(double d) {
+        return (float) Math.round(((height - (height * (d / height))) / (height / maximum)) * 10) / 10;
+    }
+
+    /**
+     * Visualize the HolonElement on the Graph.
+     *
+     * @param selectedElement which should be visualized
+     */
+    public void repaintWithNewElement(ArrayList<HolonElement> selectedElement) {
+        arrayOfFloats = selectedElement.get(selectedElement.size() - 1).getAvailableEnergyPerElementAt();
+        tempElements = selectedElement;
+        pointList = selectedElement.get(selectedElement.size() - 1).getGraphPoints();
+        isSwitch = false;
+        isElement = true;
+        maximum = getMaximum(selectedElement.get(selectedElement.size() - 1));
+        // First time clicked on the Element
+        if (pointList.isEmpty()) {
+            pointList.addFirst(new Point(0, 0));
+            pointList.addLast(new Point((int) ((this.getWidth() - (border * 2)) / scaleX), 0));
+        }
+        repaint();
+    }
+
+    /**
+     * Visualize the Switch on the Graph.
+     *
+     * @param s which should be visualized
+     */
+    public void repaintWithNewSwitch(HolonSwitch s) {
+        arrayOfBooleans = s.getActiveAt();
+        pointList = s.getGraphPoints();
+        isSwitch = true;
+        isElement = false;
+        // First time clicked on the Element
+        if (pointList.isEmpty()) {
+            pointList.addFirst(new Point(-border, (int) (height / 6)));
+            pointList.addLast(new Point((int) ((this.getWidth()) / scaleX), (int) (height / 6)));
+        }
+        repaint();
+    }
+
+    /**
+     * Build a Curve for the Graph.
+     *
+     * @param p1 startpoint
+     * @param p2 endpoint
+     * @return the CubicCurve2D for the Graph
+     */
+    public CubicCurve2D buildCurve(Point p1, Point p2) {
+        x1 = (int) p1.getX();
+        y1 = (int) p1.getY();
+        x2 = (int) p2.getX();
+        y2 = (int) p2.getY();
+
+        // calculate the controllpoints
+        ctrlx1 = x1 + (x2 - x1) / 2;
+        ctrlx2 = x2 - (x2 - x1) / 2;
+        if (y1 < y2) {
+            ctrly1 = y1 + (y2 - y1) / 10;
+            ctrly2 = y2 - (y2 - y1) / 10;
+        } else {
+            ctrly1 = y1 - (y1 - y2) / 10;
+            ctrly2 = y2 + (y1 - y2) / 10;
+        }
+
+        // set the curve
+        c.setCurve(x1 * scaleX, y1 * scaleY, ctrlx1 * scaleX, ctrly1 * scaleY, ctrlx2 * scaleX, ctrly2 * scaleY,
+                x2 * scaleX, y2 * scaleY);
+        return c;
+    }
+
+    /**
+     * Fills the Arrays with booleans.
+     */
+    public void fillArrayofBooleans() {
+        for (int i = 0; i < arrayOfBooleans.length; i++) {
+            int t = (int) getYValueAt((int) (i * width / (model.getIterations() - 1)));
+            if (t <= height / 2) {
+                arrayOfBooleans[i] = true;
+            } else {
+                arrayOfBooleans[i] = false;
+            }
+
+        }
+    }
+
+    /**
+     * Fills the Arrays of each HolonElement.
+     */
+    @SuppressWarnings("unchecked")
+    public void fillArrayofValue() {
+        for (HolonElement he : tempElements) {
+            maximum = getMaximum(he);
+            he.setGraphPoints((LinkedList<Point>) pointList.clone());
+            for (int i = 0; i < arrayOfFloats.length; i++) {
+                he.getAvailableEnergyPerElementAt()[i] = convertToValueY(getYValueAt2((int) (i * width / (model.getIterations() - 1))));
+            }
+            arrayOfFloats = he.getAvailableEnergyPerElementAt();
+        }
+    }
+
+    /**
+     * Get the Y Value at the x Coordination.
+     *
+     * @param xVal the x value for the y value
+     * @return y, the value at x
+     */
+    public float getYValueAt(int xVal) {
+        for (int i = 0; i < pointList.size() - 1; i++) {
+            // get the Points
+            if (xVal <= pointList.get(i + 1).getX()) {
+                // Curve erstellen
+                Line2D l1 = new Line2D.Double(pointList.get(i).getX(), pointList.get(i).getY(),
+                        pointList.get(i + 1).getX(), pointList.get(i + 1).getY());
+                Line2D l2 = new Line2D.Double(xVal, 0, xVal, height);
+                return getIntersectionPoint(l1, l2);
+            }
+        }
+        return 0;
+    }
+
+    /**
+     * Get y value at the x Coordination via curves.
+     *
+     * @param xVal the x value for the y value
+     * @return y value at x
+     */
+    public float getYValueAt2(int xVal) {
+        for (int i = 0; i < pointList.size() - 1; i++) {
+            // get the Points
+            if (xVal >= pointList.get(i).getX()) {
+                // Curve erstellen
+                c = buildCurve(pointList.get(i), pointList.get(i + 1));
+                c.subdivide(cl, cr);
+                // Teil der Kurve aussuchen
+                if (cl.getX1() <= xVal * scaleX && cl.getX2() > xVal * scaleX) {
+                    c = cl;
+                    // Kurve Links von "unten"
+                    if (pointList.get(i).getY() >= pointList.get(i + 1).getY()) {
+                        for (float j = (float) (height - 1); j >= 0; j -= 0.1f) {
+                            if (c.contains(xVal * scaleX, j * scaleY)) {
+                                return (float) (j);
+                            }
+                        }
+                    } else {// Kurve Links von "oben"
+                        for (float j = 0; j < height; j += 0.1f) {
+                            if (c.contains(xVal * scaleX, j * scaleY)) {
+                                return (float) (j);
+                            }
+                        }
+                    }
+                } else {
+                    c = cr;
+                    // Kurve Links von "unten"
+                    if (pointList.get(i).getY() >= pointList.get(i + 1).getY()) {
+                        for (float j = 0; j < height; j += 0.1f) {
+                            if (c.contains(xVal * scaleX, j * scaleY)) {
+                                return (float) (j);
+                            }
+                        }
+                    } else {// Kurve Links von "oben"
+                        for (float j = (float) (height - 1); j >= 0; j -= 0.1f) {
+                            if (c.contains(xVal * scaleX, j * scaleY)) {
+                                return (float) (j);
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        // else
+        return getYValueAt(xVal);
+    }
+
+    /**
+     * Get the Intersection Point of 2 Lines.
+     *
+     * @param l1 the first Line
+     * @param l2 the second Line
+     * @return The Intersection Point
+     */
+    public float getIntersectionPoint(Line2D l1, Line2D l2) {
+        if (!l1.intersectsLine(l2)) {
+            return 0;// null;
+        }
+        double px = l1.getX1(), py = l1.getY1(), rx = l1.getX2() - px, ry = l1.getY2() - py;
+        double qx = l2.getX1(), qy = l2.getY1(), sx = l2.getX2() - qx, sy = l2.getY2() - qy;
+
+        double det = sx * ry - sy * rx;
+        if (det == 0) {
+            return 0;// null;
+        } else {
+            double z = (sx * (qy - py) + sy * (px - qx)) / det;
+            if (z < 0 || z > 1) {
+                return 0;// new Point(0, 0); // intersection at end point!
+            }
+            return (float) (py + z * ry);// new Point((int) (px + z * rx), (int)
+            // (py + z * ry));
+        }
+    } // end intersection line-line
+
+    public void update(ArrayList<AbstractCpsObject> obj) {
+
+        ArrayDeque<AbstractCpsObject> queue = new ArrayDeque<>();
+
+        AbstractCpsObject u = null;
+        queue.addAll(obj);
+
+        while (!queue.isEmpty()) {
+            u = queue.pop();
+
+            repaintGraph(u);
+        }
+        empty();
+
+        if (u instanceof CpsUpperNode)
+            for (AbstractCpsObject adjacent : ((CpsUpperNode) u).getNodes()) {
+                queue.add(adjacent);
+            }
+    }
+
+    void repaintGraph(AbstractCpsObject u) {
+        ArrayList<HolonElement> list = new ArrayList<>();
+
+        if (u instanceof HolonObject) {
+            for (HolonElement ele : ((HolonObject) u).getElements()) {
+                list.add(ele);
+                repaintWithNewElement(list);
+                fillArrayofValue();
+                list.remove(0);
+            }
+        } else if (u instanceof HolonSwitch) {
+            repaintWithNewSwitch((HolonSwitch) u);
+            fillArrayofBooleans();
+        }
+    }
+
+    float getMaximum(HolonElement ele) {
+        if (ele.isFlexible()) {
+            return ele.getFlexibleEnergyAvailablePerElement();
+        } else {
+            return ele.getEnergyPerElement();
+        }
+    }
 }

+ 1192 - 1581
src/ui/view/UpperNodeCanvas.java

@@ -1,15 +1,14 @@
 package ui.view;
 
-import java.awt.BasicStroke;
-import java.awt.Color;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.Image;
-import java.awt.Point;
-import java.awt.RenderingHints;
+import classes.*;
+import com.google.gson.JsonParseException;
+import ui.controller.Control;
+import ui.controller.UpdateController;
+import ui.model.Model;
+
+import javax.swing.*;
+import java.awt.*;
 import java.awt.datatransfer.UnsupportedFlavorException;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseListener;
 import java.awt.event.MouseMotionListener;
@@ -17,1582 +16,1194 @@ import java.awt.geom.Line2D;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
-import java.util.Timer;
-import java.util.TimerTask;
-
-import javax.swing.ImageIcon;
-import javax.swing.JLabel;
-import javax.swing.JMenuItem;
-import javax.swing.JOptionPane;
-import javax.swing.JPanel;
-import javax.swing.JPopupMenu;
-import javax.swing.JScrollPane;
-import javax.swing.JSplitPane;
-import javax.swing.JTabbedPane;
-
-import com.google.gson.JsonParseException;
-
-import classes.CpsEdge;
-import classes.CpsNode;
-import classes.CpsUpperNode;
-import classes.AbstractCpsObject;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.Position;
-import classes.SubNet;
-import ui.controller.Control;
-import ui.controller.UpdateController;
-import ui.model.Model;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
- * 
+ *
  * @author Gruppe14
  */
-public class UpperNodeCanvas extends JPanel implements MouseListener, MouseMotionListener {
-
-	private static final long serialVersionUID = 1L;
-	private Image img = null; // Contains the image to draw on MyCanvas
-	private int x = 0;
-	private int y = 0;
-	// edge Object Start Point
-	private Model model;
-	private final Control controller;
-	Graphics2D g2; // For Painting
-	private int cx, cy;
-	private int sx, sy; // Mark Coords
-	private float scalediv20;
-
-	// Path
-	public String path;
-	private JLabel breadCrumb;
-
-	ArrayList<HolonElement> dataSelected = new ArrayList<HolonElement>();
-	ArrayList<AbstractCpsObject> tempSelected = new ArrayList<AbstractCpsObject>();
-
-	// The UpperNode
-	public CpsUpperNode upperNode;
-	public int code;
-
-	private boolean[] showedInformation = new boolean[5];
-	private boolean dragging = false; // for dragging
-	private boolean dragged = false; // if an object/objects was/were dragged
-	private boolean drawEdge = false; // for drawing edges
-	private boolean click = false; // for double click
-	private boolean doMark = false; // for double click
-	public AbstractCpsObject tempCps = null;
-	private CpsEdge edgeHighlight = null;
-
-	// PopUpMenu
-	private JPopupMenu popmenu = new JPopupMenu();
-	private JMenuItem itemDelete = new JMenuItem("Delete");
-	private JMenuItem itemCut = new JMenuItem("Cut");
-	private JMenuItem itemCopy = new JMenuItem("Copy");
-	public JMenuItem itemPaste = new JMenuItem("Paste");
-	public JMenuItem itemGroup = new JMenuItem("Group");
-	public JMenuItem itemUngroup = new JMenuItem("Ungroup");
-	public JMenuItem itemTrack = new JMenuItem("Track");
-	public JMenuItem itemUntrack = new JMenuItem("Untrack");
-
-	// Tooltip
-	private boolean toolTip; // Tooltip on or off
-	private Position toolTipPos = new Position(); // Tooltip Position
-	private String toolTipText = "";
-
-	private Point mousePosition = new Point(); // Mouse Position when
-												// rightclicked
-
-	// contains the value of the Capacity for new created Edges
-
-	private UpdateController updCon;
-
-	// Animation Stuff
-	javax.swing.Timer animT; // animation Timer
-	private final int ANIMTIME = 500; // animation Time
-
-	private ArrayList<AbstractCpsObject> animCps = null;
-	private int animFPS = 60;
-	private int animDuration = ANIMTIME; // animation Duration
-	private int animDelay = 1000 / animFPS; // animation Delay
-	private int animSteps = animDuration / animDelay; // animation Steps;
-	private Position unPos;
-	private ArrayList<Position> savePos;
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param mod
-	 *            the Model
-	 * @param control
-	 *            the Controller
-	 * @param unitGraph
-	 */
-	public UpperNodeCanvas(Model mod, Control control, UnitGraph unitGraph, CpsUpperNode UpperNode, String parentPath) {
-		toolTip = false;
-
-		this.controller = control;
-		this.model = mod;
-		this.upperNode = UpperNode;
-		this.code = UpperNode.hashCode();
-		this.path = parentPath + upperNode.getName();
-		this.breadCrumb = new JLabel(path);
-		// this.add(breadCrumb);
-		scalediv20 = model.getScale() / 20;
-
-		// Cps objecte aus dem border links schieben
-		upperNode.setLeftBorder((int) (50 + scalediv20 + scalediv20 + 10));
-		for (AbstractCpsObject cps : upperNode.getNodes()) {
-			if (cps.getPosition().x < model.getScaleDiv2() + upperNode.getLeftBorder() + 5) {
-				cps.setPosition(
-						new Position(upperNode.getLeftBorder() + 5 + model.getScaleDiv2(), cps.getPosition().y));
-			}
-		}
-
-		showedInformation[0] = true;
-		showedInformation[1] = true;
-		showedInformation[4] = true;
-
-		popmenu.add(itemCut);
-		popmenu.add(itemCopy);
-		popmenu.add(itemPaste);
-		popmenu.add(itemDelete);
-		popmenu.addSeparator();
-		popmenu.add(itemGroup);
-		popmenu.add(itemUngroup);
-		popmenu.add(itemTrack);
-		popmenu.add(itemUntrack);
-
-		itemDelete.setEnabled(false);
-		itemCut.setEnabled(false);
-		itemCopy.setEnabled(false);
-		itemPaste.setEnabled(true);
-		itemGroup.setEnabled(false);
-		itemUngroup.setEnabled(false);
-		itemTrack.setEnabled(false);
-		itemUntrack.setEnabled(false);
-		updCon = new UpdateController(model, controller);
-
-		itemGroup.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				// calculate uppernode pos (taken from the controller)
-				unPos = new Position(0, 0);
-				animCps = new ArrayList<>();
-				for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
-					animCps.add(cps); // add to animation Cps ArrayList
-					unPos.x += cps.getPosition().x;
-					unPos.y += cps.getPosition().y;
-				}
-				unPos.x /= animCps.size();
-				unPos.y /= animCps.size();
-
-				// save old Position
-				savePos = new ArrayList<>();
-				for (int i = 0; i < animCps.size(); i++) {
-					savePos.add(new Position(0, 0));
-					savePos.get(i).x = animCps.get(i).getPosition().x;
-					savePos.get(i).y = animCps.get(i).getPosition().y;
-				}
-
-				animT = new javax.swing.Timer(animDelay, new ActionListener() {
-
-					@Override
-					public void actionPerformed(ActionEvent e) {
-						if (animDuration - animDelay > 0 && animCps.size() > 1) {
-							for (int i = 0; i < animCps.size(); i++) {
-								double x1 = animCps.get(i).getPosition().x - unPos.x;
-								double y1 = animCps.get(i).getPosition().y - unPos.y;
-								animCps.get(i).getPosition().x -= x1 / animSteps;
-								animCps.get(i).getPosition().y -= y1 / animSteps;
-							}
-							repaint();
-							animDuration -= animDelay;
-							animSteps--;
-						} else {
-							animDuration = ANIMTIME;
-							animSteps = animDuration / animDelay;
-							animT.stop();
-							for (int i = 0; i < animCps.size(); i++) {
-								animCps.get(i).getPosition().x = savePos.get(i).x;
-								animCps.get(i).getPosition().y = savePos.get(i).y;
-							}
-							controller.addUpperNode("NodeOfNode", upperNode, model.getSelectedCpsObjects());
-							controller.calculateStateForCurrentTimeStep();
-							repaint();
-						}
-					}
-				});
-				animT.start();
-			}
-		});
-
-		itemUngroup.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				// save old Position
-				JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent().getParent();
-				for (int i = 4; i < tabbedPane.getTabCount(); i++) {
-					if (((UpperNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
-							.getComponent(0)).upperNode.getId() == ((CpsUpperNode) tempCps).getId()) {
-						tabbedPane.remove(i);
-						break;
-					}
-				}
-
-				savePos = new ArrayList<>();
-				animCps = ((CpsUpperNode) tempCps).getNodes();
-				controller.delUpperNode((CpsUpperNode) tempCps, upperNode);
-
-				for (int i = 0; i < animCps.size(); i++) {
-					savePos.add(new Position(0, 0));
-					savePos.get(i).x = animCps.get(i).getPosition().x;
-					savePos.get(i).y = animCps.get(i).getPosition().y;
-				}
-				for (AbstractCpsObject cps : animCps) {
-					int x = ((CpsUpperNode) tempCps).getPosition().x;
-					int y = ((CpsUpperNode) tempCps).getPosition().y;
-
-					cps.setPosition(new Position(x, y));
-				}
-
-				animT = new javax.swing.Timer(animDelay, new ActionListener() {
-
-					@Override
-					public void actionPerformed(ActionEvent e) {
-						if (animDuration - animDelay >= 0) {
-							for (int i = 0; i < animCps.size(); i++) {
-								double x1 = animCps.get(i).getPosition().x - savePos.get(i).x;
-								double y1 = animCps.get(i).getPosition().y - savePos.get(i).y;
-								animCps.get(i).getPosition().x -= x1 / animSteps;
-								animCps.get(i).getPosition().y -= y1 / animSteps;
-							}
-							repaint();
-							animDuration -= animDelay;
-							animSteps--;
-						} else {
-							animDuration = ANIMTIME;
-							animSteps = animDuration / animDelay;
-							animT.stop();
-							for (int i = 0; i < animCps.size(); i++) {
-								animCps.get(i).getPosition().x = savePos.get(i).x;
-								animCps.get(i).getPosition().y = savePos.get(i).y;
-							}
-
-							controller.calculateStateForCurrentTimeStep();
-							repaint();
-						}
-					}
-				});
-				animT.start();
-			}
-		});
-
-		itemTrack.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				for (AbstractCpsObject o : model.getSelectedCpsObjects()) {
-					if (o instanceof HolonObject) {
-						boolean found = false;
-						if (controller.getTrackingObj() != null) {
-							for (AbstractCpsObject obj : controller.getTrackingObj()) {
-								if (obj instanceof HolonObject) {
-									if (obj.getId() == o.getId()) {
-										found = true;
-									}
-								}
-							}
-						}
-						if (!found) {
-							controller.addTrackingObj((HolonObject) o);
-							((HolonObject) o).updateTrackingInfo();
-						}
-						if (model.getShowConsoleLog()) {
-							controller.addTextToConsole("Tracking: ", Color.BLACK, 12, false, false, false);
-							controller.addTextToConsole("" + o.getName(), Color.BLUE, 12, true, false, false);
-							controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-							controller.addTextToConsole("" + o.getId(), Color.RED, 12, true, false, true);
-						}
-					}
-				}
-			}
-		});
-
-		itemUntrack.addActionListener(new ActionListener() {
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				for (AbstractCpsObject o : model.getSelectedCpsObjects()) {
-					if (o instanceof HolonObject) {
-						boolean found = false;
-						if (controller.getTrackingObj() != null) {
-							for (AbstractCpsObject obj : controller.getTrackingObj()) {
-								if (obj instanceof HolonObject) {
-									if (obj.getId() == o.getId()) {
-										found = true;
-									}
-								}
-							}
-						}
-						if (found) {
-							// Removed from tracking array and tracking
-							// information reseted
-							controller.removeTrackingObj((HolonObject) o);
-							((HolonObject) o).setTrackingProd(new float[100]);
-							((HolonObject) o).setTrackingCons(new float[100]);
-						}
-					}
-				}
-				System.out.println(controller.getTrackingObj());
-			}
-		});
-
-		itemDelete.addActionListener(new ActionListener() {
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				// Remove the selected Object objects
-				for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
-					if (upperNode.getNodes().contains(cps)) {
-						controller.delObjUpperNode(cps, upperNode);
-						// Removes the object from the tracked objects, in case
-						// it was tracked
-						controller.removeTrackingObj(cps);
-						// Remove UpperNodeTab if UpperNode deleted
-						if (cps instanceof CpsUpperNode) {
-							boolean splitView = false;
-							JSplitPane tempSplit = (JSplitPane) getParent().getParent().getParent().getParent();
-							JTabbedPane tabbedPane;
-							JTabbedPane tabbedPane2;
-							// if SplitView is activated
-							if (tempSplit.getLeftComponent() instanceof JTabbedPane
-									&& tempSplit.getRightComponent() instanceof JTabbedPane) {
-								splitView = true;
-								tabbedPane = (JTabbedPane) tempSplit.getLeftComponent();
-								tabbedPane2 = (JTabbedPane) tempSplit.getRightComponent();
-							} else {
-								tabbedPane = (JTabbedPane) tempSplit.getLeftComponent();
-								tabbedPane2 = null;
-							}
-							// Look if the uppernode is open in a Tab
-							for (int i = 4; i < tabbedPane.getTabCount(); i++) {
-								if (tabbedPane.getComponentAt(i) == null) {
-								} else if (((UpperNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
-										.getComponent(0)).upperNode.getId() == cps.getId()) {
-									((ButtonTabComponent) tabbedPane.getTabComponentAt(i)).removeTabs();
-									break;
-								}
-							}
-							// If SplitView is on and the view on
-							// tabbedPane2 is the deleted upperNode
-							try {
-								if (tabbedPane2 != null
-										&& ((UpperNodeCanvas) ((JScrollPane) tabbedPane2.getSelectedComponent())
-												.getViewport().getComponent(0)).upperNode.getId() == cps.getId()) {
-									((ButtonTabComponent) tabbedPane.getTabComponentAt(tabbedPane2.getSelectedIndex()))
-											.removeTabs();
-								}
-							} catch (Exception e2) {
-							}
-
-						}
-					}
-				}
-				toolTip = false;
-				model.getSelectedCpsObjects().clear();
-				tempCps = null;
-				repaint();
-			}
-		});
-
-		itemCut.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				controller.cut(upperNode);
-				itemPaste.setEnabled(true);
-				repaint();
-			}
-		});
-
-		itemCopy.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				controller.copy(upperNode);
-				itemPaste.setEnabled(true);
-				repaint();
-			}
-		});
-
-		itemPaste.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				try {
-					controller.paste(upperNode, mousePosition);
-					unitGraph.update(model.getSelectedCpsObjects());
-				} catch (JsonParseException | UnsupportedFlavorException | IOException e1) {
-					// TODO Auto-generated catch block
-					JLabel message = new JLabel("The Clipboard information cannot be pastet into Application.");
-					JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
-				}
-				repaint();
-			}
-		});
-
-		this.addMouseListener(this);
-		this.addMouseMotionListener(this);
-	}
-
-	/**
-	 * Paints all Components on the Canvas.
-	 * 
-	 * @param g
-	 *            Graphics
-	 */
-	public void paintComponent(Graphics g) {
-		String maxCap;
-		super.paintComponent(g);
-		((JScrollPane) this.getParent().getParent()).setColumnHeaderView(breadCrumb);
-		// Rendering
-		g2 = (Graphics2D) g;
-		RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
-		g2.setRenderingHints(rh);
-
-		// Paint the Background
-		if (!upperNode.getImagePath().isEmpty()) {
-			img = new ImageIcon(upperNode.getImagePath()).getImage();
-			switch (upperNode.getBackgroundMode()) {
-			case BackgroundPopUp.IMAGE_PIXELS:
-				g2.drawImage(img, upperNode.getLeftBorder(), 0, img.getWidth(null), img.getHeight(null), null);
-				break;
-			case BackgroundPopUp.STRETCHED:
-				g2.drawImage(img, upperNode.getLeftBorder(), 0, model.getCanvasX(), model.getCanvasY(), null);
-				break;
-			case BackgroundPopUp.CUSTOM:
-				g2.drawImage(img, upperNode.getLeftBorder(), 0, upperNode.getImageWidht(), upperNode.getImageHeight(),
-						null);
-				break;
-			default:
-				break;
-			}
-		}
-
-		// Draw Left Border
-		g2.setColor(new Color(230, 230, 230));
-		g2.fillRect(0, 0, upperNode.getLeftBorder(), this.getHeight());
-		g2.setColor(Color.BLACK);
-		g2.drawLine(0, 0, this.getWidth(), 0);
-
-		// Test SubNet Coloring
-		int i = 0;
-		for (SubNet s : controller.getSimManager().getSubNets()) {
-
-			if (model.getSubNetColors().size() - 1 < i) {
-				controller.addSubNetColor(new Color((int) (Math.random() * 255), (int) (Math.random() * 255),
-						(int) (Math.random() * 255)));
-			}
-
-			for (HolonObject cps : s.getObjects()) {
-				cps.setBorderColor(model.getSubNetColors().get(i));
-			}
-			i++;
-		}
-
-		// drawEdges that is being dragged
-		if (drawEdge) {
-			g2.setColor(Color.BLACK);
-			g2.setStroke(new BasicStroke(2));
-
-			// If TempCps is an outside Object
-			if (!upperNode.getNodes().contains(tempCps)) {
-				int count = 0;
-				for (CpsEdge e : upperNode.getConnections()) {
-					if (e.getA().equals(tempCps)) {
-						g2.drawLine(upperNode.getLeftBorder() >> 1, (int) (model.getScaleDiv2() + scalediv20 + 5
-								+ (model.getScale() + scalediv20 + 10) * count), x, y);
-					} else if (e.getB().equals(tempCps)) {
-						g2.drawLine(upperNode.getLeftBorder() >> 1, (int) (model.getScaleDiv2() + scalediv20 + 5
-								+ (model.getScale() + scalediv20 + 10) * count), x, y);
-					}
-					count++;
-				}
-			} else {
-				g2.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
-			}
-		}
-		// draw Edges
-		for (CpsEdge con : upperNode.getNodeEdges()) {
-			if (con.getA().getId() != model.getSelectedObjectID() && con.getB().getId() != model.getSelectedObjectID()
-					&& con != edgeHighlight) {
-				if (con.getConnected() == 0) {
-					if (con.getState()) {
-						g2.setColor(Color.GREEN);
-						if (con.getCapacity() != -1) {
-							g2.setStroke(new BasicStroke(Math.min(((con.getFlow() / con.getCapacity() * 3) + 1), 4)));
-						}
-					} else {
-						g2.setColor(Color.RED);
-						g2.setStroke(new BasicStroke(2));
-					}
-				} else {
-					g2.setColor(Color.DARK_GRAY);
-					g2.setStroke(new BasicStroke(2));
-				}
-				g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
-						con.getB().getPosition().y);
-
-				if (con.getCapacity() == -1) {
-					maxCap = Character.toString('\u221e');
-				} else if (con.getCapacity() == -2) {
-					maxCap = "???";
-				} else {
-					maxCap = String.valueOf(con.getCapacity());
-				}
-				if (showedInformation[0]) {
-					if (con.getConnected() == 0 || con.getConnected() == 1) {
-						g2.drawString(con.getFlow() + "/" + maxCap,
-								(con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-								(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-					} else {
-						g2.drawString("not connected", (con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-								(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-					}
-				}
-			}
-		}
-
-		// Objects connected to upperNode
-		int count = 0;
-		for (CpsEdge e : upperNode.getConnections()) {
-			AbstractCpsObject cps;
-			if (e.getA().equals(this.upperNode)) {
-				cps = e.getB();
-			} else {
-				cps = e.getA();
-			}
-			// Show and Highlight
-			if (model.getSelectedCpsObjects().contains(cps) || showedInformation[4] == true) {
-				for (CpsEdge ed : cps.getConnections()) {
-					AbstractCpsObject obj = null;
-					if (upperNode.getNodes().contains(ed.getA())) {
-						obj = ed.getA();
-					} else if (upperNode.getNodes().contains(ed.getB())) {
-						obj = ed.getB();
-					}
-					if (obj != null) {
-						if (ed.getConnected() == 0) {
-							if (ed.getState()) {
-								g2.setColor(Color.GREEN);
-								if (ed.getCapacity() != -1) {
-									g2.setStroke(
-											new BasicStroke(Math.min(((ed.getFlow() / ed.getCapacity() * 3) + 1), 4)));
-								}
-							} else {
-								g2.setColor(Color.RED);
-								g2.setStroke(new BasicStroke(2));
-							}
-							if (ed.getA().getId() == model.getSelectedObjectID()
-									|| ed.getB().getId() == model.getSelectedObjectID() || edgeHighlight == ed)
-								g2.setColor(Color.BLUE);
-						} else {
-							g2.setColor(Color.DARK_GRAY);
-							g2.setStroke(new BasicStroke(2));
-						}
-						g2.drawLine(obj.getPosition().x, obj.getPosition().y, (upperNode.getLeftBorder() >> 1),
-								(int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + 25);
-						if (showedInformation[0]) {
-							if (ed.getCapacity() == -1) {
-								maxCap = Character.toString('\u221e');
-							} else if (ed.getCapacity() == -2) {
-								maxCap = "???";
-							} else {
-								maxCap = String.valueOf(ed.getCapacity());
-							}
-							if (ed.getConnected() == 0 || ed.getConnected() == 1) {
-								g2.drawString(ed.getFlow() + "/" + maxCap,
-										(obj.getPosition().x + (upperNode.getLeftBorder() >> 1)) / 2,
-										(obj.getPosition().y + (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count)
-												+ 25) / 2);
-							} else {
-								g2.drawString("not connected",
-										(obj.getPosition().x + (upperNode.getLeftBorder() >> 1)) / 2,
-										(obj.getPosition().y + (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count)
-												+ 25) / 2);
-							}
-						}
-					}
-				}
-			}
-
-			// Border Highlighting
-			if (showedInformation[3]) {
-				g2.setColor(cps.getBorderColor());
-				if (g2.getColor() != Color.WHITE) {
-					g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20) - 3,
-							(int) (scalediv20 + 5 + (25 + scalediv20 + 10) * count - scalediv20) - 3,
-							(int) (50 + ((scalediv20 + 3) * 2)), (int) (50 + ((scalediv20 + 3) * 2)));
-				}
-			}
-
-			// node image
-			if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
-					|| model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
-				img = new ImageIcon(this.getClass().getResource("/Images/node_selected.png")).getImage();
-			} else {
-				if (cps instanceof HolonSwitch) {
-					if (((HolonSwitch) cps).getActiveAt()[model.getCurIteration()]) {
-						((HolonSwitch) cps).setAutoState(true);
-					} else {
-						((HolonSwitch) cps).setAutoState(false);
-					}
-				}
-				// Highlighting
-				if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
-						|| model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
-					g2.setColor(Color.BLUE);
-					g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20),
-							(int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count - scalediv20),
-							(int) (50 + (scalediv20 * 2)), (int) (50 + (scalediv20 * 2)));
-				} else if (cps instanceof HolonObject) {
-					g2.setColor(((HolonObject) cps).getColor());
-
-					g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20),
-							(int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count - scalediv20),
-							(int) (50 + (scalediv20 * 2)), (int) (50 + (scalediv20 * 2)));
-				}
-				// draw image
-				File checkPath = new File(cps.getImage());
-				if (checkPath.exists()) {
-					img = new ImageIcon(cps.getImage()).getImage();
-				} else {
-					img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage();
-				}
-			}
-			g2.drawImage(img, (upperNode.getLeftBorder() >> 1) - 25,
-					(int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count), 50, 50, null);
-			count++;
-		}
-		// Highlighted Edge
-		if (model.getSelectedObjectID() > 0 || !model.getSelectedCpsObjects().isEmpty() || !tempSelected.isEmpty()) {
-			g2.setColor(Color.BLUE);
-			for (CpsEdge con : upperNode.getNodeEdges()) {
-				if (con.getFlow() <= con.getCapacity()) {
-					g2.setStroke(new BasicStroke(Math.min((con.getFlow() / con.getCapacity() * 3) + 1, 4)));
-				} else {
-					g2.setStroke(new BasicStroke(2));
-				}
-				if (con.getA().getId() == model.getSelectedObjectID()
-						|| model.getSelectedCpsObjects().contains(con.getA()) || tempSelected.contains(con.getA())
-						|| con.getB().getId() == model.getSelectedObjectID()
-						|| model.getSelectedCpsObjects().contains(con.getB())
-						|| tempSelected.contains(con.getB()) && con != edgeHighlight) {
-					g2.drawLine(con.getA().getPosition().x, con.getA().getPosition().y, con.getB().getPosition().x,
-							con.getB().getPosition().y);
-
-					if (con.getCapacity() == -1) {
-						maxCap = Character.toString('\u221e');
-					} else if (con.getCapacity() == -2) {
-						maxCap = "???";
-					} else {
-						maxCap = String.valueOf(con.getCapacity());
-					}
-					if (showedInformation[0]) {
-						if (con.getConnected() == 0 || con.getConnected() == 1) {
-							g2.drawString(con.getFlow() + "/" + maxCap,
-									(con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-									(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-						} else {
-							g2.drawString("not connected",
-									(con.getA().getPosition().x + con.getB().getPosition().x) / 2,
-									(con.getA().getPosition().y + con.getB().getPosition().y) / 2);
-						}
-					}
-				}
-			}
-		} else if (edgeHighlight != null) {
-			g2.setColor(Color.BLUE);
-			if (edgeHighlight.getFlow() <= edgeHighlight.getCapacity()) {
-				g2.setStroke(
-						new BasicStroke(Math.min((edgeHighlight.getFlow() / edgeHighlight.getCapacity() * 3) + 1, 4)));
-			} else {
-				g2.setStroke(new BasicStroke(2));
-			}
-			if (upperNode.getNodeEdges().contains(edgeHighlight)) {
-				g2.drawLine(edgeHighlight.getA().getPosition().x, edgeHighlight.getA().getPosition().y,
-						edgeHighlight.getB().getPosition().x, edgeHighlight.getB().getPosition().y);
-
-				if (edgeHighlight.getCapacity() == -1) {
-					maxCap = Character.toString('\u221e');
-				} else if (edgeHighlight.getCapacity() == -2) {
-					maxCap = "???";
-				} else {
-					maxCap = String.valueOf(edgeHighlight.getCapacity());
-				}
-				if (showedInformation[0]) {
-					g2.drawString(edgeHighlight.getFlow() + "/" + maxCap,
-							(edgeHighlight.getA().getPosition().x + edgeHighlight.getB().getPosition().x) / 2,
-							(edgeHighlight.getA().getPosition().y + edgeHighlight.getB().getPosition().y) / 2);
-				}
-			}
-		}
-
-		// Objects in upper node
-		for (AbstractCpsObject cps : upperNode.getNodes()) {
-			// Border Highlighting
-			if (showedInformation[3]) {
-				g2.setColor(cps.getBorderColor());
-				if (g2.getColor() != Color.WHITE) {
-					g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20 - 3),
-							(int) (cps.getPosition().y - model.getScaleDiv2() - scalediv20 - 3),
-							(int) (controller.getScale() + ((scalediv20 + 3) * 2)),
-							(int) (controller.getScale() + ((scalediv20 + 3) * 2)));
-				}
-			}
-
-			// node image
-			if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
-					|| model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
-				img = new ImageIcon(this.getClass().getResource("/Images/node_selected.png")).getImage();
-			} else {
-				if (cps instanceof HolonSwitch) {
-					if (((HolonSwitch) cps).getActiveAt()[model.getCurIteration()]) {
-						((HolonSwitch) cps).setAutoState(true);
-					} else {
-						((HolonSwitch) cps).setAutoState(false);
-					}
-				}
-				// Highlighting
-				if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
-						|| model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
-					g2.setColor(Color.BLUE);
-					g2.fillRect((int) (cps.getPosition().x - model.getScaleDiv2() - scalediv20),
-							(int) (cps.getPosition().y - model.getScaleDiv2() - scalediv20),
-							(int) (controller.getScale() + (scalediv20 * 2)),
-							(int) (controller.getScale() + (scalediv20 * 2)));
-					if (showedInformation[1] && cps instanceof HolonObject) {
-						g2.setColor(Color.BLACK);
-						float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
-						g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - model.getScaleDiv2(),
-								cps.getPosition().y - model.getScaleDiv2() - 10);
-					}
-				} else if (cps instanceof HolonObject) {
-					g2.setColor(((HolonObject) cps).getColor());
-
-					g2.fillRect((int) (cps.getPosition().x - model.getScaleDiv2() - scalediv20),
-							(int) (cps.getPosition().y - model.getScaleDiv2() - scalediv20),
-							(int) (controller.getScale() + (scalediv20 * 2)),
-							(int) (controller.getScale() + (scalediv20 * 2)));
-
-					if (showedInformation[1]) {
-						g2.setColor(Color.BLACK);
-						float totalEnergy = ((HolonObject) cps).getCurrentEnergyAtTimeStep(model.getCurIteration());
-						g2.drawString(Float.toString(totalEnergy), cps.getPosition().x - model.getScaleDiv2(),
-								cps.getPosition().y - model.getScaleDiv2() - 10);
-					}
-				}
-				// draw image
-				File checkPath = new File(cps.getImage());
-				if (checkPath.exists()) {
-					img = new ImageIcon(cps.getImage()).getImage();
-				} else {
-					img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage();
-				}
-			}
-			g2.drawImage(img, cps.getPosition().x - model.getScaleDiv2(), cps.getPosition().y - model.getScaleDiv2(),
-					controller.getScale(), controller.getScale(), null);
-		}
-
-		// Dragg Highlighting
-		g2.setStroke(new BasicStroke(1));
-		if (doMark) {
-			g2.setColor(Color.BLACK);
-			if (sx > x && sy > y) {
-				g2.drawRect(x, y, sx - x, sy - y);
-			} else if (sx < x && sy < y) {
-				g2.drawRect(sx, sy, x - sx, y - sy);
-			} else if (sx >= x) {
-				g2.drawRect(x, sy, sx - x, y - sy);
-			} else if (sy >= y) {
-				g2.drawRect(sx, y, x - sx, sy - y);
-			}
-		}
-
-		// Border Line
-		g2.setColor(Color.BLACK);
-		g2.drawLine(upperNode.getLeftBorder(), 0, upperNode.getLeftBorder(), this.getHeight());
-
-		// Tooltip
-		if (toolTip) {
-			g2.setColor(new Color(255, 225, 150));
-			g2.setStroke(new BasicStroke(1));
-			int textWidth = g.getFontMetrics().stringWidth(toolTipText) + 2; // Text
-																				// width
-			int fixXPos = toolTipPos.x - (textWidth >> 1) + model.getScaleDiv2(); // Position
-																					// fixed
-																					// x
-																					// Position
-																					// to
-																					// the
-																					// screen
-			int fixYPos = toolTipPos.y; //// Position fixed y Position to the
-										//// screen
-			if (fixXPos < 0) {
-				fixXPos = 0;
-			} else if (fixXPos + textWidth + 1 > this.getWidth()) {
-				fixXPos -= (fixXPos + textWidth + 1) - this.getWidth();
-			}
-			if (fixYPos + 16 > this.getHeight()) {
-				fixYPos -= (fixYPos + 16) - this.getHeight();
-			}
-			g2.fillRect(fixXPos, fixYPos, textWidth, 15);
-			g2.setColor(Color.BLACK);
-			g2.drawRect(fixXPos, fixYPos, textWidth, 15);
-			g2.drawString(toolTipText, fixXPos + 2, fixYPos + 12);
-		}
-	}
-
-	@Override
-	public void mouseClicked(MouseEvent e) {
-		updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-	}
-
-	@Override
-	public void mouseEntered(MouseEvent e) {
-	}
-
-	@Override
-	public void mouseExited(MouseEvent e) {
-	}
-
-	@Override
-	public void mousePressed(MouseEvent e) {
-		tempCps = null;
-		dataSelected = null;
-		edgeHighlight = null;
-		controller.setSelecteEdge(null);
-		controller.setSelectedObjectID(-1);
-		// Object Selection
-
-		// Erase old data in the PropertyTable
-		if (model.getPropertyTable().getRowCount() > 0) {
-			for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
-				model.getPropertyTable().removeRow(i);
-			}
-		}
-
-		if (e.getX() > upperNode.getLeftBorder()) {
-			for (AbstractCpsObject cps : upperNode.getNodes()) {
-				cx = cps.getPosition().x - model.getScaleDiv2();
-				cy = cps.getPosition().y - model.getScaleDiv2();
-				if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
-					tempCps = cps;
-					if (model.getShowConsoleLog()) {
-						controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
-						controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
-						controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-						controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
-					}
-					dragging = true;
-					if (e.isControlDown() && tempCps != null) {
-						if (model.getSelectedCpsObjects().contains(tempCps)) {
-							controller.deleteSelectedObject(tempCps);
-						} else {
-							controller.addSelectedObject(tempCps);
-						}
-					}
-
-					// If drawing an Edge (CTRL down)
-					if (tempCps.getClass() == HolonObject.class) {
-						HolonObject tempObj = ((HolonObject) tempCps);
-						dataSelected = tempObj.getElements();
-					}
-					if (e.isShiftDown()) {
-						drawEdge = true;
-						dragging = false;
-					}
-					break;
-				}
-			}
-		} else {
-			// look for objects connected to uppernode
-			int count = 0;
-			for (CpsEdge ed : upperNode.getConnections()) {
-				AbstractCpsObject cps;
-				if (ed.getA().equals(this.upperNode)) {
-					cps = ed.getB();
-				} else {
-					cps = ed.getA();
-				}
-				if (x - controller.getScale() <= ((upperNode.getLeftBorder() >> 1) - model.getScaleDiv2())
-						&& y - controller.getScale() <= (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count)
-						&& x >= (upperNode.getLeftBorder() >> 1) - model.getScaleDiv2()
-						&& y >= (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count)) {
-					tempCps = cps;
-					if (model.getShowConsoleLog()) {
-						controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
-						controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
-						controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
-						controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
-						controller.setSelectedObjectID(tempCps.getId());
-					}
-					// If drawing an Edge (CTRL down)
-					if (tempCps.getClass() == HolonObject.class) {
-						HolonObject tempObj = ((HolonObject) tempCps);
-						dataSelected = tempObj.getElements();
-					}
-					if (e.isShiftDown()) {
-						drawEdge = true;
-					}
-				}
-				count++;
-			}
-		}
-
-		// Selection of CpsObject
-		// model.setSelectedCpsObject(tempCps);
-
-		// Edge Selection
-		if (e.getButton() == e.BUTTON1) {
-			if (tempCps == null) {
-				edgeHighlight = mousePositionOnEdge(x, y);
-				controller.setSelecteEdge(edgeHighlight);
-				controller.setSelectedObjectID(0);
-				if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
-					model.getSelectedCpsObjects().clear();
-				}
-				updCon.deleteRows(model.getMultiTable());
-				updCon.deleteRows(model.getSingleTable());
-			}
-
-			if (edgeHighlight == null && tempCps == null) {
-				sx = e.getX();
-				sy = e.getY();
-				doMark = true;
-			}
-			// System.out.println("Selected Objects");
-			// for (AbstractCpsObject temp : model.getSelectedCpsObjects()) {
-			// System.out.println(temp.getName() + " " + temp.getID());
-			// }
-			repaint();
-		}
-	}
-
-	@Override
-	public void mouseReleased(MouseEvent e) {
-		x = e.getX();
-		y = e.getY();
-		dragging = false;
-		if (model.getSelectedCpsObjects().size() > 1) {
-			model.getTableHolonElement().setModel(model.getMultiTable());
-		} else if (model.getSelectedCpsObjects().size() == 1) {
-			model.getTableHolonElement().setModel(model.getSingleTable());
-		}
-
-		if (drawEdge) {
-			drawEdge = false;
-			drawDeleteEdge();
-		}
-
-		if (dragged == true) {
-			try {
-				controller.autoSave();
-			} catch (IOException ex) {
-				// TODO Auto-generated catch block
-				ex.printStackTrace();
-			}
-		}
-
-		if (!e.isControlDown() && dragged == false && tempCps != null && MouseEvent.BUTTON3 != e.getButton()) {
-			model.getSelectedCpsObjects().clear();
-			controller.addSelectedObject(tempCps);
-		}
-
-		dragged = false;
-
-		// Rightclick List
-		if (e.getButton() == MouseEvent.BUTTON3) {
-			if (tempCps != null) {
-				itemDelete.setEnabled(true);
-				itemCut.setEnabled(true);
-				itemCopy.setEnabled(true);
-				if (tempCps != null) {
-					itemGroup.setEnabled(true);
-					itemTrack.setEnabled(true);
-					itemUntrack.setEnabled(true);
-				}
-				if (tempCps instanceof CpsUpperNode)
-					itemUngroup.setEnabled(true);
-				else
-					itemUngroup.setEnabled(false);
-				if (model.getSelectedCpsObjects().size() == 0) {
-					controller.addSelectedObject(tempCps);
-				}
-			} else {
-				itemCut.setEnabled(false);
-				itemCopy.setEnabled(false);
-				itemDelete.setEnabled(false);
-				itemGroup.setEnabled(false);
-				itemUngroup.setEnabled(false);
-				itemTrack.setEnabled(false);
-				itemUntrack.setEnabled(false);
-			}
-			mousePosition = this.getMousePosition();
-			popmenu.show(e.getComponent(), e.getX(), e.getY());
-		}
-
-		if (doMark) {
-			doMark = false;
-			for (AbstractCpsObject cps : tempSelected) {
-				if (!model.getSelectedCpsObjects().contains(cps)) {
-					controller.addSelectedObject(cps);
-				}
-			}
-			controller.getObjectsInDepth();
-			tempSelected.clear();
-		}
-
-		if (doubleClick() && tempCps != null && tempCps instanceof HolonSwitch) {
-			((HolonSwitch) tempCps).switchState();
-		}
-
-		controller.calculateStateForTimeStep(model.getCurIteration());
-		updCon.paintProperties(tempCps);
-		updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-		updCon.refreshTableProperties(model.getPropertyTable());
-		repaint();
-
-	}
-
-	@Override
-	public void mouseDragged(MouseEvent e) {
-		// If Edge is drawn
-		x = e.getX();
-		y = e.getY();
-		if (!model.getSelectedCpsObjects().contains(tempCps) && doMark == false) {
-			model.getSelectedCpsObjects().clear();
-			if (tempCps != null) {
-				controller.addSelectedObject(tempCps);
-			}
-		}
-		if (dragging) {
-			try {
-				// tempCps in the upperNode? else its a connected Object from
-				// outside
-				if (upperNode.getNodes().contains(tempCps)) {
-					dragged = true;
-					float xDist, yDist; // Distance
-
-					x = e.getX();
-					y = e.getY();
-
-					// Make sure its in bounds
-					if (e.getX() < controller.getScaleDiv2() + upperNode.getLeftBorder() + 5)
-						x = controller.getScaleDiv2() + upperNode.getLeftBorder() + 5;
-					else if (e.getX() > this.getWidth() - controller.getScaleDiv2())
-						x = this.getWidth() - controller.getScaleDiv2();
-					if (e.getY() < controller.getScaleDiv2())
-						y = controller.getScaleDiv2();
-					else if (e.getY() > this.getHeight() - controller.getScaleDiv2())
-						y = this.getHeight() - controller.getScaleDiv2();
-
-					// Distance
-					xDist = x - tempCps.getPosition().x;
-					yDist = y - tempCps.getPosition().y;
-
-					tempCps.setPosition(x, y); // Drag Position
-
-					// TipText Position and name
-					toolTip = true;
-					toolTipText = tempCps.getName() + ", " + tempCps.getId();
-					toolTipPos.x = tempCps.getPosition().x - model.getScaleDiv2();
-					toolTipPos.y = tempCps.getPosition().y + model.getScaleDiv2();
-
-					// All Selected Objects
-					for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
-						if (cps != tempCps) {
-							x = (int) (cps.getPosition().x + xDist);
-							y = (int) (cps.getPosition().y + yDist);
-
-							// Make sure its in bounds
-							if (x < upperNode.getLeftBorder() + 5 + controller.getScaleDiv2())
-								x = controller.getScaleDiv2() + upperNode.getLeftBorder() + 5;
-							else if (x > this.getWidth() - controller.getScaleDiv2())
-								x = this.getWidth() - controller.getScaleDiv2();
-							if (y <= controller.getScaleDiv2())
-								y = controller.getScaleDiv2();
-							else if (y > this.getHeight() - controller.getScaleDiv2())
-								y = this.getHeight() - controller.getScaleDiv2();
-
-							cps.setPosition(x, y);
-						}
-					}
-				}
-				repaint();
-			} catch (Exception eex) {
-
-			}
-		}
-
-		// Mark Objects
-		if (doMark) {
-			tempSelected.clear();
-			for (AbstractCpsObject cps : upperNode.getNodes()) {
-				int x1 = sx, x2 = x, y1 = sy, y2 = y;
-
-				if (sx >= x) {
-					x1 = x;
-					x2 = sx;
-				}
-				if (sy >= y) {
-					y1 = y;
-					y2 = sy;
-				}
-				if (x1 <= cps.getPosition().x + model.getScaleDiv2() && y1 <= cps.getPosition().y + model.getScaleDiv2()
-						&& x2 >= cps.getPosition().x && y2 >= cps.getPosition().y) {
-					tempSelected.add(cps);
-
-				}
-			}
-			int count = 0;
-			for (CpsEdge ed : upperNode.getConnections()) {
-				AbstractCpsObject cps = null;
-				if (ed.getA().equals(upperNode)) {
-					cps = ed.getB();
-				} else {
-					cps = ed.getA();
-				}
-
-				int x1 = sx, x2 = x, y1 = sy, y2 = y;
-
-				if (sx >= x) {
-					x1 = x;
-					x2 = sx;
-				}
-				if (sy >= y) {
-					y1 = y;
-					y2 = sy;
-				}
-
-				if (x1 <= upperNode.getLeftBorder() >> 1
-						&& y1 <= (int) (5 + (model.getScale() + scalediv20 + 10) * count) + model.getScaleDiv2()
-						&& x2 >= upperNode.getLeftBorder() >> 1
-						&& y2 >= (int) (5 + (model.getScale() + scalediv20 + 10) * count)) {
-					tempSelected.add(cps);
-
-				}
-				count++;
-			}
-		}
-
-		repaint();
-
-	}
-
-	@Override
-	public void mouseMoved(MouseEvent e) {
-		x = e.getX();
-		y = e.getY();
-
-		// Everytghing for the tooltip :)
-		boolean on = false;
-		for (AbstractCpsObject cps : upperNode.getNodes()) {
-
-			cx = cps.getPosition().x - controller.getScaleDiv2();
-			cy = cps.getPosition().y - controller.getScaleDiv2();
-			if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
-				on = true;
-				toolTipPos.x = cps.getPosition().x - model.getScaleDiv2();
-				toolTipPos.y = cps.getPosition().y + model.getScaleDiv2();
-				toolTipText = cps.getName() + ", " + cps.getId();
-			}
-		}
-		int count = 0;
-		for (CpsEdge ed : upperNode.getConnections()) {
-
-			AbstractCpsObject cps;
-			if (ed.getA().equals(this.upperNode)) {
-				cps = ed.getB();
-			} else {
-				cps = ed.getA();
-			}
-
-			cx = upperNode.getLeftBorder() >> 1;
-			cy = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count);
-			if (x - 50 <= cx && y - 50 <= cy && x >= cx && y >= cy) {
-
-				on = true;
-				toolTipPos.x = cx - 25;
-				toolTipPos.y = cy + 50;
-				toolTipText = cps.getName() + ", " + cps.getId();
-
-			}
-			count++;
-		}
-
-		if (on) {
-			toolTip = true;
-		} else {
-			toolTip = false;
-		}
-		repaint();
-	}
-
-	/**
-	 * Draws or Deletes an Edge.
-	 */
-	private void drawDeleteEdge() {
-		boolean node = true; // new node?
-		boolean newEdge = true;
-		boolean onEdge = true;
-		boolean deleteNode = false;
-		boolean outsideCon = !upperNode.getNodes().contains(tempCps); // Connection
-																		// to
-																		// the
-																		// outside
-		boolean found = false; // dont search for outside connetion if inside
-								// connection is found
-		CpsEdge e = null;
-		for (AbstractCpsObject cps : upperNode.getNodes()) {
-
-			cx = cps.getPosition().x - controller.getScaleDiv2();
-			cy = cps.getPosition().y - controller.getScaleDiv2();
-
-			if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
-					&& cps != tempCps) {
-				found = true;
-				node = false;
-				onEdge = false;
-				for (CpsEdge p : tempCps.getConnections()) {
-					if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
-						newEdge = false;
-						e = p;
-					}
-				}
-				if (!newEdge) {
-					if (outsideCon) {
-						controller.disconnectNodes(e, upperNode);
-					} else {
-						controller.delEdgeUpperNode(e, upperNode);
-					}
-					// Node ohne Edge?
-					if (e.getA().getClass() == CpsNode.class && e.getA().getConnections().isEmpty()) {
-						tempCps = e.getA();
-						deleteNode = true;
-					}
-					if (e.getB().getClass() == CpsNode.class && e.getB().getConnections().isEmpty()) {
-						deleteNode = true;
-					}
-				}
-				if (newEdge) {
-					e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
-					if (outsideCon) {
-						controller.connectNodes(e, upperNode);
-					} else {
-						controller.addEdgeUpperNode(e, upperNode);
-					}
-				}
-			}
-		}
-		if (!found && !outsideCon) {
-			int count = 0;
-			for (CpsEdge ed : upperNode.getConnections()) {
-				AbstractCpsObject cps = null;
-				if (ed.getA().equals(upperNode)) {
-					cps = ed.getB();
-				} else {
-					cps = ed.getA();
-				}
-
-				cx = upperNode.getLeftBorder() >> 1;
-				cy = (int) (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count);
-
-				if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
-						&& cps != tempCps) {
-					outsideCon = true;
-					node = false;
-					onEdge = false;
-					for (CpsEdge p : tempCps.getConnections()) {
-						if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
-							newEdge = false;
-							e = p;
-						}
-					}
-					if (!newEdge) {
-						if (outsideCon) {
-							controller.disconnectNodes(e, upperNode);
-						} else {
-							controller.delEdgeUpperNode(e, upperNode);
-						}
-						// Node ohne Edge?
-						if (e.getA().getClass() == CpsNode.class && e.getA().getConnections().isEmpty()) {
-							tempCps = e.getA();
-							deleteNode = true;
-						}
-						if (e.getB().getClass() == CpsNode.class && e.getB().getConnections().isEmpty()) {
-							deleteNode = true;
-						}
-					}
-					if (newEdge) {
-						CpsEdge edge = new CpsEdge(cps, tempCps, model.getMaxCapacity());
-						if (outsideCon) {
-							controller.connectNodes(edge, upperNode);
-						} else {
-							controller.addEdgeUpperNode(edge, upperNode);
-						}
-					}
-				}
-				count++;
-			}
-		}
-
-		// Edge auf eine Edge gezogen?
-		if (onEdge) {
-			CpsEdge p = mousePositionOnEdge(x, y);
-			if (p != null) {
-				CpsEdge e1 = null;
-				CpsEdge e2 = null;
-
-				node = false;
-
-				CpsNode n = new CpsNode("Node");
-
-				n.setPosition(x, y);
-				controller.addObjUpperNode(n, upperNode);
-
-				AbstractCpsObject r, k;
-				r = p.getA();
-				k = p.getB();
-
-				e = new CpsEdge(n, tempCps, model.getMaxCapacity());
-
-				e1 = new CpsEdge(n, r, model.getMaxCapacity());
-
-				e2 = new CpsEdge(n, k, model.getMaxCapacity());
-
-				controller.delEdgeUpperNode(p, upperNode);
-				if (outsideCon) {
-					controller.connectNodes(e, upperNode);
-				} else {
-					controller.addEdgeUpperNode(e, upperNode);
-				}
-
-				controller.addEdgeUpperNode(e1, upperNode);
-				controller.addEdgeUpperNode(e2, upperNode);
-			}
-		}
-
-		// ins leere Gedragged
-		if (node && x > upperNode.getLeftBorder()) {
-			CpsNode n = new CpsNode("Node");
-
-			n.setPosition(x, y);
-			controller.addObjUpperNode(n, upperNode);
-
-			e = new CpsEdge(n, tempCps, model.getMaxCapacity());
-
-			if (outsideCon) {
-				controller.connectNodes(e, upperNode);
-			} else {
-				controller.addEdgeUpperNode(e, upperNode);
-			}
-		}
-
-		// Wenn ein Node ohne Connections da ist
-		if (deleteNode) {
-			controller.delCanvasObject(tempCps, true);
-			tempCps = null;
-		}
-	}
-
-	/**
-	 * Checks if the mouse is on an Edge.
-	 * 
-	 * @param x
-	 *            Position of the Mouse
-	 * @param y
-	 *            Position of the Mouse
-	 * 
-	 * @return CpsEdge the Mouse is on, null if the mouse is not on an Edge
-	 */
-	public CpsEdge mousePositionOnEdge(int x, int y) {
-		x += controller.getScaleDiv2();
-		y += controller.getScaleDiv2();
-		int lx, ly, hx, hy;
-		for (CpsEdge p : upperNode.getNodeEdges()) {
-			Line2D l = new Line2D.Float(p.getA().getPosition().x, p.getA().getPosition().y, p.getB().getPosition().x,
-					p.getB().getPosition().y);
-			if (p.getA().getPosition().x > p.getB().getPosition().x) {
-				hx = p.getA().getPosition().x + model.getScaleDiv2() + 7;
-				lx = p.getB().getPosition().x + model.getScaleDiv2() - 7;
-			} else {
-				lx = p.getA().getPosition().x + model.getScaleDiv2() - 7;
-				hx = p.getB().getPosition().x + model.getScaleDiv2() + 7;
-			}
-			if (p.getA().getPosition().y > p.getB().getPosition().y) {
-				hy = p.getA().getPosition().y + model.getScaleDiv2() + 7;
-				ly = p.getB().getPosition().y + model.getScaleDiv2() - 7;
-			} else {
-				ly = p.getA().getPosition().y + model.getScaleDiv2() - 7;
-				hy = p.getB().getPosition().y + model.getScaleDiv2() + 7;
-			}
-
-			// distance from a point to a line and between both Objects
-			if (l.ptLineDistSq(x - model.getScaleDiv2(), y - model.getScaleDiv2()) < 20 && x > lx && x < hx && y > ly
-					&& y < hy) {
-				return p;
-			}
-		}
-
-		// edge to outside connection
-
-		int count = 0;
-		for (CpsEdge e : upperNode.getConnections()) {
-			AbstractCpsObject cps;
-			if (e.getA().equals(this.upperNode)) {
-				cps = e.getB();
-			} else {
-				cps = e.getA();
-			}
-			for (CpsEdge p : cps.getConnections()) {
-				AbstractCpsObject obj = null;
-				boolean doTest = false;
-				if (upperNode.getNodes().contains(p.getA())) {
-					obj = p.getA();
-					doTest = true;
-				} else if (upperNode.getNodes().contains(p.getB())) {
-					obj = p.getB();
-					doTest = true;
-				}
-				// g2.drawImage(img, (borderPos >> 1) - 25, (int) (scalediv20 +
-				// 5 + (50 + scalediv20 + 10) * count), 50, 50, null);
-				if (doTest) {
-					Line2D l = new Line2D.Float((upperNode.getLeftBorder() >> 1) - 25,
-							(int) (scalediv20 + 5 + 25 + (50 + scalediv20 + 10) * count), obj.getPosition().x,
-							obj.getPosition().y);
-					if ((upperNode.getLeftBorder() >> 1) > obj.getPosition().x) {
-						hx = (upperNode.getLeftBorder() >> 1) - 25 + model.getScaleDiv2() + 7;
-						lx = obj.getPosition().x + model.getScaleDiv2() - 7;
-					} else {
-						lx = (upperNode.getLeftBorder() >> 1) - 25 + model.getScaleDiv2() - 7;
-						hx = obj.getPosition().x + model.getScaleDiv2() + 7;
-					}
-					if ((int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) > obj.getPosition().y) {
-						hy = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + model.getScaleDiv2() + 7;
-						ly = obj.getPosition().y + model.getScaleDiv2() - 7;
-					} else {
-						ly = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + model.getScaleDiv2() - 7;
-						hy = obj.getPosition().y + model.getScaleDiv2() + 7;
-					}
-
-					// distance from a point to a line and between both Objects
-					if (l.ptLineDistSq(x - model.getScaleDiv2(), y - model.getScaleDiv2()) < 20 && x > lx && x < hx
-							&& y > ly && y < hy) {
-						return p;
-					}
-				}
-			}
-			count++;
-		}
-		return null;
-	}
-
-	/**
-	 * Checks if a double click was made.
-	 * 
-	 * @return true if doublecklick, false if not
-	 */
-	private boolean doubleClick() {
-		if (click) {
-			click = false;
-			return true;
-		} else {
-			click = true;
-			Timer t = new Timer("doubleclickTimer", false);
-			t.schedule(new TimerTask() {
-				@Override
-				public void run() {
-					click = false;
-				}
-			}, 500);
-		}
-		return false;
-	}
-
-	/**
-	 * sets the Edge Capacity.
-	 * 
-	 * @param cap
-	 *            capacity
-	 */
-	public void setEdgeCapacity(float cap) {
-		controller.setMaxCapacity(cap);
-	}
-
-	/**
-	 * Set if Information should be shown.
-	 * 
-	 * @param connection
-	 *            boolean for conecction
-	 * @param object
-	 *            boolean for objects
-	 */
-	public void setShowedInformation(boolean connection, boolean object, boolean nodeOfnode) {
-		showedInformation[0] = connection;
-		showedInformation[1] = object;
-		showedInformation[4] = nodeOfnode;
-	}
-
-	/**
-	 * copies a set of given informations
-	 * 
-	 * @param informations
-	 */
-	public void setShowedInformation(boolean[] informations) {
-		showedInformation = informations;
-	}
-
-	/**
-	 * Returns if Information should be shown.
-	 * 
-	 * @return Array of boolean [0] = connection, [1] = objects
-	 */
-	public boolean[] getShowedInformation() {
-		return showedInformation;
-	}
-
-	/**
-	 * Set the Background Image;
-	 * 
-	 * @param imagePath
-	 *            Image Path
-	 * @param mode
-	 *            Image Mode
-	 * @param width
-	 *            Image custom width
-	 * @param height
-	 *            Image custom height
-	 */
-	public void setBackgroundImage(String imagePath, int mode, int width, int height) {
-		upperNode.setBackgroundImage(imagePath, mode, width, height);
-	}
-
-	/**
-	 * set tooltIp
-	 * 
-	 * @param bool
-	 */
-	public void setToolTip(boolean bool) {
-		this.toolTip = bool;
-	}
-
-	/**
-	 * Set the Mouse Position on the UpperNodeCanvas;
-	 * 
-	 * @param x
-	 * @param y
-	 */
-	public void setXY(int x, int y) {
-		this.x = x;
-		this.y = y;
-	}
+public class UpperNodeCanvas extends AbstractCanvas implements MouseListener, MouseMotionListener {
+
+    private static final long serialVersionUID = 1L;
+    // The UpperNode
+    public CpsUpperNode upperNode;
+    // Path
+    protected String path;
+    int code;
+    private JLabel breadCrumb;
+
+
+    /**
+     * Constructor.
+     *
+     * @param mod       the Model
+     * @param control   the Controller
+     * @param unitGraph
+     */
+    UpperNodeCanvas(Model mod, Control control, UnitGraph unitGraph, CpsUpperNode UpperNode, String parentPath) {
+        toolTip = false;
+
+        this.controller = control;
+        this.model = mod;
+        this.upperNode = UpperNode;
+        this.code = UpperNode.hashCode();
+        this.path = parentPath + upperNode.getName();
+        this.breadCrumb = new JLabel(path);
+        // this.add(breadCrumb);
+        scalediv20 = model.getScale() / 20;
+
+        // Cps objecte aus dem border links schieben
+        upperNode.setLeftBorder((int) (50 + scalediv20 + scalediv20 + 10));
+        for (AbstractCpsObject cps : upperNode.getNodes()) {
+            if (cps.getPosition().x < model.getScaleDiv2() + upperNode.getLeftBorder() + 5) {
+                cps.setPosition(
+                        new Position(upperNode.getLeftBorder() + 5 + model.getScaleDiv2(), cps.getPosition().y));
+            }
+        }
+
+        showedInformation[0] = true;
+        showedInformation[1] = true;
+        showedInformation[4] = true;
+
+        popmenu.add(itemCut);
+        popmenu.add(itemCopy);
+        popmenu.add(itemPaste);
+        popmenu.add(itemDelete);
+        popmenu.addSeparator();
+        popmenu.add(itemGroup);
+        popmenu.add(itemUngroup);
+        popmenu.add(itemTrack);
+        popmenu.add(itemUntrack);
+
+        itemDelete.setEnabled(false);
+        itemCut.setEnabled(false);
+        itemCopy.setEnabled(false);
+        itemPaste.setEnabled(true);
+        itemGroup.setEnabled(false);
+        itemUngroup.setEnabled(false);
+        itemTrack.setEnabled(false);
+        itemUntrack.setEnabled(false);
+        updCon = new UpdateController(model, controller);
+
+        itemGroup.addActionListener(actionEvent -> {
+            // calculate uppernode pos (taken from the controller)
+            unPos = new Position(0, 0);
+            animCps = new ArrayList<>();
+            for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
+                animCps.add(cps); // add to animation Cps ArrayList
+                unPos.x += cps.getPosition().x;
+                unPos.y += cps.getPosition().y;
+            }
+            unPos.x /= animCps.size();
+            unPos.y /= animCps.size();
+
+            // save old Position
+            savePos = new ArrayList<>();
+            for (int i = 0; i < animCps.size(); i++) {
+                savePos.add(new Position(0, 0));
+                savePos.get(i).x = animCps.get(i).getPosition().x;
+                savePos.get(i).y = animCps.get(i).getPosition().y;
+            }
+
+            animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
+                if (animDuration - animDelay > 0 && animCps.size() > 1) {
+                    for (AbstractCpsObject currentAnimCps : animCps) {
+                        double x1 = currentAnimCps.getPosition().x - unPos.x;
+                        double y1 = currentAnimCps.getPosition().y - unPos.y;
+                        currentAnimCps.getPosition().x -= x1 / animSteps;
+                        currentAnimCps.getPosition().y -= y1 / animSteps;
+                    }
+                    repaint();
+                    animDuration -= animDelay;
+                    animSteps--;
+                } else {
+                    animDuration = ANIMTIME;
+                    animSteps = animDuration / animDelay;
+                    animT.stop();
+                    for (int i = 0; i < animCps.size(); i++) {
+                        animCps.get(i).getPosition().x = savePos.get(i).x;
+                        animCps.get(i).getPosition().y = savePos.get(i).y;
+                    }
+                    controller.addUpperNode("NodeOfNode", upperNode, model.getSelectedCpsObjects());
+                    controller.calculateStateForCurrentTimeStep();
+                    repaint();
+                }
+            });
+            animT.start();
+        });
+
+        itemUngroup.addActionListener(actionEvent -> {
+            // save old Position
+            JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent().getParent();
+            for (int i = 4; i < tabbedPane.getTabCount(); i++) {
+                if (((UpperNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
+                        .getComponent(0)).upperNode.getId() == tempCps.getId()) {
+                    tabbedPane.remove(i);
+                    break;
+                }
+            }
+
+            savePos = new ArrayList<>();
+            animCps = ((CpsUpperNode) tempCps).getNodes();
+            controller.delUpperNode((CpsUpperNode) tempCps, upperNode);
+
+            for (int i = 0; i < animCps.size(); i++) {
+                savePos.add(new Position(0, 0));
+                savePos.get(i).x = animCps.get(i).getPosition().x;
+                savePos.get(i).y = animCps.get(i).getPosition().y;
+            }
+            for (AbstractCpsObject cps : animCps) {
+                int x = tempCps.getPosition().x;
+                int y = tempCps.getPosition().y;
+
+                cps.setPosition(new Position(x, y));
+            }
+
+            animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
+                if (animDuration - animDelay >= 0) {
+                    for (int i = 0; i < animCps.size(); i++) {
+                        double x1 = animCps.get(i).getPosition().x - savePos.get(i).x;
+                        double y1 = animCps.get(i).getPosition().y - savePos.get(i).y;
+                        animCps.get(i).getPosition().x -= x1 / animSteps;
+                        animCps.get(i).getPosition().y -= y1 / animSteps;
+                    }
+                    repaint();
+                    animDuration -= animDelay;
+                    animSteps--;
+                } else {
+                    animDuration = ANIMTIME;
+                    animSteps = animDuration / animDelay;
+                    animT.stop();
+                    for (int i = 0; i < animCps.size(); i++) {
+                        animCps.get(i).getPosition().x = savePos.get(i).x;
+                        animCps.get(i).getPosition().y = savePos.get(i).y;
+                    }
+
+                    controller.calculateStateForCurrentTimeStep();
+                    repaint();
+                }
+            });
+            animT.start();
+        });
+
+        itemTrack.addActionListener(actionEvent -> {
+            for (AbstractCpsObject o : model.getSelectedCpsObjects()) {
+                if (o instanceof HolonObject) {
+                    boolean found = false;
+                    if (controller.getTrackingObj() != null) {
+                        for (AbstractCpsObject obj : controller.getTrackingObj()) {
+                            if (obj instanceof HolonObject) {
+                                if (obj.getId() == o.getId()) {
+                                    found = true;
+                                }
+                            }
+                        }
+                    }
+                    if (!found) {
+                        controller.addTrackingObj(o);
+                        ((HolonObject) o).updateTrackingInfo();
+                    }
+                    if (model.getShowConsoleLog()) {
+                        controller.addTextToConsole("Tracking: ", Color.BLACK, 12, false, false, false);
+                        controller.addTextToConsole("" + o.getName(), Color.BLUE, 12, true, false, false);
+                        controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
+                        controller.addTextToConsole("" + o.getId(), Color.RED, 12, true, false, true);
+                    }
+                }
+            }
+        });
+
+        itemUntrack.addActionListener(actionEvent -> {
+            for (AbstractCpsObject o : model.getSelectedCpsObjects()) {
+                if (o instanceof HolonObject) {
+                    boolean found = false;
+                    if (controller.getTrackingObj() != null) {
+                        for (AbstractCpsObject obj : controller.getTrackingObj()) {
+                            if (obj instanceof HolonObject) {
+                                if (obj.getId() == o.getId()) {
+                                    found = true;
+                                }
+                            }
+                        }
+                    }
+                    if (found) {
+                        // Removed from tracking array and tracking
+                        // information reseted
+                        controller.removeTrackingObj(o);
+                        ((HolonObject) o).setTrackingProd(new float[100]);
+                        ((HolonObject) o).setTrackingCons(new float[100]);
+                    }
+                }
+            }
+            System.out.println(controller.getTrackingObj());
+        });
+
+        itemDelete.addActionListener(actionEvent -> {
+            // Remove the selected Object objects
+            for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
+                if (upperNode.getNodes().contains(cps)) {
+                    controller.delObjUpperNode(cps, upperNode);
+                    // Removes the object from the tracked objects, in case
+                    // it was tracked
+                    controller.removeTrackingObj(cps);
+                    // Remove UpperNodeTab if UpperNode deleted
+                    if (cps instanceof CpsUpperNode) {
+                        JSplitPane tempSplit = (JSplitPane) getParent().getParent().getParent().getParent();
+                        JTabbedPane tabbedPane;
+                        JTabbedPane tabbedPane2;
+                        // if SplitView is activated
+                        if (tempSplit.getLeftComponent() instanceof JTabbedPane
+                                && tempSplit.getRightComponent() instanceof JTabbedPane) {
+                            tabbedPane = (JTabbedPane) tempSplit.getLeftComponent();
+                            tabbedPane2 = (JTabbedPane) tempSplit.getRightComponent();
+                        } else {
+                            tabbedPane = (JTabbedPane) tempSplit.getLeftComponent();
+                            tabbedPane2 = null;
+                        }
+                        // Look if the uppernode is open in a Tab
+                        for (int i = 4; i < tabbedPane.getTabCount(); i++) {
+
+                            if (tabbedPane.getComponentAt(i) != null &&
+                                    ((UpperNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
+                                            .getComponent(0)).upperNode.getId() == cps.getId()) {
+                                ((ButtonTabComponent) tabbedPane.getTabComponentAt(i)).removeTabs();
+                                break;
+                            }
+                        }
+                        // If SplitView is on and the view on
+                        // tabbedPane2 is the deleted upperNode
+                        try {
+                            if (tabbedPane2 != null
+                                    && ((UpperNodeCanvas) ((JScrollPane) tabbedPane2.getSelectedComponent())
+                                    .getViewport().getComponent(0)).upperNode.getId() == cps.getId()) {
+                                ((ButtonTabComponent) tabbedPane.getTabComponentAt(tabbedPane2.getSelectedIndex()))
+                                        .removeTabs();
+                            }
+                        } catch (Exception e2) {
+                        }
+
+                    }
+                }
+            }
+            toolTip = false;
+            model.getSelectedCpsObjects().clear();
+            tempCps = null;
+            repaint();
+        });
+
+        itemCut.addActionListener(actionEvent -> {
+            controller.cut(upperNode);
+            itemPaste.setEnabled(true);
+            repaint();
+        });
+
+        itemCopy.addActionListener(actionEvent -> {
+            controller.copy(upperNode);
+            itemPaste.setEnabled(true);
+            repaint();
+        });
+
+        itemPaste.addActionListener(actionEvent -> {
+            try {
+                controller.paste(upperNode, mousePosition);
+                unitGraph.update(model.getSelectedCpsObjects());
+            } catch (JsonParseException | UnsupportedFlavorException | IOException e1) {
+                JLabel message = new JLabel("The Clipboard information cannot be pastet into Application.");
+                JOptionPane.showMessageDialog(null, message, "", JOptionPane.ERROR_MESSAGE);
+            }
+            repaint();
+        });
+
+        this.addMouseListener(this);
+        this.addMouseMotionListener(this);
+    }
+
+    /**
+     * Paints all Components on the Canvas.
+     *
+     * @param g Graphics
+     */
+    public void paintComponent(Graphics g) {
+        String maxCap = null;
+        super.paintComponent(g);
+        ((JScrollPane) this.getParent().getParent()).setColumnHeaderView(breadCrumb);
+        // Rendering
+        g2 = (Graphics2D) g;
+        RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+        g2.setRenderingHints(rh);
+
+        // Paint the Background
+        if (!upperNode.getImagePath().isEmpty()) {
+            img = new ImageIcon(upperNode.getImagePath()).getImage();
+            switch (upperNode.getBackgroundMode()) {
+                case BackgroundPopUp.IMAGE_PIXELS:
+                    g2.drawImage(img, upperNode.getLeftBorder(), 0, img.getWidth(null), img.getHeight(null), null);
+                    break;
+                case BackgroundPopUp.STRETCHED:
+                    g2.drawImage(img, upperNode.getLeftBorder(), 0, model.getCanvasX(), model.getCanvasY(), null);
+                    break;
+                case BackgroundPopUp.CUSTOM:
+                    g2.drawImage(img, upperNode.getLeftBorder(), 0, upperNode.getImageWidht(), upperNode.getImageHeight(),
+                            null);
+                    break;
+                default:
+                    break;
+            }
+        }
+
+        // Draw Left Border
+        g2.setColor(new Color(230, 230, 230));
+        g2.fillRect(0, 0, upperNode.getLeftBorder(), this.getHeight());
+        g2.setColor(Color.BLACK);
+        g2.drawLine(0, 0, this.getWidth(), 0);
+
+        // Test SubNet Coloring
+        int i = 0;
+        for (SubNet s : controller.getSimManager().getSubNets()) {
+
+            if (model.getSubNetColors().size() - 1 < i) {
+                controller.addSubNetColor(new Color((int) (Math.random() * 255), (int) (Math.random() * 255),
+                        (int) (Math.random() * 255)));
+            }
+
+            for (HolonObject cps : s.getObjects()) {
+                cps.setBorderColor(model.getSubNetColors().get(i));
+            }
+            i++;
+        }
+
+        // drawEdges that is being dragged
+        if (drawEdge) {
+            g2.setColor(Color.BLACK);
+            g2.setStroke(new BasicStroke(2));
+
+            // If TempCps is an outside Object
+            if (!upperNode.getNodes().contains(tempCps)) {
+                int count = 0;
+                for (CpsEdge e : upperNode.getConnections()) {
+                    if (e.getA().equals(tempCps)) {
+                        g2.drawLine(upperNode.getLeftBorder() >> 1, (int) (model.getScaleDiv2() + scalediv20 + 5
+                                + (model.getScale() + scalediv20 + 10) * count), x, y);
+                    } else if (e.getB().equals(tempCps)) {
+                        g2.drawLine(upperNode.getLeftBorder() >> 1, (int) (model.getScaleDiv2() + scalediv20 + 5
+                                + (model.getScale() + scalediv20 + 10) * count), x, y);
+                    }
+                    count++;
+                }
+            } else {
+                g2.drawLine(tempCps.getPosition().x, tempCps.getPosition().y, x, y);
+            }
+        }
+        // draw Edges
+        for (CpsEdge con : upperNode.getNodeEdges()) {
+            maxCap = paintEdge(con, maxCap);
+        }
+
+        // Objects connected to upperNode
+        int count = 0;
+        for (CpsEdge e : upperNode.getConnections()) {
+            AbstractCpsObject cps;
+            if (e.getA().equals(this.upperNode)) {
+                cps = e.getB();
+            } else {
+                cps = e.getA();
+            }
+            // Show and Highlight
+            if (model.getSelectedCpsObjects().contains(cps) || showedInformation[4]) {
+                for (CpsEdge ed : cps.getConnections()) {
+                    AbstractCpsObject obj = null;
+                    if (upperNode.getNodes().contains(ed.getA())) {
+                        obj = ed.getA();
+                    } else if (upperNode.getNodes().contains(ed.getB())) {
+                        obj = ed.getB();
+                    }
+                    if (obj != null) {
+                        if (ed.getConnected() == 0) {
+
+                            setEdgeState(ed);
+
+                            if (ed.getA().getId() == model.getSelectedObjectID()
+                                    || ed.getB().getId() == model.getSelectedObjectID() || edgeHighlight == ed)
+                                g2.setColor(Color.BLUE);
+                        } else {
+                            g2.setColor(Color.DARK_GRAY);
+                            g2.setStroke(new BasicStroke(2));
+                        }
+                        g2.drawLine(obj.getPosition().x, obj.getPosition().y, (upperNode.getLeftBorder() >> 1),
+                                (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + 25);
+                        if (showedInformation[0]) {
+
+                            maxCap = setCapacityString(ed, maxCap);
+
+                            if (ed.getConnected() == 0 || ed.getConnected() == 1) {
+                                g2.drawString(ed.getFlow() + "/" + maxCap,
+                                        (obj.getPosition().x + (upperNode.getLeftBorder() >> 1)) / 2,
+                                        (obj.getPosition().y + (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count)
+                                                + 25) / 2);
+                            } else {
+                                g2.drawString("not connected",
+                                        (obj.getPosition().x + (upperNode.getLeftBorder() >> 1)) / 2,
+                                        (obj.getPosition().y + (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count)
+                                                + 25) / 2);
+                            }
+                        }
+                    }
+                }
+            }
+
+            // Border Highlighting
+            if (showedInformation[3]) {
+                g2.setColor(cps.getBorderColor());
+                if (g2.getColor() != Color.WHITE) {
+                    g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20) - 3,
+                            (int) (scalediv20 + 5 + (25 + scalediv20 + 10) * count - scalediv20) - 3,
+                            (int) (50 + ((scalediv20 + 3) * 2)), (int) (50 + ((scalediv20 + 3) * 2)));
+                }
+            }
+
+            // node image
+            if (cps instanceof CpsNode && (cps == tempCps || model.getSelectedCpsObject() == cps
+                    || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps))) {
+                img = new ImageIcon(this.getClass().getResource("/Images/node_selected.png")).getImage();
+            } else {
+                if (cps instanceof HolonSwitch) {
+                    if (((HolonSwitch) cps).getActiveAt()[model.getCurIteration()]) {
+                        ((HolonSwitch) cps).setAutoState(true);
+                    } else {
+                        ((HolonSwitch) cps).setAutoState(false);
+                    }
+                }
+                // Highlighting
+                if ((cps == tempCps && model.getSelectedCpsObjects().size() == 0 && tempSelected.size() == 0)
+                        || model.getSelectedCpsObjects().contains(cps) || tempSelected.contains(cps)) {
+                    g2.setColor(Color.BLUE);
+                    g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20),
+                            (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count - scalediv20),
+                            (int) (50 + (scalediv20 * 2)), (int) (50 + (scalediv20 * 2)));
+                } else if (cps instanceof HolonObject) {
+                    g2.setColor(((HolonObject) cps).getColor());
+
+                    g2.fillRect((int) ((upperNode.getLeftBorder() >> 1) - 25 - scalediv20),
+                            (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count - scalediv20),
+                            (int) (50 + (scalediv20 * 2)), (int) (50 + (scalediv20 * 2)));
+                }
+                // draw image
+                File checkPath = new File(cps.getImage());
+                if (checkPath.exists()) {
+                    img = new ImageIcon(cps.getImage()).getImage();
+                } else {
+                    img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage();
+                }
+            }
+            g2.drawImage(img, (upperNode.getLeftBorder() >> 1) - 25,
+                    (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count), 50, 50, null);
+            count++;
+        }
+        // Highlighted Edge
+        if (model.getSelectedObjectID() > 0 || !model.getSelectedCpsObjects().isEmpty() || !tempSelected.isEmpty()) {
+            g2.setColor(Color.BLUE);
+            for (CpsEdge con : upperNode.getNodeEdges()) {
+                if (con.getFlow() <= con.getCapacity()) {
+                    g2.setStroke(new BasicStroke(Math.min((con.getFlow() / con.getCapacity() * 3) + 1, 4)));
+                } else {
+                    g2.setStroke(new BasicStroke(2));
+                }
+
+                maxCap = drawEdgeLine(con, maxCap);
+            }
+        } else if (edgeHighlight != null) {
+            g2.setColor(Color.BLUE);
+            if (edgeHighlight.getFlow() <= edgeHighlight.getCapacity()) {
+                g2.setStroke(
+                        new BasicStroke(Math.min((edgeHighlight.getFlow() / edgeHighlight.getCapacity() * 3) + 1, 4)));
+            } else {
+                g2.setStroke(new BasicStroke(2));
+            }
+            if (upperNode.getNodeEdges().contains(edgeHighlight)) {
+                g2.drawLine(edgeHighlight.getA().getPosition().x, edgeHighlight.getA().getPosition().y,
+                        edgeHighlight.getB().getPosition().x, edgeHighlight.getB().getPosition().y);
+
+                maxCap = setCapacityString(edgeHighlight, maxCap);
+
+                if (showedInformation[0]) {
+                    g2.drawString(edgeHighlight.getFlow() + "/" + maxCap,
+                            (edgeHighlight.getA().getPosition().x + edgeHighlight.getB().getPosition().x) / 2,
+                            (edgeHighlight.getA().getPosition().y + edgeHighlight.getB().getPosition().y) / 2);
+                }
+            }
+        }
+
+        // Objects in upper node
+        for (AbstractCpsObject cps : upperNode.getNodes()) {
+            // Border Highlighting
+            if (showedInformation[3]) {
+                g2.setColor(cps.getBorderColor());
+                if (g2.getColor() != Color.WHITE) {
+                    g2.fillRect((int) (cps.getPosition().x - controller.getScaleDiv2() - scalediv20 - 3),
+                            (int) (cps.getPosition().y - model.getScaleDiv2() - scalediv20 - 3),
+                            (int) (controller.getScale() + ((scalediv20 + 3) * 2)),
+                            (int) (controller.getScale() + ((scalediv20 + 3) * 2)));
+                }
+            }
+
+            setEdgePictureAndHighlighting(cps);
+
+            g2.drawImage(img, cps.getPosition().x - model.getScaleDiv2(), cps.getPosition().y - model.getScaleDiv2(),
+                    controller.getScale(), controller.getScale(), null);
+        }
+
+        // Dragged marker Highlighting
+        g2.setStroke(new BasicStroke(1));
+        if (doMark) {
+            g2.setColor(Color.BLACK);
+            drawMarker();
+        }
+
+        // Border Line
+        g2.setColor(Color.BLACK);
+        g2.drawLine(upperNode.getLeftBorder(), 0, upperNode.getLeftBorder(), this.getHeight());
+
+        // Tooltip
+        showTooltip(g);
+    }
+
+    @Override
+    public void mouseClicked(MouseEvent e) {
+        triggerUpdateController();
+    }
+
+    @Override
+    public void mouseEntered(MouseEvent e) {
+    }
+
+    @Override
+    public void mouseExited(MouseEvent e) {
+    }
+
+    @Override
+    public void mousePressed(MouseEvent e) {
+        tempCps = null;
+        dataSelected = null;
+        edgeHighlight = null;
+        controller.setSelecteEdge(null);
+        controller.setSelectedObjectID(-1);
+        // Object Selection
+
+        // Erase old data in the PropertyTable
+        if (model.getPropertyTable().getRowCount() > 0) {
+            for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
+                model.getPropertyTable().removeRow(i);
+            }
+        }
+
+        if (e.getX() > upperNode.getLeftBorder()) {
+            for (AbstractCpsObject cps : upperNode.getNodes()) {
+                cx = cps.getPosition().x - model.getScaleDiv2();
+                cy = cps.getPosition().y - model.getScaleDiv2();
+                if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
+                    tempCps = cps;
+
+                    setConsoleTextAfterSelect(cps);
+
+                    dragging = true;
+                    if (e.isControlDown() && tempCps != null) {
+                        if (model.getSelectedCpsObjects().contains(tempCps)) {
+                            controller.deleteSelectedObject(tempCps);
+                        } else {
+                            controller.addSelectedObject(tempCps);
+                        }
+                    }
+
+                    // If drawing an Edge (CTRL down)
+                    if (tempCps.getClass() == HolonObject.class) {
+                        HolonObject tempObj = ((HolonObject) tempCps);
+                        dataSelected = tempObj.getElements();
+                    }
+                    if (e.isShiftDown()) {
+                        drawEdge = true;
+                        dragging = false;
+                    }
+                    break;
+                }
+            }
+        } else {
+            // look for objects connected to uppernode
+            int count = 0;
+            for (CpsEdge ed : upperNode.getConnections()) {
+                AbstractCpsObject cps;
+                if (ed.getA().equals(this.upperNode)) {
+                    cps = ed.getB();
+                } else {
+                    cps = ed.getA();
+                }
+                if (x - controller.getScale() <= ((upperNode.getLeftBorder() >> 1) - model.getScaleDiv2())
+                        && y - controller.getScale() <= (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count)
+                        && x >= (upperNode.getLeftBorder() >> 1) - model.getScaleDiv2()
+                        && y >= (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count)) {
+                    tempCps = cps;
+                    if (model.getShowConsoleLog()) {
+                        controller.addTextToConsole("Selected: ", Color.BLACK, 12, false, false, false);
+                        controller.addTextToConsole("" + cps.getName(), Color.BLUE, 12, true, false, false);
+                        controller.addTextToConsole(", ID:", Color.BLACK, 12, false, false, false);
+                        controller.addTextToConsole("" + cps.getId(), Color.RED, 12, true, false, true);
+                        controller.setSelectedObjectID(tempCps.getId());
+                    }
+                    // If drawing an Edge (CTRL down)
+                    if (tempCps.getClass() == HolonObject.class) {
+                        HolonObject tempObj = ((HolonObject) tempCps);
+                        dataSelected = tempObj.getElements();
+                    }
+                    if (e.isShiftDown()) {
+                        drawEdge = true;
+                    }
+                }
+                count++;
+            }
+        }
+
+        // Selection of CpsObject
+        // model.setSelectedCpsObject(tempCps);
+
+        // Edge Selection
+        if (e.getButton() == MouseEvent.BUTTON1) {
+            if (tempCps == null) {
+                edgeHighlight = mousePositionOnEdge(x, y);
+                controller.setSelecteEdge(edgeHighlight);
+                controller.setSelectedObjectID(0);
+                if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
+                    model.getSelectedCpsObjects().clear();
+                }
+                updCon.deleteRows(model.getMultiTable());
+                updCon.deleteRows(model.getSingleTable());
+            }
+
+            if (edgeHighlight == null && tempCps == null) {
+                sx = e.getX();
+                sy = e.getY();
+                doMark = true;
+            }
+            // System.out.println("Selected Objects");
+            // for (AbstractCpsObject temp : model.getSelectedCpsObjects()) {
+            // System.out.println(temp.getName() + " " + temp.getID());
+            // }
+            repaint();
+        }
+    }
+
+    @Override
+    public void mouseReleased(MouseEvent e) {
+        x = e.getX();
+        y = e.getY();
+        dragging = false;
+        if (model.getSelectedCpsObjects().size() > 1) {
+            model.getTableHolonElement().setModel(model.getMultiTable());
+        } else if (model.getSelectedCpsObjects().size() == 1) {
+            model.getTableHolonElement().setModel(model.getSingleTable());
+        }
+
+        if (drawEdge) {
+            drawEdge = false;
+            drawDeleteEdge();
+        }
+
+        if (dragged) {
+            try {
+                controller.autoSave();
+            } catch (IOException ex) {
+                ex.printStackTrace();
+            }
+        }
+
+        if (!e.isControlDown() && !dragged && tempCps != null && MouseEvent.BUTTON3 != e.getButton()) {
+            model.getSelectedCpsObjects().clear();
+            controller.addSelectedObject(tempCps);
+        }
+
+        dragged = false;
+
+        // Rightclick List
+        setRightClickMenu(e);
+
+        markObjects();
+
+        if (doubleClick() && tempCps != null && tempCps instanceof HolonSwitch) {
+            ((HolonSwitch) tempCps).switchState();
+        }
+
+        controller.calculateStateForTimeStep(model.getCurIteration());
+        triggerUpdateController();
+        repaint();
+
+    }
+
+    @Override
+    public void mouseDragged(MouseEvent e) {
+        // If Edge is drawn
+        x = e.getX();
+        y = e.getY();
+        if (!model.getSelectedCpsObjects().contains(tempCps) && !doMark) {
+            model.getSelectedCpsObjects().clear();
+            if (tempCps != null) {
+                controller.addSelectedObject(tempCps);
+            }
+        }
+        if (dragging) {
+            try {
+                // tempCps in the upperNode? else its a connected Object from
+                // outside
+                if (upperNode.getNodes().contains(tempCps)) {
+                    dragged = true;
+                    float xDist, yDist; // Distance
+
+                    x = e.getX();
+                    y = e.getY();
+
+                    // Make sure its in bounds
+                    if (e.getX() < controller.getScaleDiv2() + upperNode.getLeftBorder() + 5)
+                        x = controller.getScaleDiv2() + upperNode.getLeftBorder() + 5;
+                    else if (e.getX() > this.getWidth() - controller.getScaleDiv2())
+                        x = this.getWidth() - controller.getScaleDiv2();
+                    if (e.getY() < controller.getScaleDiv2())
+                        y = controller.getScaleDiv2();
+                    else if (e.getY() > this.getHeight() - controller.getScaleDiv2())
+                        y = this.getHeight() - controller.getScaleDiv2();
+
+                    // Distance
+                    xDist = x - tempCps.getPosition().x;
+                    yDist = y - tempCps.getPosition().y;
+
+                    tempCps.setPosition(x, y); // Drag Position
+
+                    // TipText Position and name
+                    toolTip = true;
+                    toolTipText = tempCps.getName() + ", " + tempCps.getId();
+                    toolTipPos.x = tempCps.getPosition().x - model.getScaleDiv2();
+                    toolTipPos.y = tempCps.getPosition().y + model.getScaleDiv2();
+
+                    // All Selected Objects
+                    for (AbstractCpsObject cps : model.getSelectedCpsObjects()) {
+                        if (cps != tempCps) {
+                            x = (int) (cps.getPosition().x + xDist);
+                            y = (int) (cps.getPosition().y + yDist);
+
+                            // Make sure its in bounds
+                            if (x < upperNode.getLeftBorder() + 5 + controller.getScaleDiv2())
+                                x = controller.getScaleDiv2() + upperNode.getLeftBorder() + 5;
+                            else if (x > this.getWidth() - controller.getScaleDiv2())
+                                x = this.getWidth() - controller.getScaleDiv2();
+                            if (y <= controller.getScaleDiv2())
+                                y = controller.getScaleDiv2();
+                            else if (y > this.getHeight() - controller.getScaleDiv2())
+                                y = this.getHeight() - controller.getScaleDiv2();
+
+                            cps.setPosition(x, y);
+                        }
+                    }
+                }
+                repaint();
+            } catch (Exception eex) {
+
+            }
+        }
+
+        // Mark Objects
+        if (doMark) {
+            tempSelected.clear();
+            for (AbstractCpsObject cps : upperNode.getNodes()) {
+                int x1 = sx, x2 = x, y1 = sy, y2 = y;
+
+                if (sx >= x) {
+                    x1 = x;
+                    x2 = sx;
+                }
+                if (sy >= y) {
+                    y1 = y;
+                    y2 = sy;
+                }
+                if (x1 <= cps.getPosition().x + model.getScaleDiv2() && y1 <= cps.getPosition().y + model.getScaleDiv2()
+                        && x2 >= cps.getPosition().x && y2 >= cps.getPosition().y) {
+                    tempSelected.add(cps);
+
+                }
+            }
+            int count = 0;
+            for (CpsEdge ed : upperNode.getConnections()) {
+                AbstractCpsObject cps;
+                if (ed.getA().equals(upperNode)) {
+                    cps = ed.getB();
+                } else {
+                    cps = ed.getA();
+                }
+
+                int x1 = sx, x2 = x, y1 = sy, y2 = y;
+
+                if (sx >= x) {
+                    x1 = x;
+                    x2 = sx;
+                }
+                if (sy >= y) {
+                    y1 = y;
+                    y2 = sy;
+                }
+
+                if (x1 <= upperNode.getLeftBorder() >> 1
+                        && y1 <= (int) (5 + (model.getScale() + scalediv20 + 10) * count) + model.getScaleDiv2()
+                        && x2 >= upperNode.getLeftBorder() >> 1
+                        && y2 >= (int) (5 + (model.getScale() + scalediv20 + 10) * count)) {
+                    tempSelected.add(cps);
+
+                }
+                count++;
+            }
+        }
+
+        repaint();
+
+    }
+
+    @Override
+    public void mouseMoved(MouseEvent e) {
+        x = e.getX();
+        y = e.getY();
+
+        // Everything for the tooltip :)
+        boolean on = false;
+        for (AbstractCpsObject cps : upperNode.getNodes()) {
+
+            cx = cps.getPosition().x - controller.getScaleDiv2();
+            cy = cps.getPosition().y - controller.getScaleDiv2();
+
+            on = setToolTipInfoAndPosition(on, cps);
+        }
+        int count = 0;
+        for (CpsEdge ed : upperNode.getConnections()) {
+
+            AbstractCpsObject cps;
+            if (ed.getA().equals(this.upperNode)) {
+                cps = ed.getB();
+            } else {
+                cps = ed.getA();
+            }
+
+            cx = upperNode.getLeftBorder() >> 1;
+            cy = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count);
+            if (x - 50 <= cx && y - 50 <= cy && x >= cx && y >= cy) {
+
+                on = true;
+                toolTipPos.x = cx - 25;
+                toolTipPos.y = cy + 50;
+                toolTipText = cps.getName() + ", " + cps.getId();
+
+            }
+            count++;
+        }
+
+        toolTip = on;
+        repaint();
+    }
+
+    /**
+     * Draws or Deletes an Edge.
+     */
+    void drawDeleteEdge() {
+        boolean node = true; // new node?
+        boolean newEdge = true;
+        boolean onEdge = true;
+        boolean deleteNode = false;
+        boolean outsideCon = !upperNode.getNodes().contains(tempCps); // Connection to the outside
+        boolean found = false; // dont search for outside connetion if inside
+        // connection is found
+        CpsEdge e = null;
+        for (AbstractCpsObject cps : upperNode.getNodes()) {
+
+            cx = cps.getPosition().x - controller.getScaleDiv2();
+            cy = cps.getPosition().y - controller.getScaleDiv2();
+
+            if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
+                    && cps != tempCps) {
+                found = true;
+                node = false;
+                onEdge = false;
+                for (CpsEdge p : tempCps.getConnections()) {
+                    if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
+                        newEdge = false;
+                        e = p;
+                    }
+                }
+                if (!newEdge) {
+                    if (outsideCon) {
+                        controller.disconnectNodes(e, upperNode);
+                    } else {
+                        controller.delEdgeUpperNode(e, upperNode);
+                    }
+                    // Node ohne Edge?
+                    if (e.getA().getClass() == CpsNode.class && e.getA().getConnections().isEmpty()) {
+                        tempCps = e.getA();
+                        deleteNode = true;
+                    }
+                    if (e.getB().getClass() == CpsNode.class && e.getB().getConnections().isEmpty()) {
+                        deleteNode = true;
+                    }
+                } else {
+                    e = new CpsEdge(cps, tempCps, model.getMaxCapacity());
+                    if (outsideCon) {
+                        controller.connectNodes(e, upperNode);
+                    } else {
+                        controller.addEdgeUpperNode(e, upperNode);
+                    }
+                }
+            }
+        }
+        if (!found && !outsideCon) {
+            int count = 0;
+            for (CpsEdge ed : upperNode.getConnections()) {
+                AbstractCpsObject cps;
+                if (ed.getA().equals(upperNode)) {
+                    cps = ed.getB();
+                } else {
+                    cps = ed.getA();
+                }
+
+                cx = upperNode.getLeftBorder() >> 1;
+                cy = (int) (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count);
+
+                if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
+                        && cps != tempCps) {
+                    outsideCon = true;
+                    node = false;
+                    onEdge = false;
+                    for (CpsEdge p : tempCps.getConnections()) {
+                        if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
+                            newEdge = false;
+                            e = p;
+                        }
+                    }
+                    if (!newEdge) {
+                        if (outsideCon) {
+                            controller.disconnectNodes(e, upperNode);
+                        } else {
+                            controller.delEdgeUpperNode(e, upperNode);
+                        }
+                        // Node ohne Edge?
+                        if (e.getA().getClass() == CpsNode.class && e.getA().getConnections().isEmpty()) {
+                            tempCps = e.getA();
+                            deleteNode = true;
+                        }
+                        if (e.getB().getClass() == CpsNode.class && e.getB().getConnections().isEmpty()) {
+                            deleteNode = true;
+                        }
+                    } else {
+                        CpsEdge edge = new CpsEdge(cps, tempCps, model.getMaxCapacity());
+                        if (outsideCon) {
+                            controller.connectNodes(edge, upperNode);
+                        } else {
+                            controller.addEdgeUpperNode(edge, upperNode);
+                        }
+                    }
+                }
+                count++;
+            }
+        }
+
+        // Edge auf eine Edge gezogen?
+        if (onEdge) {
+            CpsEdge p = mousePositionOnEdge(x, y);
+            if (p != null) {
+                CpsEdge e1;
+                CpsEdge e2;
+
+                node = false;
+
+                CpsNode n = new CpsNode("Node");
+
+                n.setPosition(x, y);
+                controller.addObjUpperNode(n, upperNode);
+
+                AbstractCpsObject r, k;
+                r = p.getA();
+                k = p.getB();
+
+                e = new CpsEdge(n, tempCps, model.getMaxCapacity());
+
+                e1 = new CpsEdge(n, r, model.getMaxCapacity());
+
+                e2 = new CpsEdge(n, k, model.getMaxCapacity());
+
+                controller.delEdgeUpperNode(p, upperNode);
+                if (outsideCon) {
+                    controller.connectNodes(e, upperNode);
+                } else {
+                    controller.addEdgeUpperNode(e, upperNode);
+                }
+
+                controller.addEdgeUpperNode(e1, upperNode);
+                controller.addEdgeUpperNode(e2, upperNode);
+            }
+        }
+
+        // ins leere Gedragged
+        if (node && x > upperNode.getLeftBorder()) {
+            CpsNode n = new CpsNode("Node");
+
+            n.setPosition(x, y);
+            controller.addObjUpperNode(n, upperNode);
+
+            e = new CpsEdge(n, tempCps, model.getMaxCapacity());
+
+            if (outsideCon) {
+                controller.connectNodes(e, upperNode);
+            } else {
+                controller.addEdgeUpperNode(e, upperNode);
+            }
+        }
+
+        // Wenn ein Node ohne Connections da ist
+        if (deleteNode) {
+            controller.delCanvasObject(tempCps, true);
+            tempCps = null;
+        }
+    }
+
+    /**
+     * Checks if the mouse is on an Edge.
+     *
+     * @param x Position of the Mouse
+     * @param y Position of the Mouse
+     * @return CpsEdge the Mouse is on, null if the mouse is not on an Edge
+     */
+    private CpsEdge mousePositionOnEdge(int x, int y) {
+        x += controller.getScaleDiv2();
+        y += controller.getScaleDiv2();
+        int lx, ly, hx, hy;
+
+
+        for (CpsEdge p : upperNode.getNodeEdges()) {
+            Line2D l = new Line2D.Float(p.getA().getPosition().x, p.getA().getPosition().y, p.getB().getPosition().x,
+                    p.getB().getPosition().y);
+
+            int[] positions = determineMousePositionOnEdge(p);
+            lx = positions[0];
+            ly = positions[1];
+            hx = positions[2];
+            hy = positions[3];
+
+            // distance from a point to a line and between both Objects
+            if (l.ptLineDistSq(x - model.getScaleDiv2(), y - model.getScaleDiv2()) < 20 && x > lx && x < hx && y > ly
+                    && y < hy) {
+                return p;
+            }
+        }
+
+        // edge to outside connection
+
+        int count = 0;
+        for (CpsEdge e : upperNode.getConnections()) {
+            AbstractCpsObject cps;
+            if (e.getA().equals(this.upperNode)) {
+                cps = e.getB();
+            } else {
+                cps = e.getA();
+            }
+            for (CpsEdge p : cps.getConnections()) {
+                AbstractCpsObject obj = null;
+                boolean doTest = false;
+                if (upperNode.getNodes().contains(p.getA())) {
+                    obj = p.getA();
+                    doTest = true;
+                } else if (upperNode.getNodes().contains(p.getB())) {
+                    obj = p.getB();
+                    doTest = true;
+                }
+                // g2.drawImage(img, (borderPos >> 1) - 25, (int) (scalediv20 +
+                // 5 + (50 + scalediv20 + 10) * count), 50, 50, null);
+                if (doTest) {
+                    Line2D l = new Line2D.Float((upperNode.getLeftBorder() >> 1) - 25,
+                            (int) (scalediv20 + 5 + 25 + (50 + scalediv20 + 10) * count), obj.getPosition().x,
+                            obj.getPosition().y);
+                    if ((upperNode.getLeftBorder() >> 1) > obj.getPosition().x) {
+                        hx = (upperNode.getLeftBorder() >> 1) - 25 + model.getScaleDiv2() + 7;
+                        lx = obj.getPosition().x + model.getScaleDiv2() - 7;
+                    } else {
+                        lx = (upperNode.getLeftBorder() >> 1) - 25 + model.getScaleDiv2() - 7;
+                        hx = obj.getPosition().x + model.getScaleDiv2() + 7;
+                    }
+                    if ((int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) > obj.getPosition().y) {
+                        hy = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + model.getScaleDiv2() + 7;
+                        ly = obj.getPosition().y + model.getScaleDiv2() - 7;
+                    } else {
+                        ly = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + model.getScaleDiv2() - 7;
+                        hy = obj.getPosition().y + model.getScaleDiv2() + 7;
+                    }
+
+                    // distance from a point to a line and between both Objects
+                    if (l.ptLineDistSq(x - model.getScaleDiv2(), y - model.getScaleDiv2()) < 20 && x > lx && x < hx
+                            && y > ly && y < hy) {
+                        return p;
+                    }
+                }
+            }
+            count++;
+        }
+        return null;
+    }
+
+//    /**
+//     * sets the Edge Capacity.
+//     *
+//     * @param cap capacity
+//     */
+//    public void setEdgeCapacity(float cap) {
+//        controller.setMaxCapacity(cap);
+//    }
+
+//    /**
+//     * Returns if Information should be shown.
+//     *
+//     * @return Array of boolean [0] = connection, [1] = objects
+//     */
+//    public boolean[] getShowedInformation() {
+//        return showedInformation;
+//    }
+
+    /**
+     * copies a set of given informations
+     *
+     * @param informations
+     */
+    protected void setShowedInformation(boolean[] informations) {
+        showedInformation = informations;
+    }
+
+//    /**
+//     * Set the Background Image;
+//     *
+//     * @param imagePath Image Path
+//     * @param mode      Image Mode
+//     * @param width     Image custom width
+//     * @param height    Image custom height
+//     */
+//    public void setBackgroundImage(String imagePath, int mode, int width, int height) {
+//        upperNode.setBackgroundImage(imagePath, mode, width, height);
+//    }
+
+    /**
+     * set tooltIp
+     *
+     * @param bool
+     */
+    void setToolTip(boolean bool) {
+        this.toolTip = bool;
+    }
+
+    /**
+     * Set the Mouse Position on the UpperNodeCanvas;
+     *
+     * @param x
+     * @param y
+     */
+    void setXY(int x, int y) {
+        this.x = x;
+        this.y = y;
+    }
 
 }