TomTroppmann 3 лет назад
Родитель
Сommit
ac93fcd484
91 измененных файлов с 6304 добавлено и 9157 удалено
  1. 0 4
      .gitignore
  2. BIN
      jars/miglayout/miglayout-core-4.3-20121116.151612-3-javadoc.jar
  3. BIN
      jars/miglayout/miglayout-core-4.3-20121116.151612-3-sources.jar
  4. BIN
      jars/miglayout/miglayout-core-4.3-20121116.151612-3.jar
  5. BIN
      jars/miglayout/miglayout-swing-4.3-20121116.151626-3-javadoc.jar
  6. BIN
      jars/miglayout/miglayout-swing-4.3-20121116.151626-3-sources.jar
  7. BIN
      jars/miglayout/miglayout-swing-4.3-20121116.151626-3.jar
  8. BIN
      res/Images/duplicate.png
  9. 1 2
      src/Connection/ConnectHandheld.java
  10. 1 1
      src/Connection/ConnectPhysical.java
  11. 14 19
      src/Connection/socket/Server.java
  12. 2 4
      src/addOns/Utility/HolonElementSketch.java
  13. 2 2
      src/algorithm/binary/BaseLine.java
  14. 2 3
      src/algorithm/example/DemoAlgo.java
  15. 3 3
      src/algorithm/example/FlexExample.java
  16. 0 1
      src/algorithm/objectiveFunction/Evaluation.java
  17. 1 1
      src/algorithm/objectiveFunction/TopologieObjectiveFunction.java
  18. 4 4
      src/api/AlgorithmFrameworkFlex.java
  19. 3 3
      src/api/TopologieAlgorithmFramework.java
  20. 4 26
      src/classes/AbstractCanvasObject.java
  21. 2 2
      src/classes/Flexibility.java
  22. 0 20
      src/classes/GroupNode.java
  23. 0 172
      src/classes/HolonBody.java
  24. 19 71
      src/classes/HolonElement.java
  25. 15 89
      src/classes/HolonObject.java
  26. 5 10
      src/classes/HolonSwitch.java
  27. 1 5
      src/classes/Node.java
  28. 1 1
      src/classes/comparator/UnitGraphPointComperator.java
  29. 2 2
      src/classes/comparator/elementComparator/ElemCompOnEnergy.java
  30. 0 18
      src/classes/comparator/elementComparator/ElemCompOnObj.java
  31. 0 20
      src/classes/comparator/elementComparator/ElemCompOnQuantity.java
  32. 5 3
      src/interfaces/GraphEditable.java
  33. 1 0
      src/interfaces/GraphListener.java
  34. 3 0
      src/interfaces/TimelineDependent.java
  35. 51 32
      src/ui/controller/CanvasController.java
  36. 8 9
      src/ui/controller/CategoryController.java
  37. 15 12
      src/ui/controller/ClipboardController.java
  38. 774 813
      src/ui/controller/Control.java
  39. 0 2
      src/ui/controller/FlexManager.java
  40. 0 236
      src/ui/controller/HolonCanvasController.java
  41. 2 4
      src/ui/controller/IndexTranslator.java
  42. 24 33
      src/ui/controller/LoadController.java
  43. 6 9
      src/ui/controller/NodeController.java
  44. 188 187
      src/ui/controller/ObjectController.java
  45. 2 1
      src/ui/controller/SimulationManager.java
  46. 0 487
      src/ui/controller/UpdateController.java
  47. 1 1
      src/ui/model/MinimumNetwork.java
  48. 29 92
      src/ui/model/Model.java
  49. 0 49
      src/ui/view/DefaulTable.java
  50. 0 2830
      src/ui/view/GUI.java
  51. 0 1272
      src/ui/view/GroupNodeCanvas.java
  52. 0 51
      src/ui/view/Main.java
  53. 0 1126
      src/ui/view/MyCanvas.java
  54. 0 38
      src/ui/view/PropertyTable.java
  55. 0 792
      src/ui/view/UnitGraph.java
  56. 80 120
      src/ui/view/canvas/AbstractCanvas.java
  57. 1054 0
      src/ui/view/canvas/Canvas.java
  58. 489 0
      src/ui/view/canvas/GroupNodeCanvas.java
  59. 2 7
      src/ui/view/component/ButtonTabComponent.java
  60. 1 1
      src/ui/view/component/Console.java
  61. 95 0
      src/ui/view/component/TrippleCheckBox.java
  62. 1 1
      src/ui/view/dialog/AboutUsPopUp.java
  63. 19 26
      src/ui/view/dialog/AddElementPopUp.java
  64. 22 37
      src/ui/view/dialog/AddObjectPopUp.java
  65. 8 3
      src/ui/view/dialog/BackgroundPopUp.java
  66. 25 19
      src/ui/view/dialog/CanvasResizePopUp.java
  67. 4 6
      src/ui/view/dialog/CreateNewDialog.java
  68. 9 9
      src/ui/view/dialog/CreateTemplatePopUp.java
  69. 4 3
      src/ui/view/dialog/EditEdgesPopUp.java
  70. 34 28
      src/ui/view/dialog/SearchPopUp.java
  71. 165 0
      src/ui/view/inspector/Inspector.java
  72. 348 0
      src/ui/view/inspector/InspectorTable.java
  73. 900 0
      src/ui/view/inspector/UnitGraph.java
  74. 1 1
      src/ui/view/inspector/UnitGraphPoint.java
  75. 1713 0
      src/ui/view/main/GUI.java
  76. 54 0
      src/ui/view/main/Main.java
  77. 11 18
      src/ui/view/main/TimePanel.java
  78. 2 2
      src/ui/view/window/AddOnWindow.java
  79. 3 3
      src/ui/view/window/FlexWindow.java
  80. 2 6
      src/ui/view/window/Outliner.java
  81. 1 1
      src/utility/events/Action.java
  82. 1 1
      src/utility/events/Event.java
  83. 16 0
      src/utility/events/LostFocusListener.java
  84. 24 0
      src/utility/events/SimpleDocumentListener.java
  85. 1 1
      tests/tests/PraktikumHolonsAdapter.java
  86. 3 3
      tests/tests/PraktikumHolonsTestCanvasController.java
  87. 6 6
      tests/tests/PraktikumHolonsTestCategoryController.java
  88. 4 8
      tests/tests/PraktikumHolonsTestClasses.java
  89. 2 2
      tests/tests/PraktikumHolonsTestGlobalController.java
  90. 0 274
      tests/tests/PraktikumHolonsTestLoadAndStoreController.java
  91. 9 9
      tests/tests/PraktikumHolonsTestObjectController.java

+ 0 - 4
.gitignore

@@ -135,7 +135,3 @@ dist/
 nbdist/
 .nb-gradle/
 
-### added manually ###
-.idea/
-praktikum-holons.iml
-/target/

BIN
jars/miglayout/miglayout-core-4.3-20121116.151612-3-javadoc.jar


BIN
jars/miglayout/miglayout-core-4.3-20121116.151612-3-sources.jar


BIN
jars/miglayout/miglayout-core-4.3-20121116.151612-3.jar


BIN
jars/miglayout/miglayout-swing-4.3-20121116.151626-3-javadoc.jar


BIN
jars/miglayout/miglayout-swing-4.3-20121116.151626-3-sources.jar


BIN
jars/miglayout/miglayout-swing-4.3-20121116.151626-3.jar


BIN
res/Images/duplicate.png


+ 1 - 2
src/Connection/ConnectHandheld.java

@@ -27,7 +27,7 @@ import classes.GroupNode;
 import classes.HolonObject;
 import Connection.socket.Server;
 import ui.controller.Control;
-import ui.view.Console;
+import ui.view.component.Console;
 
 public class ConnectHandheld implements AddOn{
 	
@@ -154,7 +154,6 @@ public class ConnectHandheld implements AddOn{
 			console.println(e.getMessage());
 		}
 		catch (IOException e) {
-			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
 	}

+ 1 - 1
src/Connection/ConnectPhysical.java

@@ -36,7 +36,7 @@ import classes.GroupNode;
 import classes.HolonElement;
 import classes.HolonObject;
 import ui.controller.Control;
-import ui.view.Console;
+import ui.view.component.Console;
 /**
  * Easy Connection via Http Request. Repeat Request with a delay.
  * 

+ 14 - 19
src/Connection/socket/Server.java

@@ -17,7 +17,7 @@ public class Server implements Runnable{
     private DataInputStream in;
     private boolean stopped = false;		
     private boolean connection = false;
-    private ui.view.Console console;
+    private ui.view.component.Console console;
     
     
     private HolonObject observed;
@@ -25,7 +25,7 @@ public class Server implements Runnable{
     private HolonObjectModel newModelField;
 	private Control control;
     
-    public Server(int port, ui.view.Console console, HolonObject observed, Control control) throws IOException {
+    public Server(int port, ui.view.component.Console console, HolonObject observed, Control control) throws IOException {
     	this.observed = observed;
     	this.console = console;
     	this.control = control;
@@ -97,9 +97,9 @@ public class Server implements Runnable{
 				if(observed == null) stopConnection();
 				console.println("Res: [" + inputByte + "] -> SetAmount");
 				int index = in.readInt();
-				int amount = in.readInt();
-				modelField.getElements().get(index).amount = amount;
-				observed.getElements().get(index).setAmount(amount);
+				//int amount = in.readInt();
+				//modelField.getElements().get(index).amount = amount;
+				//observed.getElements().get(index).setAmount(amount);
 				
 			}else if (inputByte == Command.SetEnable) {
 				if(observed == null) stopConnection();
@@ -112,24 +112,23 @@ public class Server implements Runnable{
 				if(observed == null) stopConnection();
 				console.println("Res: [" + inputByte + "] -> IncreaseAmount");
 				int index = in.readInt();
-				modelField.getElements().get(index).amount++;
+				//modelField.getElements().get(index).amount++;
 				HolonElement ele = observed.getElements().get(index);
-				ele.setAmount(ele.getAmount()+1);
+				//ele.setAmount(ele.getAmount()+1);
 				
 			}else if (inputByte == Command.DecreaseAmount) {
 				if(observed == null) stopConnection();
 				console.println("Res: [" + inputByte + "] -> DecreaseAmount");
 				int index = in.readInt();
-				modelField.getElements().get(index).amount--;
+				//modelField.getElements().get(index).amount--;
 				HolonElement ele = observed.getElements().get(index);
-				ele.setAmount(ele.getAmount()-1);
+				//ele.setAmount(ele.getAmount()-1);
 				
 			} else{
 				console.println("Res: [" + inputByte + "] -> unknown");
 			}
 			control.calculateStateAndVisualForCurrentTimeStep();
 			control.updateCanvas();
-			control.getGui().triggerUpdateController(null);
 		}
 	}
 	
@@ -172,7 +171,6 @@ public class Server implements Runnable{
 		}
 
 		private boolean checkForUpdates() {
-			//TODO Delete And CheckforUpdatesReal
 			newModelField = createModel();
 			if(compareModels(modelField,newModelField)) {
 				return false;
@@ -195,7 +193,7 @@ public class Server implements Runnable{
 				out.writeInt(modelField.size());
 				for(HolonElementWrapper wrapper : modelField.getElements()) {
 					out.writeUTF(wrapper.name);
-					out.writeInt(wrapper.amount);
+					//out.writeInt(wrapper.amount);
 					out.writeFloat(wrapper.energy);
 					out.writeBoolean(wrapper.enabled);
 				}
@@ -248,10 +246,10 @@ public class Server implements Runnable{
 		
 		public void add(HolonElement ele, int index ) {
 			String name = ele.getEleName();
-			int amount =ele.getAmount();
-			float energy =  ele.getEnergyPerElement();
+			//int amount =ele.getAmount();
+			float energy =  ele.getEnergy();
 			boolean enabled = ele.isActive();
-			elements.add(new HolonElementWrapper(name, amount, energy, enabled, index));
+			elements.add(new HolonElementWrapper(name, energy, enabled, index));
 		}
 		
 		public int size() {
@@ -274,15 +272,13 @@ public class Server implements Runnable{
 	public class HolonElementWrapper{
 		public int index;
 		public String name;
-		public int amount;
 		public float energy;
 		public boolean enabled;
 		public HolonElementWrapper(){
 			
 		}
-		public HolonElementWrapper(String name, int amount, float energy, boolean enabled, int index){
+		public HolonElementWrapper(String name, float energy, boolean enabled, int index){
 			this.name = name;
-			this.amount = amount;
 			this.energy = energy;
 			this.enabled = enabled;
 		}
@@ -299,7 +295,6 @@ public class Server implements Runnable{
 			
 			
 			return this.name.compareTo(element.name) == 0 &&
-				   this.amount == element.amount &&
 				   this.energy == element.energy &&
 				   this.enabled == element.enabled;
 		}

+ 2 - 4
src/addOns/Utility/HolonElementSketch.java

@@ -19,14 +19,12 @@ public class HolonElementSketch {
 	public FlexibilitySketch onFlex;
 	public FlexibilitySketch offFlex;
 	
-	public HolonElementSketch(String name, int minAmount, int maxAmount, float energy) {
+	public HolonElementSketch(String name, float energy) {
 		this.name = name;
-		this.minAmount = minAmount;
-		this.maxAmount = maxAmount;
 		this.energy = energy;
 	}
 	public HolonElement createHolonElement(HolonObject parentObject, boolean active) {
-		HolonElement ele = new HolonElement(parentObject, name, Random.nextIntegerInRange(minAmount, maxAmount + 1), energy);
+		HolonElement ele = new HolonElement(parentObject, name, energy);
 		ele.setActive(active);
 		if(onFlex != null && Random.nextDouble() < onFlex.flexChance)addFlex(ele, parentObject.getName(), true);
 		if(offFlex != null && Random.nextDouble() < offFlex.flexChance)addFlex(ele, parentObject.getName(), false);

+ 2 - 2
src/algorithm/binary/BaseLine.java

@@ -271,7 +271,7 @@ public class BaseLine implements AddOn {
 	 */
 	private void executeBaseLine() {
 		extractPositionAndAccess();
-		int actualIteration = control.getModel().getCurIteration();
+		int actualIteration = control.getModel().getCurrentIteration();
 		if(closeSwitches)setAllSwitchesClosed();
 		setHolonElemntsAktiv();
 		control.calculateStateAndVisualForCurrentTimeStep();
@@ -338,7 +338,7 @@ public class BaseLine implements AddOn {
 		objectList = new ArrayList<HolonObject>();
 		initialState = new ArrayList<Boolean>(); 
 		access= new HashMap<Integer, AccessWrapper>();
-		rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
+		rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurrentIteration());
 		return initialState;
 	}
 	/**

+ 2 - 3
src/algorithm/example/DemoAlgo.java

@@ -283,7 +283,7 @@ public class DemoAlgo implements AddOn {
 		private void executeDemoAlgo() {
 			extractPositionAndAccess();
 			counter = 0;
-			int actualIteration = control.getModel().getCurIteration();
+			int actualIteration = control.getModel().getCurrentIteration();
 			deactivateWindrad();
 			setAllSwitchesClosed();
 			updateVisual();
@@ -341,7 +341,7 @@ public class DemoAlgo implements AddOn {
 			objectList = new ArrayList<HolonObject>();
 			initialState = new ArrayList<Boolean>(); 
 			access= new HashMap<Integer, AccessWrapper>();
-			rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());
+			rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurrentIteration());
 			return initialState;
 		}
 		/**
@@ -376,7 +376,6 @@ public class DemoAlgo implements AddOn {
 		private void updateVisual() {
 			control.calculateStateAndVisualForCurrentTimeStep();
 			control.updateCanvas();
-			control.getGui().triggerUpdateController(null);
 		}
 		/**
 		 * Sets the Model back to its original State before the LAST run.

+ 3 - 3
src/algorithm/example/FlexExample.java

@@ -332,7 +332,7 @@ public class FlexExample implements AddOn {
 		 */
 		private void executeDemoAlgo(RunResult result) {
 			extractPositionAndAccess();
-			int actualIteration = control.getModel().getCurIteration();
+			int actualIteration = control.getModel().getCurrentIteration();
 			println("TimeStep:" + actualIteration);
 			control.calculateStateOnlyForCurrentTimeStep();
 			List<Priority> priorityListASC = createPriorityListASC();
@@ -424,7 +424,7 @@ public class FlexExample implements AddOn {
 			
 			List<HolonElement> elementsOfPriorityToShutdown = allHolonElemntsInThisNetwork.stream().filter(hElement -> hElement.isConsumer() && hElement.getPriority() == emergencyShutDownPriority && !hElement.isFlexActive(flexManager) && hElement.isActive()).collect(Collectors.toList());
 					//.forEach(hElement -> hElement.setActive(false));
-			float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergyPerElement() * hElement.getAmount()).reduce(0.0f, (a, b) -> a + b);
+			float energyGained = elementsOfPriorityToShutdown.stream().map(hElement -> -hElement.getEnergy()).reduce(0.0f, (a, b) -> a + b);
 			elementsOfPriorityToShutdown.forEach(hElement -> hElement.setActive(false));
 			int shutdownCount = elementsOfPriorityToShutdown.size();
 			result.deactivatedElements += shutdownCount;
@@ -466,7 +466,7 @@ public class FlexExample implements AddOn {
 			objectList = new ArrayList<HolonObject>();
 			initialState = new ArrayList<Boolean>();
 			access= new HashMap<Integer, AccessWrapper>();
-			rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());			
+			rollOutNodes((useGroupNode && (dGroupNode != null))? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurrentIteration());			
 			resetChain.add(initialState); 
 			return initialState;
 		}

+ 0 - 1
src/algorithm/objectiveFunction/Evaluation.java

@@ -12,7 +12,6 @@ public class Evaluation {
 	
 	/**
 	 * Calculate the Fitness(Penelty) Value for a state (alias the calculated Position).
-	 * TODO: Make me better Rolf.
 	 * @param state
 	 * @return
 	 */

+ 1 - 1
src/algorithm/objectiveFunction/TopologieObjectiveFunction.java

@@ -96,7 +96,7 @@ public class TopologieObjectiveFunction {
 	 * 
 	 * 
 	 * @param state
-	 * @param moreInformation TODO
+	 * @param moreInformation if more prints should be made
 	 * @return f_g value between 0 and 100
 	 */
 	static public float getFitnessValueForState(DecoratedState state, int amountOfAddedSwitch, double addedCableMeters, boolean moreInformation) {

+ 4 - 4
src/api/AlgorithmFrameworkFlex.java

@@ -59,8 +59,8 @@ import ui.model.DecoratedState;
 import ui.model.Model;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedSwitch.SwitchState;
+import ui.view.component.Console;
 import ui.model.DecoratedNetwork;
-import ui.view.Console;
 import utility.ImageImport;
 import utility.StringFormat;
 
@@ -624,7 +624,7 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
 		}
 		
-		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurrentIteration());
 		this.extractPositionAndAccess();
 		setState(runBest.position);
 		updateVisual();
@@ -753,7 +753,7 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 	 * @param position
 	 */
 	private void setState(List<Boolean> position) {
-		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurrentIteration());
 		int i = 0;
 		for(Boolean bool: position) {
 			access.get(i++).setState(bool);
@@ -773,7 +773,7 @@ public abstract class AlgorithmFrameworkFlex implements AddOn{
 		this.accessKillSwitch = new HashMap<HolonObject, AccessWrapper>();
 		access= new ArrayList<AccessWrapper>();
 		List<Boolean> initialState = new ArrayList<Boolean>();
-		rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurIteration());			
+		rollOutNodes((dGroupNode != null)? dGroupNode.getModel().getNodes() :model.getObjectsOnCanvas(), initialState, model.getCurrentIteration());			
 		resetChain.add(initialState);
 		if(algoUseFlexes) {			
 			for(FlexWrapper flex :control.getSimManager().getActualFlexManager().getAllFlexWrapperWithState(FlexState.OFFERED)){

+ 3 - 3
src/api/TopologieAlgorithmFramework.java

@@ -55,8 +55,8 @@ import ui.model.DecoratedState;
 import ui.model.Model;
 import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedSwitch.SwitchState;
+import ui.view.component.Console;
 import ui.model.DecoratedNetwork;
-import ui.view.Console;
 
 public abstract class TopologieAlgorithmFramework implements AddOn{
 	//Algo
@@ -224,7 +224,7 @@ public abstract class TopologieAlgorithmFramework implements AddOn{
 	private void toggleSwitches() {
 		List<HolonSwitch> allSwitchList = control.getModel().getAllSwitches();
 		if(allSwitchList.isEmpty()) return;
-		boolean set = allSwitchList.get(0).getState(control.getModel().getCurIteration());
+		boolean set = allSwitchList.get(0).getState(control.getModel().getCurrentIteration());
 		allSwitchList.forEach(hSwitch -> {
 			hSwitch.setManualMode(true);
 			hSwitch.setManualState(!set);
@@ -622,7 +622,7 @@ public abstract class TopologieAlgorithmFramework implements AddOn{
 			if(roundBest.fitness < runBest.fitness) runBest = roundBest;
 		}
 		
-		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurIteration());
+		control.getSimManager().resetFlexManagerForTimeStep(control.getModel().getCurrentIteration());
 		setState(runBest.position);
 		for(HolonSwitch hSwitch: switchList) {
 			hSwitch.setManualMode(true);

+ 4 - 26
src/classes/AbstractCanvasObject.java

@@ -35,10 +35,6 @@ public abstract class AbstractCanvasObject {
 	/* Position with a X and Y value */
 	@Expose
 	Vector2Int position = new Vector2Int(0,0);
-	/*
-	 * Energy input and output of each object in the grid Where the Object is
-	 * Stored
-	 */
 	@Expose
 	String sav;
 	/* tags that can be used */
@@ -51,7 +47,6 @@ public abstract class AbstractCanvasObject {
 	 *            of the Object
 	 */
 	public AbstractCanvasObject(String objName) {
-		setObjName(objName);
 		setName(objName);
 		setImage("/Images/Dummy_House.png");
 	}
@@ -65,33 +60,13 @@ public abstract class AbstractCanvasObject {
 	 *            Object to be copied
 	 */
 	public AbstractCanvasObject(AbstractCanvasObject obj) {
-		setObjName(obj.getObjName());
-		setName(obj.getObjName());
+		setName(obj.getName());
 		setConnections(new ArrayList<>());
 		setId(IdCounter.nextId(CounterType.Object));
 		setImage(obj.getImage());
 	}
 	
-	public abstract AbstractCanvasObject makeCopy();
-
-	/**
-	 * Getter for the type of the Object.
-	 * 
-	 * @return String
-	 */
-	public String getObjName() {
-		return objName;
-	}
 
-	/**
-	 * Set the type of Object.
-	 * 
-	 * @param objName
-	 *            String
-	 */
-	public void setObjName(String objName) {
-		this.objName = objName;
-	}
 
 	/**
 	 * Getter for the user-defined name (no unique).
@@ -150,6 +125,9 @@ public abstract class AbstractCanvasObject {
 		this.image = image;
 	}
 
+	
+	
+	
 	/**
 	 * List of all existing connections.
 	 * 

+ 2 - 2
src/classes/Flexibility.java

@@ -85,12 +85,12 @@ public class Flexibility {
 
 	/** returns the total energy Amount accumulated over the TimeSteps.*/
 	public float magnitude() {
-		return ((float)duration) *  element.getEnergyPerElement() * element.getAmount();
+		return ((float)duration) *  element.getEnergy();
 	}
 	
 	public float bringtmir(){
 		//System.out.println("Name:" +  element.getEleName() + "   BringtMir:" + (-element.getEnergyPerElement() * element.getAmount()));
-		return (constrainList.stream().map(constrain -> constrain.getName()).anyMatch(name -> name.equals("onConstrain"))?-1.0f:1.0f) * element.getEnergyPerElement() * element.getAmount();
+		return (constrainList.stream().map(constrain -> constrain.getName()).anyMatch(name -> name.equals("onConstrain"))?-1.0f:1.0f) * element.getEnergy();
 	}
 	public boolean isPositive() {
 		return bringtmir() >= 0;

+ 0 - 20
src/classes/GroupNode.java

@@ -12,8 +12,6 @@ public class GroupNode extends AbstractCanvasObject {
 	private ArrayList<AbstractCanvasObject> nodes;
 	private HashMap<Integer, Integer> nodesIdx;
 	
-	@Expose
-	private int leftBorder; //TODO Delete leftBorder, jet is just set to 0
 	@Expose
 	private String imgPath = "";
 	@Expose
@@ -180,24 +178,6 @@ public class GroupNode extends AbstractCanvasObject {
 		return backgroundHeight;
 	}
 
-	/**
-	 * @return the leftBorder
-	 */
-	public int getLeftBorder() {
-		return leftBorder;
-	}
-
-	/**
-	 * @param leftBorder the leftBorder to set
-	 */
-	public void setLeftBorder(int leftBorder) {
-		this.leftBorder = leftBorder;
-	}
-
-	@Override
-	public AbstractCanvasObject makeCopy() {
-		return this;
-	}
 
 
 }

+ 0 - 172
src/classes/HolonBody.java

@@ -1,172 +0,0 @@
-package classes;
-
-import java.awt.Color;
-import java.awt.Dimension;
-import java.awt.Font;
-import java.awt.Graphics2D;
-
-import utility.Vector2Float;
-
-public class HolonBody implements Comparable<HolonBody> {
-
-	public Vector2Float velocity;
-	public Vector2Float position;
-	private float mass;
-	private float radius;
-	private Color color;
-	private int id;
-
-	public void setId(int id) {
-		this.id = id;
-	}
-
-	public int getId() {
-		return id;
-	}
-
-	public Color getColor() {
-		return color;
-	}
-
-	public HolonBody(float x, float y, float radius, float mass, Color color) {
-		this.velocity = new Vector2Float(0, 0);
-		this.position = new Vector2Float(x, y);
-		this.setMass(mass);
-		this.setRadius(radius);
-		this.color = color;
-	}
-
-	public void draw(Graphics2D g2, String info) {
-
-		g2.setColor(color);
-		g2.fillOval((int) (position.getX() - getRadius()), (int) (position.getY() - getRadius()),
-				(int) (2 * getRadius()), (int) (2 * getRadius()));
-		g2.setFont(new Font("TimesRoman", Font.PLAIN, (int) radius/((info.length()/5)+1)));
-		g2.setColor(Color.WHITE);
-		g2.drawString(info, position.getX() - g2.getFontMetrics().stringWidth(info) / 2,
-				position.getY() + g2.getFontMetrics().getHeight() / 3);
-	}
-
-	public void setRadius(float radius) {
-		if (radius > 1)
-			this.radius = radius;
-		else
-			this.radius = 1;
-	}
-
-	public float getRadius() {
-		return radius;
-	}
-
-	public boolean colliding(HolonBody body) {
-		float xd = position.getX() - body.position.getX();
-		float yd = position.getY() - body.position.getY();
-
-		float sumRadius = getRadius() + body.getRadius();
-		float sqrRadius = sumRadius * sumRadius;
-
-		float distSqr = (xd * xd) + (yd * yd);
-
-		if (distSqr <= sqrRadius) {
-			return true;
-		}
-
-		return false;
-
-	}
-
-	public void resolveCollision(HolonBody body) {
-
-		// get the mtd
-		Vector2Float delta = (position.subtract(body.position));
-		float r = getRadius() + body.getRadius();
-		float dist2 = delta.dot(delta);
-
-		if (dist2 > r * r)
-			return; // they aren't colliding
-
-		float d = delta.getLength();
-
-		Vector2Float mtd;
-		if (d != 0.0f) {
-			// minimum translation distance to push bodies apart after
-			// intersecting
-			mtd = delta.multiply(((getRadius() + body.getRadius()) - d) / d);
-
-		} else {
-			// Special case. Bodies are exactly on top of eachother. Don't want
-			// to divide by zero.
-			d = body.getRadius() + getRadius() - 1.0f;
-			delta = new Vector2Float(body.getRadius() + getRadius(), 0.0f);
-
-			mtd = delta.multiply(((getRadius() + body.getRadius()) - d) / d);
-		}
-
-		// resolve intersection
-		float im1 = 1 / getMass(); // inverse mass quantities
-		float im2 = 1 / body.getMass();
-
-		// push-pull them apart
-		position = position.add(mtd.multiply(im1 / (im1 + im2)));
-		body.position = body.position.subtract(mtd.multiply(im2 / (im1 + im2)));
-
-		// impact speed
-		Vector2Float v = (this.velocity.subtract(body.velocity));
-		float vn = v.dot(mtd.normalize());
-
-		// sphere intersecting but moving away from each other already
-		if (vn > 0.0f)
-			return;
-
-		// collision impulse
-		float restitution = 0.85f;
-		float i = (-(1.0f + restitution) * vn) / (im1 + im2);
-		Vector2Float impulse = mtd.multiply(i);
-
-		// change in momentum
-		this.velocity = this.velocity.add(impulse.multiply(im1));
-		body.velocity = body.velocity.subtract(impulse.multiply(im2));
-
-	}
-
-	public void setMass(float mass) {
-		this.mass = mass;
-	}
-
-	private float getMass() {
-		return mass;
-	}
-
-	public int compareTo(HolonBody body) {
-		if (this.position.getX() - this.getRadius() > body.position.getX() - body.getRadius()) {
-			return 1;
-		} else if (this.position.getX() - this.getRadius() < body.position.getX() - body.getRadius()) {
-			return -1;
-		} else {
-			return 0;
-		}
-	}
-
-	public int compareSizeTo(HolonBody body) {
-		if (this.getRadius() > body.getRadius()) {
-			return 1;
-		} else if (this.getRadius() < body.getRadius()) {
-			return -1;
-		} else {
-			return 0;
-		}
-	}
-
-	public int compareDistTo(HolonBody body, Dimension center) {
-		float thisDist = (float) Math.sqrt(Math.pow(center.getWidth()-this.position.getX(),2)+Math.pow(center.getHeight()-this.position.getY(), 2));
-		float bodyDist = (float) Math.sqrt(Math.pow(center.getWidth()-body.position.getX(),2)+Math.pow(center.getHeight()-body.position.getY(), 2));
-		if (thisDist > bodyDist) {
-			return 1;
-		} else if (thisDist < bodyDist) {
-			return -1;
-		} else {
-			return 0;
-		}
-	}
-
-}

+ 19 - 71
src/classes/HolonElement.java

@@ -1,12 +1,12 @@
 package classes;
 
 import com.google.gson.annotations.Expose;
+import com.google.gson.annotations.SerializedName;
 
 import classes.IdCounter.CounterType;
-import interfaces.GraphEditable;
-import interfaces.LocalMode;
+import interfaces.TimelineDependent;
 import ui.controller.FlexManager;
-import ui.view.IndexTranslator;
+import ui.controller.IndexTranslator;
 
 import java.awt.*;
 import java.awt.geom.Point2D;
@@ -21,7 +21,7 @@ import java.util.ListIterator;
  *
  * @author Gruppe14
  */
-public class HolonElement implements LocalMode, GraphEditable{
+public class HolonElement implements TimelineDependent{
 
     /** Points of new TestGraph 
      * Represent the Graph 
@@ -29,18 +29,13 @@ public class HolonElement implements LocalMode, GraphEditable{
      * the Y component from a Point is the percentage from 0..1
      * */
     private LinkedList<Point2D.Double> graphPoints;
-    /** Name of the object, e.g. House, 1 */
-    @Expose
-    private String objName;
     /** Name of the gadget, e.g. TV */
     @Expose
     private String eleName;
     /** Amount of same elements */
     @Expose
-    private int amount;
-    /** Currently used energy per element (- indicates consumation of energy, + indicates production of energy)*/
-    @Expose
-    private float energyPerElement;
+    @SerializedName(value = "energy", alternate = "energyPerElement")
+    private float energy;
     /** Whether the gadget is active or not (currently uses/produces the energy in energyPerElement) */
     @Expose
     private boolean active;
@@ -90,20 +85,19 @@ public class HolonElement implements LocalMode, GraphEditable{
      * @param energy  float
      * @param model Model
      */
-    public HolonElement(HolonObject parentObject, String eleName, int amount, float energy) {
+    public HolonElement(HolonObject parentObject, String eleName, float energy) {
     	
-    	this(parentObject, eleName, amount, energy, IdCounter.nextId(CounterType.Element));
+    	this(parentObject, eleName, energy, IdCounter.nextId(CounterType.Element));
     }
     
 
     /**
      * same as standard constructor, but with already given id (so the counter is not increased twice)
      */
-    public HolonElement(HolonObject parentObject, String eleName, int amount, float energy, int id){
+    public HolonElement(HolonObject parentObject, String eleName, float energy, int id){
     	this.parentObject = parentObject;
     	setUseLocalPeriod(false);
     	setEleName(eleName);
-        setAmount(amount);
         setEnergyPerElement(energy);
         setActive(true);
         setGraphPoints(new LinkedList<>());
@@ -125,8 +119,7 @@ public class HolonElement implements LocalMode, GraphEditable{
     	setUseLocalPeriod(element.isUsingLocalPeriod());
         setEleName(element.getEleName());
         setLocalPeriod(element.getLocalPeriod());
-        setAmount(element.getAmount());
-        setEnergyPerElement(element.getEnergyPerElement());
+        setEnergyPerElement(element.getEnergy());
         setActive(element.isActive());
         setGraphPoints(new LinkedList<>());
         for (Point2D.Double p : element.getGraphPoints()) {
@@ -138,13 +131,6 @@ public class HolonElement implements LocalMode, GraphEditable{
 
     }
 
-	public String getObjName() {
-		return objName;
-	}
-
-	public void setObjName(String objName) {
-		this.objName = objName;
-	}
 
 
 
@@ -166,31 +152,14 @@ public class HolonElement implements LocalMode, GraphEditable{
         this.eleName = name;
     }
 
-    /**
-     * Get the actual amount of Elements in the selected Object.
-     *
-     * @return the amount int
-     */
-    public int getAmount() {
-        return amount;
-    }
-
-    /**
-     * Set the amount of the Element in the selected Object.
-     *
-     * @param amount the amount to set
-     */
-    public void setAmount(int amount) {
-        this.amount = amount;
-    }
 
     /**
      * Get the energyPerElement value of the selected Element.
      *
      * @return the energyPerElement
      */
-    public float getEnergyPerElement() {
-        return energyPerElement;
+    public float getEnergy() {
+        return energy;
     }
     public Priority getPriority() {
     	return priority;
@@ -209,7 +178,7 @@ public class HolonElement implements LocalMode, GraphEditable{
      */
     public boolean isProducer()
     {
-    	return (energyPerElement > 0);
+    	return (energy > 0);
     }
     
     /**
@@ -218,7 +187,7 @@ public class HolonElement implements LocalMode, GraphEditable{
      */
     public boolean isConsumer()
     {
-    	return (energyPerElement < 0);
+    	return (energy < 0);
     }
 
     /**
@@ -227,7 +196,7 @@ public class HolonElement implements LocalMode, GraphEditable{
      * @param energyPerElement the energyPerElement to set
      */
     public void setEnergyPerElement(float energyPerElement) {
-        this.energyPerElement = energyPerElement;
+        this.energy = energyPerElement;
     }
 
     /**
@@ -257,31 +226,11 @@ public class HolonElement implements LocalMode, GraphEditable{
         this.active = active;
     }
 
-    /**
-     * Multiply the amount of gadgets, given by the user, and the
-     * consumption/production. If the switch isWorking is turned off for on
-     * gadget, the energyPerElement of this gadget have to be subtracted.
-     *
-     * @return totalEnergy (actual)
-     */
-    public float getMaximumEnergy() {
-        return amount * energyPerElement;
-    }
-
-    /**
-     * Get the energyPerElement value at a selected time x.
-     *
-     * @param timestep int
-     * @return energyPerElement value
-     */
-    public float getOverallEnergyAtTimeStep(int timestep) {
-       return ((float) amount) * energyPerElement * curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
-    }
     /**
      * Get the energyPerElement currently(at given time step) available
      */
     public float getEnergyAtTimeStep(int timestep) {
-    	return amount * energyPerElement * this.curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
+    	return energy * this.curveSample[IndexTranslator.getEffectiveIndex(this, timestep)];
     }
 
 
@@ -324,9 +273,8 @@ public class HolonElement implements LocalMode, GraphEditable{
         sb.append("id=").append(id)
                 .append(", eleName=").append(eleName)
                 .append(", parentName=").append(parentObject.getName())
-                .append(", amount=").append(amount)
                 .append(", active=").append(active)
-                .append(", energyPerElement used=").append(energyPerElement);
+                .append(", energyPerElement used=").append(energy);
         sb.append("]");
 
         return sb.toString();
@@ -362,8 +310,8 @@ public class HolonElement implements LocalMode, GraphEditable{
 	
 	//interfaces.GraphEditable
 	@Override
-	public Graphtype getGraphType() {
-		return Graphtype.doubleGraph;
+	public GraphType getGraphType() {
+		return GraphType.doubleGraph;
 	}
 
 

+ 15 - 89
src/classes/HolonObject.java

@@ -18,12 +18,6 @@ import java.util.List;
 public class HolonObject extends AbstractCanvasObject { 
     /* Array of all consumers */
     private List<HolonElement> elements = new ArrayList<HolonElement>();
-    /* Array for tracking Production */
-    private float[] trackingProd;
-    /* Array for tracking Consumption */
-    private float[] trackingCons;
-    /* Total Flexibility */
-    private float totalFlex;
     
     /**
      * Constructor Set by default the name of the object equals to the category
@@ -33,8 +27,6 @@ public class HolonObject extends AbstractCanvasObject {
      */
     public HolonObject(String objName) {
         super(objName);
-        setTrackingProd(new float[100]);
-        setTrackingCons(new float[100]);
     }
 
     /**
@@ -47,8 +39,6 @@ public class HolonObject extends AbstractCanvasObject {
         for(HolonElement ele : obj.getElements()) {
         	this.addElement(new HolonElement(ele));
         }
-        setTrackingProd(new float[100]);
-        setTrackingCons(new float[100]);
     }
 
  
@@ -72,16 +62,21 @@ public class HolonObject extends AbstractCanvasObject {
         elements.add(element);
         element.parentObject = this;
     }
-
+    
     /**
-     * deletes Element at a given index.
+     * remove an Element to the Object.
      *
-     * @param idx index
+     * @param element the Element to add
      */
-    public void deleteElement(int idx) {
-    	elements.remove(idx);
+    public void removeElement(HolonElement element) {
+        elements.remove(element);
+        element.parentObject = null;
     }
-    
+
+    public void removeElement(int index) {
+    	HolonElement ele = elements.remove(index);
+    	ele.parentObject = null;
+	}
 
     
 
@@ -249,78 +244,11 @@ public class HolonObject extends AbstractCanvasObject {
 
 
 
-    /**
-     * Get the Array Production
-     */
-    public float[] getTrackingProd() {
-        return this.trackingProd;
-    }
 
-    /**
-     * Set the Array Production
-     */
-    public void setTrackingProd(float[] arr) {
-        this.trackingProd = arr;
-    }
 
-    /**
-     * Get the Array Consumption
-     */
-    public float[] getTrackingCons() {
-        return this.trackingCons;
-    }
 
-    /**
-     * Set the Array Consumption
-     */
-    public void setTrackingCons(float[] arr) {
-        this.trackingCons = arr;
-    }
-
-    /**
-     * Get the Array Consumption
-     */
-    public float getTotalFlex() {
-        return totalFlex;
-    }
-
-    /**
-     * Set the Array Consumption
-     */
-    public void setTotalFlex(float totalFlex) {
-        this.totalFlex = totalFlex;
-    }
-
-
-
-
-    /**
-     * If the user track any HolonObject the tracking information will be
-     * updated. (If the HolonObject enters into the untracked state, the array
-     * will be reseted)
-     */
-
-    public void updateTrackingInfo() {
-        float[] tempProd = new float[100];
-        float[] tempCons = new float[100];
-        for (int i = 0; i < 100; i++) {
-            float valueProd = 0;
-            float valueCons = 0;
-            for (HolonElement e : getElements()) {
-                if (e.isActive() && e.isProducer()) {
-                    valueProd += e.getOverallEnergyAtTimeStep(i);
-                }
-                if (e.isActive() && e.isConsumer()) {
-                    valueCons += e.getOverallEnergyAtTimeStep(i);
-                }
-            }
-            tempProd[i] = valueProd;
-            tempCons[i] = valueCons;
-        }
-        this.trackingProd = tempProd;
-        this.trackingCons = tempCons;
-    }
 
+   
 
     public String toString() {
         StringBuilder sb = new StringBuilder();
@@ -342,10 +270,6 @@ public class HolonObject extends AbstractCanvasObject {
         return sb.toString();
     }
     
-    @Override
-	public HolonObject makeCopy(){
-		return new HolonObject(this);
-	}
 
 	public int getNumberOfActiveElements() {
 		return (int) elements.stream().filter(ele -> ele.isActive()).count();
@@ -356,10 +280,12 @@ public class HolonObject extends AbstractCanvasObject {
 	}
 	
 	public int getNumberOfElements() {
-		return (int) elements.stream().count();
+		return elements.size();
 	}
 
 	public void setElements(List<HolonElement> list) {
 		this.elements = list;
 	}
+
+	
 }

+ 5 - 10
src/classes/HolonSwitch.java

@@ -7,9 +7,9 @@ import java.util.LinkedList;
 import java.util.ListIterator;
 
 import com.google.gson.annotations.Expose;
-import interfaces.GraphEditable;
 import interfaces.LocalMode;
-import ui.view.IndexTranslator;
+import interfaces.TimelineDependent;
+import ui.controller.IndexTranslator;
 
 /**
  * The class HolonSwitch represents a Switch, which can be turned on and off.
@@ -17,7 +17,7 @@ import ui.view.IndexTranslator;
  * @author Gruppe14
  *
  */
-public class HolonSwitch extends AbstractCanvasObject implements LocalMode, GraphEditable {
+public class HolonSwitch extends AbstractCanvasObject implements TimelineDependent {
 
 	/**
 	 * The class HolonSwitch represents an Object in the system, that has the
@@ -86,7 +86,6 @@ public class HolonSwitch extends AbstractCanvasObject implements LocalMode, Grap
 	 */
 	public HolonSwitch(AbstractCanvasObject obj) {
 		super(obj);
-		System.out.println("SwitchCopy?");
 		HolonSwitch copyObj = (HolonSwitch)obj;
 		setLocalPeriod(copyObj.getLocalPeriod());
 		setUseLocalPeriod(copyObj.isUsingLocalPeriod());
@@ -244,8 +243,8 @@ public class HolonSwitch extends AbstractCanvasObject implements LocalMode, Grap
 
 	//interfaces.GraphEditable
 	@Override
-	public Graphtype getGraphType() {
-		return Graphtype.boolGraph;
+	public GraphType getGraphType() {
+		return GraphType.boolGraph;
 	}
 
 	@Override
@@ -308,10 +307,6 @@ public class HolonSwitch extends AbstractCanvasObject implements LocalMode, Grap
 		this.localPeriodActive=state;
 	}
 	
-	@Override
-	public HolonSwitch makeCopy(){
-		return new HolonSwitch(this);
-	}
 	
 		
 	public String toString() {

+ 1 - 5
src/classes/Node.java

@@ -34,9 +34,5 @@ public class Node extends AbstractCanvasObject {
 	public String toString(){
 		return "Node ID:" + super.id;
 	}
-	
-	@Override
-	public AbstractCanvasObject makeCopy() {
-		return new Node(this);
-	}
+
 }

+ 1 - 1
src/classes/comparator/UnitGraphPointComperator.java

@@ -2,7 +2,7 @@ package classes.comparator;
 
 import java.util.Comparator;
 
-import classes.UnitGraphPoint;
+import ui.view.inspector.UnitGraphPoint;
 
 
 public class UnitGraphPointComperator implements Comparator<UnitGraphPoint>{

+ 2 - 2
src/classes/comparator/elementComparator/ElemCompOnEnergy.java

@@ -12,8 +12,8 @@ public class ElemCompOnEnergy extends ElementComparator {
 	@Override
 	public int compare(HolonElement a, HolonElement b) {
 
-		float verbrauchA = a.getEnergyPerElement();
-		float verbrauchB = b.getEnergyPerElement();
+		float verbrauchA = a.getEnergy();
+		float verbrauchB = b.getEnergy();
 		if (verbrauchA < verbrauchB)
 			return -1;
 		if (verbrauchA > verbrauchB)

+ 0 - 18
src/classes/comparator/elementComparator/ElemCompOnObj.java

@@ -1,18 +0,0 @@
-package classes.comparator.elementComparator;
-
-import classes.HolonElement;
-
-public class ElemCompOnObj extends ElementComparator {
-
-	@Override
-	public int compare(HolonElement a, HolonElement b) {
-
-		String objNameA = a.getObjName();
-		String objNameB = b.getObjName();
-		if(objNameA == null)return -1;
-		if (objNameB == null)return 1;
-		return objNameA.compareTo(objNameB);
-
-	}
-
-}

+ 0 - 20
src/classes/comparator/elementComparator/ElemCompOnQuantity.java

@@ -1,20 +0,0 @@
-package classes.comparator.elementComparator;
-
-import classes.HolonElement;
-
-public class ElemCompOnQuantity extends ElementComparator {
-
-	@Override
-	public int compare(HolonElement a, HolonElement b) {
-
-		float amountA = a.getAmount();
-		float amountB = b.getAmount();
-		if (amountA < amountB)
-			return -1;
-		if (amountA > amountB)
-			return 1;
-		return 0;
-
-	}
-
-}

+ 5 - 3
src/interfaces/GraphEditable.java

@@ -8,19 +8,21 @@ import java.util.LinkedList;
  * @author Tom Troppmann
  *
  */
-public interface GraphEditable {
 
+
+
+public interface GraphEditable {
 	/**
 	 * all types of graphs
 	 */
-	public static enum Graphtype {
+	public static enum GraphType {
 		boolGraph, doubleGraph
 	}
 	/**
 	 * Determine what type the Graph have.
 	 * @return the type of the Graph
 	 */
-	Graphtype getGraphType();
+	GraphType getGraphType();
 	/**
 	 * Getter for the graph.
 	 * @return The list of all graph points.

+ 1 - 0
src/interfaces/GraphListener.java

@@ -4,6 +4,7 @@ import classes.AbstractCanvasObject;
 
 import java.util.ArrayList;
 
+//TODO delete
 public interface GraphListener {
 
     void repaintTree();

+ 3 - 0
src/interfaces/TimelineDependent.java

@@ -0,0 +1,3 @@
+package interfaces;
+
+public interface TimelineDependent extends GraphEditable, LocalMode {}

+ 51 - 32
src/ui/controller/CanvasController.java

@@ -2,17 +2,20 @@ package ui.controller;
 
 import java.awt.Point;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
 import java.util.ListIterator;
+import java.util.stream.Collectors;
 
+import classes.AbstractCanvasObject;
 import classes.Edge;
-import classes.Node;
 import classes.GroupNode;
-import classes.AbstractCanvasObject;
 import classes.HolonObject;
 import classes.HolonSwitch;
+import classes.Node;
 import interfaces.ObjectListener;
 import ui.model.Model;
+import ui.view.main.GUI;
 import utility.Vector2Int;
 
 /**
@@ -24,7 +27,7 @@ public class CanvasController {
 
 	private Model model;
 	private MultiPurposeController mpC;
-
+    private GUI gui;
 	/**
 	 * Constructor.
 	 * 
@@ -90,9 +93,6 @@ public class CanvasController {
 				replaceObjectOnCanvas(toBeReplaced, object);
 			}
 		}
-		
-		
-		notifyObjListeners();
 	}
 
 	/**
@@ -117,14 +117,6 @@ public class CanvasController {
 		model.getObjectListeners().add(objLis);
 	}
 
-	/**
-	 * notifies all listeners about changes in the Canvas.
-	 */
-	public void notifyObjListeners() {
-		for (ObjectListener l : model.getObjectListeners()) {
-			l.onChange(model.getObjectsOnCanvas());
-		}
-	}
 
 	/**
 	 * Deletes an CpsObject on the Canvas and its connections.
@@ -137,7 +129,15 @@ public class CanvasController {
 		mpC.decIdx(obj.getId(), model.getCvsObjIdx());
 		model.getCvsObjIdx().remove(obj.getId());
 		model.getObjectsOnCanvas().remove(obj);
-		notifyObjListeners();
+	}
+	
+	public void deleteObjectsOnCanvas(Collection<AbstractCanvasObject> objects) {
+		for(AbstractCanvasObject obj: objects) {
+			removeAllConnectionsFromObject(obj);
+			mpC.decIdx(obj.getId(), model.getCvsObjIdx());
+			model.getCvsObjIdx().remove(obj.getId());
+			model.getObjectsOnCanvas().remove(obj);
+		}
 	}
 
 	/**
@@ -196,7 +196,7 @@ public class CanvasController {
 	 *            the mouse Position
 	 */
 	public void pasteObjects(Point p) {
-		model.getSelectedCpsObjects().clear();
+		model.getSelectedObjects().clear();
 		AbstractCanvasObject tCps = null;
 		int x = Integer.MAX_VALUE, y = Integer.MAX_VALUE;
 
@@ -210,7 +210,6 @@ public class CanvasController {
 			}
 		}
 
-		ArrayList<AbstractCanvasObject> tempList = new ArrayList<>();
 		// Objects
 		for (AbstractCanvasObject cps : model.getClipboradObjects()) {
 			if (cps instanceof HolonObject) {
@@ -222,22 +221,21 @@ public class CanvasController {
 			}
 			tCps.setPosition(new Vector2Int(p.x + (cps.getPosition().getX() - x), p.y + (cps.getPosition().getY() - y)));
 			tCps.setSav(cps.getSav());
-			tempList.add(tCps);
 			addObject(tCps, false);
 		}
 
 		// Edges
-		boolean newEdge = true;
+
 		for (AbstractCanvasObject cps : model.getClipboradObjects()) {
 			for (Edge e : cps.getConnectedTo()) {
 				// A and B of e in the copied Elements?
-				if (model.getClipboradObjects().indexOf(e.getA()) != -1
-						&& model.getClipboradObjects().indexOf(e.getB()) != -1) {
-					AbstractCanvasObject a = tempList.get(model.getClipboradObjects().indexOf(e.getA()));
-					AbstractCanvasObject b = tempList.get(model.getClipboradObjects().indexOf(e.getB()));
+				if (model.getClipboradObjects().contains(e.getA())
+						&& model.getClipboradObjects().contains(e.getB())) {
+					AbstractCanvasObject a = e.getA();
+					AbstractCanvasObject b = e.getB();
+					boolean newEdge = true;
 					// was this Edge created or not?
-					for (Edge et : tempList.get(model.getClipboradObjects().indexOf(cps)).getConnectedTo()) {
-						//TODO Changed et to etA is this right?
+					for (Edge et : cps.getConnectedTo()) {
 						for (Edge etA : et.getA().getConnectedTo()) {
 							if (etA.getA() == a && etA.getB() == b) {
 								newEdge = false;
@@ -250,12 +248,10 @@ public class CanvasController {
 						}
 					}
 					if (newEdge) {
-						Edge tempE = new Edge(tempList.get(model.getClipboradObjects().indexOf(e.getA())), // A
-								tempList.get(model.getClipboradObjects().indexOf(e.getB())), /* B */
+						Edge tempE = new Edge(a, b,
 								e.getCapacity());
 						addEdgeOnCanvas(tempE);
 					}
-					newEdge = true;
 				}
 			}
 		}
@@ -265,15 +261,13 @@ public class CanvasController {
 	/**
 	 * Cut all Selected Objects.
 	 */
-	@SuppressWarnings("unchecked")
 	public void cutObjects() {
-		model.setClipboradObjects((ArrayList<AbstractCanvasObject>) model.getSelectedCpsObjects().clone());
-
+		model.setClipboradObjects(model.getSelectedObjects().stream().collect(Collectors.toSet()));
 		for (AbstractCanvasObject cps : model.getClipboradObjects()) {
 			deleteObjectOnCanvas(cps);
 		}
 
-		model.getSelectedCpsObjects().clear();
+		model.getSelectedObjects().clear();
 	}
 
 	
@@ -305,6 +299,29 @@ public class CanvasController {
 		}
 	}
 	
+	public void updateOutliner(SimulationManager manager ) {
+		gui.updateOutliners(manager.getActualDecorState());
+	}
+	
+	public void updateFlexWindow() {
+		gui.updateFlexWindows();
+	}
+	
+	
+	public void updateCanvas() {
+		gui.repaintCanvas();
+	}
+	public GUI getGui() {
+		return gui;
+	}
+
+	public void guiDisable(boolean state) {
+		gui.guiDisable(state);
+	}
+	
+	public void setGui(GUI gui) {
+		this.gui = gui;
+	}
 	
 	
 	/**
@@ -325,5 +342,7 @@ public class CanvasController {
 		model.setCanvasImageWidth(width);
 		model.setCanvasImageHeight(height);
 	}
+
+	
 	
 }

+ 8 - 9
src/ui/controller/CategoryController.java

@@ -10,7 +10,7 @@ import classes.HolonObject;
 import classes.HolonSwitch;
 import classes.Pair;
 import ui.model.Model;
-import utility.Event;
+import utility.events.Event;
 
 /**
  * Controller for the Categories.
@@ -129,12 +129,11 @@ public class CategoryController {
 		int i = 0;
 		boolean updateElementSaves = false;
 		String name = "";
-		while (mpC.searchCatObj(category, object.getObjName()) != null) {
+		while (mpC.searchCatObj(category, object.getName()) != null) {
 			updateElementSaves = true;
-			if (object.getObjName().contains("_"))
-				object.setObjName(object.getObjName().substring(0, object.getObjName().indexOf('_')));
-			name = object.getObjName() + "_" + i;
-			object.setObjName(name);
+			if (object.getName().contains("_"))
+				object.setName(object.getName().substring(0, object.getName().indexOf('_')));
+			name = object.getName() + "_" + i;
 			object.setName(name);
 			i++;
 		}
@@ -143,7 +142,7 @@ public class CategoryController {
 				e.setSaving(new Pair<String,String>(e.getSaving().getKey(), name));
 			}
 		}
-		category.getObjIdx().put(object.getObjName(), category.getObjects().size());
+		category.getObjIdx().put(object.getName(), category.getObjects().size());
 		category.getObjects().add(object);
 	}
 
@@ -195,8 +194,8 @@ public class CategoryController {
 	 */
 	public void removeObject(Category category, AbstractCanvasObject cps) {
 
-		mpC.decIdx(cps.getObjName(), category.getObjIdx());
-		category.getObjIdx().remove(cps.getObjName());
+		mpC.decIdx(cps.getName(), category.getObjIdx());
+		category.getObjIdx().remove(cps.getName());
 		category.getObjects().remove(cps);
 		OnCategoryChanged.broadcast();
 	}

+ 15 - 12
src/ui/controller/ClipboardController.java

@@ -33,9 +33,10 @@ public class ClipboardController {
     private HashMap<Integer, Integer> eleIDMap;
     private String sav;
     private Point point;
+	private SimulationManager simManager;
 
     ClipboardController(Model model, SaveController store, LoadController load, CanvasController cvs,
-                        ObjectController obj, NodeController uppC, MultiPurposeController mp) {
+                        ObjectController obj, NodeController uppC, SimulationManager simManager) {
         this.model = model;
         this.store = store;
         this.load = load;
@@ -43,6 +44,7 @@ public class ClipboardController {
         this.objC = obj;
         this.uppC = uppC;
         this.clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
+        this.simManager = simManager;
         parser = new JsonParser();
     }
 
@@ -58,13 +60,12 @@ public class ClipboardController {
         store.initNumeration();
 
         file.add("SAV", new JsonPrimitive((upperNode == null ? "CVS" : "" + upperNode.getId())));
-        Vector2Int pos = uppC.calculatePos(model.getSelectedCpsObjects());
+        Vector2Int pos = uppC.calculatePos(model.getSelectedObjects());
         file.add("CENTER", model.getGson().toJsonTree(pos, Vector2Int.class));
 
-        for (AbstractCanvasObject abs : model.getSelectedCpsObjects()) {
+        for (AbstractCanvasObject abs : model.getSelectedObjects()) {
             queue.add(abs);
         }
-        System.out.println("heiCopy");
         while (!queue.isEmpty()) {
 
             u = queue.pop();
@@ -125,7 +126,7 @@ public class ClipboardController {
 
         HashMap<Integer, AbstractCanvasObject> objDispatch = new HashMap<>();
         HashMap<Integer, HolonElement> eleDispatch = new HashMap<>();
-        model.getSelectedCpsObjects().clear();
+        model.getSelectedObjects().clear();
 
         objIDMap = new HashMap<>();
         eleIDMap = new HashMap<>();
@@ -138,7 +139,7 @@ public class ClipboardController {
         // for selecting Cps
         getObjectsInDepth();
         forwardEdges(edges, json, objDispatch, upperNode);
-
+        this.simManager.calculateStateForTimeStep(model.getCurrentIteration(), true);
     }
 
     /**
@@ -146,7 +147,7 @@ public class ClipboardController {
      */
     void cut(GroupNode upperNode) {
         copy(upperNode);
-        for (AbstractCanvasObject abs : model.getSelectedCpsObjects()) {
+        for (AbstractCanvasObject abs : model.getSelectedObjects()) {
             if (upperNode == null)
                 cvsC.deleteObjectOnCanvas(abs);
             else
@@ -155,6 +156,8 @@ public class ClipboardController {
             if (abs instanceof GroupNode)
                 cvsC.bfsNodeCleaner((GroupNode) abs);
         }
+        model.getSelectedObjects().clear();
+        this.simManager.calculateStateForTimeStep(model.getCurrentIteration(), true);
 
     }
 
@@ -210,7 +213,7 @@ public class ClipboardController {
             else
                 uppC.addObjectInUpperNode(temp, upperNode, false);
             // mark the Pasted Objects
-            model.getSelectedCpsObjects().add(temp);
+            model.getSelectedObjects().add(temp);
         } else {
             // else look up the table and put it into the right Uppernode
             GroupNode temp2 = (GroupNode) objDispatch.get(objIDMap.get(Integer.parseInt(temp.getSav())));
@@ -379,8 +382,8 @@ public class ClipboardController {
      * Adds all Objects in Depth into Clipboardobjects preemptive when objects are selected
      */
     void getObjectsInDepth() {
-        model.setClipboradObjects(new ArrayList<>());
-        for (AbstractCanvasObject obj : model.getSelectedCpsObjects()) {
+        model.getClipboradObjects().clear();
+        for (AbstractCanvasObject obj : model.getSelectedObjects()) {
             clipboadDepth(obj);
         }
     }
@@ -429,8 +432,8 @@ public class ClipboardController {
         if (y < 0)
             y = 0 + model.getScaleDiv2() + 1;
         if (upperNode != null) {
-            if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
-                x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
+            if (x < model.getScaleDiv2() + 1)
+                x = model.getScaleDiv2() + 1;
         } else if (x < 0)
             x = 0 + model.getScaleDiv2() + 1;
         if (x > model.getCanvasX())

+ 774 - 813
src/ui/controller/Control.java

@@ -1,10 +1,14 @@
 package ui.controller;
+
 import java.awt.Point;
 import java.awt.datatransfer.UnsupportedFlavorException;
 import java.io.File;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 
 import javax.swing.JFrame;
@@ -22,9 +26,9 @@ import classes.HolonObject;
 import classes.Node;
 import ui.model.Model;
 import ui.model.Model.FairnessModel;
-import ui.view.CreateTemplatePopUp;
-import ui.view.GUI;
-import utility.Event;
+import ui.view.dialog.CreateTemplatePopUp;
+import ui.view.main.GUI;
+import utility.events.Event;
 
 /**
  * The Class represents the controller in the model, controller view Pattern.
@@ -33,849 +37,806 @@ import utility.Event;
  */
 public class Control {
 
-    private final MultiPurposeController multiPurposeController;
-    private final CategoryController categoryController;
-    private final ObjectController objectController;
-    private final CanvasController canvasController;
-    private final GlobalController globalController;
-    private final SaveController saveController;
-    private final LoadController loadController;
-    private final AutoSaveController autoSaveController;
-    private final NodeController nodeController;
-    private final ClipboardController clipboardController;
-    private final HolonCanvasController holonCanvasController;
-    private Model model;
-    private GUI gui;
-    private SimulationManager simulationManager;
-    private String autosaveDir = "";
-    private String categoryDir = "";
-    private String otherDir = "";
-    private String dimensionsFileName = "dimensions";
-    private int rand;
-
-    
-    public Event OnCategoryChanged = new Event();
-    /**
-     * Constructor.
-     *
-     * @param model the Model
-     */
-    public Control(Model model) {
-        this.model = model;
-
-        this.multiPurposeController = new MultiPurposeController(model);
-        this.categoryController = new CategoryController(model, multiPurposeController, this);
-        this.objectController = new ObjectController(model, multiPurposeController);
-        this.canvasController = new CanvasController(model, multiPurposeController);
-        this.globalController = new GlobalController(model);
-        this.saveController = new SaveController(model);
-        this.nodeController = new NodeController(model, canvasController, multiPurposeController);
-        this.loadController = new LoadController(model, categoryController, canvasController, objectController,
-                nodeController, multiPurposeController);
-        this.simulationManager = new SimulationManager(model);
-        this.autoSaveController = new AutoSaveController(model);
-        this.clipboardController = new ClipboardController(model, saveController, loadController, canvasController,
-                objectController, nodeController, multiPurposeController);
-        this.holonCanvasController = new HolonCanvasController(model);
-
-        autosaveDir = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
-        categoryDir = System.getProperty("user.home") + "/.config/HolonGUI/Category/";
-        otherDir = System.getProperty("user.home") + "/.config/HolonGUI/Other/";
-        File autoSave = new File(autosaveDir);
-        File category = new File(categoryDir);
-        File other = new File(otherDir);
-        // deleteDirectory(dest);
-        autoSave.mkdirs();
-        category.mkdirs();
-        other.mkdirs();
-        createAutoRandom();
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Generate random number, so that every instance of the program has unique
-     * save files
-     */
-    private void createAutoRandom() {
-        rand = (int) (Math.random() * 1000);
-        while (new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
-            rand = (int) Math.random() * 1000;
-        }
-    }
-
-    /**
-     * Delete a Directory.
-     *
-     * @param path to delete
-     */
-    public void deleteDirectory(File path) {
-        if (path.exists()) {
-            File[] files = path.listFiles();
-            for (File file : files) {
-                if (file.isDirectory()) {
-                    deleteDirectory(file);
-                } else {
-                    if (file.getName().contains("" + rand))
-                        file.delete();
-                }
-            }
-            // path.delete();
-        }
-    }
+	private final MultiPurposeController multiPurposeController;
+	private final CategoryController categoryController;
+	private final ObjectController objectController;
+	private final CanvasController canvasController;
+	private final GlobalController globalController;
+	private final SaveController saveController;
+	private final LoadController loadController;
+	private final AutoSaveController autoSaveController;
+	private final NodeController nodeController;
+	private final ClipboardController clipboardController;
+	private Model model;
+
+	private SimulationManager simulationManager;
+	private String autosaveDir = "";
+	private String categoryDir = "";
+	private String otherDir = "";
+	private String dimensionsFileName = "dimensions";
+	private int rand;
+
+	public Event OnCategoryChanged = new Event();
+	public Event OnSelectionChanged = new Event();
+
+	/**
+	 * Constructor.
+	 *
+	 * @param model the Model
+	 */
+	public Control(Model model) {
+		this.model = model;
+
+		this.multiPurposeController = new MultiPurposeController(model);
+		this.categoryController = new CategoryController(model, multiPurposeController, this);
+		this.objectController = new ObjectController(model, multiPurposeController);
+		this.canvasController = new CanvasController(model, multiPurposeController);
+		this.globalController = new GlobalController(model);
+		this.saveController = new SaveController(model);
+		this.nodeController = new NodeController(model, canvasController, multiPurposeController);
+		this.loadController = new LoadController(model, categoryController, canvasController, objectController,
+				nodeController, multiPurposeController);
+		this.simulationManager = new SimulationManager(model);
+		this.autoSaveController = new AutoSaveController(model);
+		this.clipboardController = new ClipboardController(model, saveController, loadController, canvasController,
+				objectController, nodeController, this.simulationManager);
+
+		autosaveDir = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
+		categoryDir = System.getProperty("user.home") + "/.config/HolonGUI/Category/";
+		otherDir = System.getProperty("user.home") + "/.config/HolonGUI/Other/";
+		File autoSave = new File(autosaveDir);
+		File category = new File(categoryDir);
+		File other = new File(otherDir);
+		// deleteDirectory(dest);
+		autoSave.mkdirs();
+		category.mkdirs();
+		other.mkdirs();
+		createAutoRandom();
+
+		tryAutoSave();
+	}
+
+	/**
+	 * Generate random number, so that every instance of the program has unique save
+	 * files
+	 */
+	private void createAutoRandom() {
+		rand = (int) (Math.random() * 1000);
+		while (new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
+			rand = (int) Math.random() * 1000;
+		}
+	}
+
+	/**
+	 * Delete a Directory.
+	 *
+	 * @param path to delete
+	 */
+	public void deleteDirectory(File path) {
+		if (path.exists()) {
+			File[] files = path.listFiles();
+			for (File file : files) {
+				if (file.isDirectory()) {
+					deleteDirectory(file);
+				} else {
+					if (file.getName().contains("" + rand))
+						file.delete();
+				}
+			}
+			// path.delete();
+		}
+	}
 
 	/* Operations for searching */
 
-    /**
-     * Search for Object by ID.
-     *
-     * @param id the id of the Object
-     * @return the CpsObject
-     */
-    public AbstractCanvasObject searchByID(int id) {
-        return multiPurposeController.searchByID(id);
-    }
-
-    /**
-     * Search for Object by ID in upperNode
-     *
-     * @param id the id of the Object
-     * @return the CpsObject
-     */
-    public AbstractCanvasObject searchByIDUpperNode(int id, GroupNode upperNode) {
-        return multiPurposeController.searchByIDUpperNode(id, upperNode);
-    }
-
-    public AbstractCanvasObject searchTracked(int id) {
-        return multiPurposeController.searchByID(id);
-    }
-
-    /**
-     * Search for Object in a Category.
-     *
-     * @param category name of the Category
-     * @param object   Name of the Object
-     * @return The Object
-     */
-    public AbstractCanvasObject searchCategoryObject(String category, String object) {
-        return multiPurposeController.searchCatObj(multiPurposeController.searchCat(category), object);
-    }
-
-    /**
-     * search for category.
-     *
-     * @param cat name of the Category
-     * @return the Category
-     */
-    public Category searchCategory(String cat) {
-        return multiPurposeController.searchCat(cat);
-    }
+	/**
+	 * Search for Object by ID.
+	 *
+	 * @param id the id of the Object
+	 * @return the CpsObject
+	 */
+	public AbstractCanvasObject searchByID(int id) {
+		return multiPurposeController.searchByID(id);
+	}
+
+	/**
+	 * Search for Object by ID in upperNode
+	 *
+	 * @param id the id of the Object
+	 * @return the CpsObject
+	 */
+	public AbstractCanvasObject searchByIDUpperNode(int id, GroupNode upperNode) {
+		return multiPurposeController.searchByIDUpperNode(id, upperNode);
+	}
+
+	public AbstractCanvasObject searchTracked(int id) {
+		return multiPurposeController.searchByID(id);
+	}
+
+	/**
+	 * Search for Object in a Category.
+	 *
+	 * @param category name of the Category
+	 * @param object   Name of the Object
+	 * @return The Object
+	 */
+	public AbstractCanvasObject searchCategoryObject(String category, String object) {
+		return multiPurposeController.searchCatObj(multiPurposeController.searchCat(category), object);
+	}
+
+	/**
+	 * search for category.
+	 *
+	 * @param cat name of the Category
+	 * @return the Category
+	 */
+	public Category searchCategory(String cat) {
+		return multiPurposeController.searchCat(cat);
+	}
 
 	/* Operations for Categories and Objects */
 
-    /**
-     * init default category and objects.
-     *
-     * @throws IOException
-     */
-    public void resetCategorys() throws IOException {
-        categoryController.initCategories();
-        objectController.initHolonElements();
-        saveCategory();
-    }
-
-    /**
-     * Adds New Category into Model.
-     *
-     * @param cat name of the new Category
-     * @throws IOException
-     */
-    public void addCategory(String cat) throws IOException {
-        categoryController.addNewCategory(cat);
-        saveCategory();
-    }
-
-    /**
-     * Gives all Category as String
-     * @return a array of strings from all Categorys
-     */
-    public String[] getCategoriesStrings()
-    {
-		return ((ArrayList<String>) categoryController.getCategories().stream().map(c -> c.getName()).collect(Collectors.toList())).toArray(new String[categoryController.getCategories().size()]);
-    }
-    /**
-     * Add new Holon Object to a Category.
-     *
-     * @param cat Category
-     * @param obj New Object Name
-     * @param list Array of Elements
-     * @param img the image Path
-     * @throws IOException
-     */
-    public void addObject(Category cat, String obj, List<HolonElement> list, String img) throws IOException {
-        categoryController.addNewHolonObject(cat, obj, list, img);
-        saveCategory();
-    }
-
-
-    /**
-     * Add new Holon Switch to a Category.
-     *
-     * @param cat Category
-     * @param obj New Object Name
-     * @throws IOException
-     */
-    public void addSwitch(Category cat, String obj) throws IOException {
-        categoryController.addNewHolonSwitch(cat, obj, "/Images/switch-on.png");
-        saveCategory();
-    }
-   
-    
-    /**
-     * delete a given Category.
-     *
-     * @param cat the Category
-     * @throws IOException
-     */
-    public void deleteCategory(String cat) throws IOException {
-        categoryController.deleteCategory(cat);
-        saveCategory();
-    }
-
-    /**
-     * Delete an Object from a Category.
-     *
-     * @param cat the Category
-     * @param obj the Object
-     * @throws IOException
-     */
-    public void delObjectCategory(String cat, String obj) throws IOException {
-        categoryController.deleteObject(cat, obj);
-        saveCategory();
-    }
-
-    /**
-     * deletes a selectedObject.
-     *
-     * @param obj Cpsobject
-     */
-    public void deleteSelectedObject(AbstractCanvasObject obj) {
-        objectController.deleteSelectedObject(obj);
-    }
-
-    /**
-     * add an Object to selectedObject.
-     *
-     * @param obj AbstractCpsobject
-     */
-    public void addSelectedObject(AbstractCanvasObject obj) {
-        objectController.addSelectedObject(obj);
-    }
+	/**
+	 * init default category and objects.
+	 *
+	 * @throws IOException
+	 */
+	public void resetCategorys() throws IOException {
+		categoryController.initCategories();
+		objectController.initHolonElements();
+		saveCategory();
+	}
 
-	/* Operations for Canvas */
+	/**
+	 * Adds New Category into Model.
+	 *
+	 * @param cat name of the new Category
+	 * @throws IOException
+	 */
+	public void addCategory(String cat) throws IOException {
+		categoryController.addNewCategory(cat);
+		saveCategory();
+	}
+
+	/**
+	 * Gives all Category as String
+	 * 
+	 * @return a array of strings from all Categorys
+	 */
+	public String[] getCategoriesStrings() {
+		return ((ArrayList<String>) categoryController.getCategories().stream().map(c -> c.getName())
+				.collect(Collectors.toList())).toArray(new String[categoryController.getCategories().size()]);
+	}
+
+	/**
+	 * Add new Holon Object to a Category.
+	 *
+	 * @param cat  Category
+	 * @param obj  New Object Name
+	 * @param list Array of Elements
+	 * @param img  the image Path
+	 * @throws IOException
+	 */
+	public void addObject(Category cat, String obj, List<HolonElement> list, String img) throws IOException {
+		categoryController.addNewHolonObject(cat, obj, list, img);
+		saveCategory();
+	}
 
-    /**
-     * Add a new Object.
-     *
-     * @param object the Object
-     */
-    public void addObjectCanvas(AbstractCanvasObject object) {
-        canvasController.addNewObject(object);
-        calculateStateAndVisualForTimeStep(model.getCurIteration());
-        if (!(object instanceof Node)) {
-            try {
-                autoSave();
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-        }
-    }
-
-    /**
-     * Deletes an CpsObject on the Canvas and its connections.
-     *
-     * @param obj  AbstractCpsObject
-     * @param save
-     */
-    public void delCanvasObject(AbstractCanvasObject obj, boolean save) {
-        canvasController.deleteObjectOnCanvas(obj);
-        if (obj instanceof GroupNode) {
-        	canvasController.bfsNodeCleaner((GroupNode) obj);        	
-        }
-        calculateStateAndVisualForCurrentTimeStep();
-        if (save)
-            try {
-                autoSave();
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-    }
-
-    /**
-     * Replaces {@code toBeReplaced} by {@code by} on the canvas
-     * @param toBeReplaced the object that will be replaced
-     * @param by the object that will replace it
-     */
-    public void replaceCanvasObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
-    	canvasController.replaceObjectOnCanvas(toBeReplaced, by);
-    	try {
-            autoSave();
-        } catch (IOException e) {
-        	System.out.println("Error by Replacing "+toBeReplaced.toString() + " by " + by.toString());
-            e.printStackTrace();
-        }
-    }
-    
-    /**
-     * Add an edge to the Canvas.
-     *
-     * @param edge the edge
-     */
-    public void addEdgeOnCanvas(Edge edge) {
-        canvasController.addEdgeOnCanvas(edge);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Removes an Edge from the Canvas.
-     *
-     * @param edge the edge to remove
-     */
-    public void removeEdgesOnCanvas(Edge edge) {
-        canvasController.removeEdgesOnCanvas(edge);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Set the selected Edge.
-     *
-     * @param edge that is selected
-     */
-    public void setSelecteEdge(Edge edge) {
-        model.setSelectedEdge(edge);
-    }
-
-    /**
-     * Returns the ID of the selected Object 0 = no Object is selected.
-     *
-     * @param id the ID of the selected Object
-     */
-    public void setSelectedObjectID(int id) {
-        objectController.setSelectedObjectID(id);
-    }
+	/**
+	 * Add new Holon Switch to a Category.
+	 *
+	 * @param cat Category
+	 * @param obj New Object Name
+	 * @throws IOException
+	 */
+	public void addSwitch(Category cat, String obj) throws IOException {
+		categoryController.addNewHolonSwitch(cat, obj, "/Images/switch-on.png");
+		saveCategory();
+	}
+
+	/**
+	 * delete a given Category.
+	 *
+	 * @param cat the Category
+	 * @throws IOException
+	 */
+	public void deleteCategory(String cat) throws IOException {
+		categoryController.deleteCategory(cat);
+		saveCategory();
+	}
+
+	/**
+	 * Delete an Object from a Category.
+	 *
+	 * @param cat the Category
+	 * @param obj the Object
+	 * @throws IOException
+	 */
+	public void delObjectCategory(String cat, String obj) throws IOException {
+		categoryController.deleteObject(cat, obj);
+		saveCategory();
+	}
+
+	/**
+	 * removes a selectedObject from selection.
+	 *
+	 * @param obj Cpsobject
+	 */
+	public void removeObjectsFromSelection(Collection<AbstractCanvasObject> objects) {
+		for (AbstractCanvasObject object : objects) {
+			objectController.removeObjectFromSelection(object);
+		}
+		OnSelectionChanged.broadcast();
+	}
+
+	/**
+	 * removes a selectedObject from selection.
+	 *
+	 * @param obj Cpsobject
+	 */
+	public void removeObjectFromSelection(AbstractCanvasObject obj) {
+		objectController.removeObjectFromSelection(obj);
+		OnSelectionChanged.broadcast();
+	}
+
+
+	/**
+	 * add an Object to selectedObject.
+	 *
+	 * @param obj AbstractCpsobject
+	 */
+	public void addSelectedObject(AbstractCanvasObject obj) {
+		objectController.addSelectedObject(obj);
+		OnSelectionChanged.broadcast();
+	}
+
+	public void addSelectedObjects(Collection<AbstractCanvasObject> objects) {
+		objectController.addSelectedObjects(objects);
+		OnSelectionChanged.broadcast();
+	}
 
+	public void clearSelection() {
+		if(!model.getSelectedObjects().isEmpty()) {
+			model.getSelectedObjects().clear();
+			OnSelectionChanged.broadcast();
+		}
+	}
 	
+	/**
+	 * This method is primarily for the multi-selection. It adds unselected objects
+	 * to the selection and Removes selected objects from the selection. Like the
+	 * normal OS Desktop selection.
+	 * 
+	 * @param objects
+	 */
+	public void toggleSelectedObjects(Collection<AbstractCanvasObject> objects) {
+		Set<AbstractCanvasObject> intersection = new HashSet<>(objects);
+		intersection.retainAll(model.getSelectedObjects());
+		model.getSelectedObjects().addAll(objects);
+		model.getSelectedObjects().removeAll(intersection);
+		OnSelectionChanged.broadcast();
+	}
+
+	/* Operations for Canvas */
+
+	/**
+	 * Add a new Object.
+	 *
+	 * @param object the Object
+	 */
+	public void addObjectCanvas(AbstractCanvasObject object) {
+		canvasController.addNewObject(object);
+		calculateStateAndVisualForTimeStep(model.getCurrentIteration());
+		if (!(object instanceof Node)) {
+			tryAutoSave();
+		}
+	}
+
+	/**
+	 * Deletes an CpsObject on the Canvas and its connections.
+	 *
+	 * @param obj  AbstractCpsObject
+	 * @param save
+	 */
+	public void delCanvasObject(AbstractCanvasObject obj, boolean save) {
+		canvasController.deleteObjectOnCanvas(obj);
+		if (obj instanceof GroupNode) {
+			canvasController.bfsNodeCleaner((GroupNode) obj);
+		}
+		calculateStateAndVisualForCurrentTimeStep();
+		if (save) {
+			tryAutoSave();
+		}
+	}
+
+	public void delCanvasObjects(Collection<AbstractCanvasObject> objects) {
+		canvasController.deleteObjectsOnCanvas(objects);
+		calculateStateAndVisualForCurrentTimeStep();
+		tryAutoSave();
+	}
+
+	/**
+	 * Replaces {@code toBeReplaced} by {@code by} on the canvas
+	 * 
+	 * @param toBeReplaced the object that will be replaced
+	 * @param by           the object that will replace it
+	 */
+	public void replaceCanvasObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
+		canvasController.replaceObjectOnCanvas(toBeReplaced, by);
+		tryAutoSave();
+	}
+
+	/**
+	 * Add an edge to the Canvas.
+	 *
+	 * @param edge the edge
+	 */
+	public void addEdgeOnCanvas(Edge edge) {
+		canvasController.addEdgeOnCanvas(edge);
+		tryAutoSave();
+	}
+
+	/**
+	 * Removes an Edge from the Canvas.
+	 *
+	 * @param edge the edge to remove
+	 */
+	public void removeEdgesOnCanvas(Edge edge) {
+		canvasController.removeEdgesOnCanvas(edge);
+		tryAutoSave();
+	}
+
+	/**
+	 * Set the selected Edge.
+	 *
+	 * @param edge that is selected
+	 */
+	public void setSelecteEdge(Edge edge) {
+		model.setSelectedEdge(edge);
+	}
+
+	/**
+	 * Returns the ID of the selected Object 0 = no Object is selected.
+	 *
+	 * @param id the ID of the selected Object
+	 */
+	public void setSelectedObjectID(int id) {
+		objectController.setSelectedObjectID(id);
+	}
 
 	/* Operations for Objects and Elements */
 
-    /**
-     * Add a new Element into a Object on the Canvas.
-     *
-     * @param objectId  the Object ID
-     * @param ele       the Name of the Element
-     * @param amount    the Amount
-     * @param energy    the Energy
-     * @param elementId the Element ID
-     */
-    public void addElementCanvasObject(int objectId, String ele, int amount, float energy, int elementId) {
-        objectController.addNewElementIntoCanvasObject(objectId, ele, amount, energy, elementId);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Add a new Element into a Object in Category.
-     *
-     * @param catName the Category
-     * @param objName the Object
-     * @param eleName the Element Name
-     * @param amount  the amount
-     * @param energy  the Energy
-     */
-    public void addElementCategoryObject(String catName, String objName, String eleName, int amount, float energy) {
-        objectController.addNewElementIntoCategoryObject(catName, objName, eleName, amount, energy);
-    }
-
-    /**
-     * deletes a Element from a given Canvas Object.
-     *
-     * @param id        the ID
-     * @param elementid the Element ID
-     */
-    public void deleteElementCanvas(int id, int elementid) {
-        objectController.deleteElementInCanvas(id, elementid);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-    /**
-     * Returns SCALE.
-     *
-     * @return SCALE
-     */
-    public int getScale() {
-        return globalController.getScale();
-    }
-
-    /**
-     * Changes the value of SCALE and SCALEDIV2.
-     *
-     * @param s Scale
-     */
-    public void setScale(int s) {
-        globalController.setScale(s);
-    }
-
-    /**
-     * Returns SCALE Divided by 2.
-     *
-     * @return SCALE Divided by 2
-     */
-    public int getScaleDiv2() {
-        return globalController.getScaleDiv2();
-    }
-
-    /**
-     * sets the current Iteration.
-     *
-     * @param curit the current Iteration
-     */
-    public void setCurIteration(int curit) {
-        globalController.setCurIteration(curit);
-        //getGui().getTimePanel().getTimeSlider().setValue(curit);
-    }
-
-    /**
-     * Writes the current State of the Modelling into a JSON File which can be
-     * loaded.
-     *
-     * @param path the Path
-     * @throws IOException exception
-     */
-    public void saveFile(String path) throws IOException, ArchiveException {
-        saveController.writeSave(path);
-    }
-
-    /**
-     * Reads the the Save File and load the state into the Model.
-     *
-     * @param path the Path
-     * @throws IOException      exception
-     * @throws ArchiveException
-     */
-    public void loadFile(String path) throws IOException, ArchiveException {
-        loadController.readSave(path);
-        saveCategory();
-        autoSave();
-    }
-
-    /**
-     * Reads the Json File from Autosave
-     *
-     * @param path
-     * @throws IOException
-     */
-    public void loadAutoSave(String path) throws IOException {
-        loadController.readJson(path);
-    }
-
-    public ArrayList<Integer> loadSavedWindowDimensionsIfExistent() {
-        try {
-            return loadController.readWindowDimensions(otherDir + dimensionsFileName);
-        } catch (Exception e) {
-            return new ArrayList<>();
-        }
-    }
-
-    /**
-     * calculates the flow of the edges and the supply for objects for the
-     * current Timestep.
-     */
-    public void calculateStateAndVisualForCurrentTimeStep() {
-    	calculateStateAndVisualForTimeStep(model.getCurIteration());
-    }
-
-    public void calculateStateOnlyForCurrentTimeStep() {
-    	simulationManager.calculateStateForTimeStep(model.getCurIteration(), false);
-    }
-    /**
-     * calculates the flow of the edges and the supply for objects.
-     *
-     * @param x current Iteration
-     */
-    public void calculateStateAndVisualForTimeStep(int x) {
-        simulationManager.calculateStateForTimeStep(x, true);
-        updateOutliner();
-        updateFlexWindow();
-        this.updateCanvas();
-    }
-
-    /**
-     * resets the whole State of the simulation including a reset of all Edges
-     * to the default "is working" state
-     */
-    public void resetSimulation() {
-      simulationManager.resetFlexManager();
-    }
-
-
-    /**
-     * make an autosave.
-     *
-     * @throws IOException Exception
-     */
-    public void autoSave() throws IOException {
-        autoSaveController.increaseAutoSaveNr();
-        saveController.writeAutosave(autosaveDir + rand + autoSaveController.getAutoSaveNr());
-        if (autoSaveController.allowed()) {
-            new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr() - globalController.getNumbersOfSaves()))
-                    .delete();
-        }
-    }
-
-    /**
-     * find all old auto save files (with a file-name, that does not contain the current rand)
-     *
-     * @return a list of files, that are not from the current run
-     */
-    public ArrayList<File> filterOldAutoSaveFiles() {
-        File[] files = new File(autosaveDir).listFiles();
-        ArrayList<File> oldAutoSaves = new ArrayList<>();
-
-        for (File file : files) {
-            if (!file.getName().contains(String.valueOf(rand)))
-                oldAutoSaves.add(file);
-        }
-
-        return oldAutoSaves;
-    }
-
-    /**
-     * deletes the old autosave files
-     */
-    public void deleteObsoleteAutoSaveFiles() {
-        for (File file : filterOldAutoSaveFiles()) {
-            file.delete();
-        }
-    }
-
-    public void saveCategory() throws IOException {
-        saveController.writeCategory(categoryDir + "Category.json");
-    }
-
-    public void savePosAndSizeOfWindow(int x, int y, int width, int height) throws IOException, ArchiveException {
-        saveController.writeWindowStatus(otherDir + dimensionsFileName, x, y, width, height);
-    }
-
-    /**
-     * Returns the undo save.
-     *
-     * @return the undo save
-     */
-    public String getUndoSave() {
-        autoSaveController.decreaseAutoSaveNr();
-        if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
-            autoSaveController.increaseAutoSaveNr();
-        }
-        return autosaveDir + rand + (autoSaveController.getAutoSaveNr());
-    }
-
-    /**
-     * Returns the redo save.
-     *
-     * @return the redo save
-     */
-    public String getRedoSave() {
-        autoSaveController.increaseAutoSaveNr();
-        if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
-            autoSaveController.decreaseAutoSaveNr();
-
-            // if it still does not exist, try old autosaves
-            if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
-                ArrayList<File> oldAutoSaves = filterOldAutoSaveFiles();
-                if (oldAutoSaves.size() > 0) {
-                    return autosaveDir + oldAutoSaves.get(oldAutoSaves.size() - 1).getName();
-                }
-            }
-        }
-        return autosaveDir + rand + (autoSaveController.getAutoSaveNr());
-    }
-
-    /**
-     * Getter for Model.
-     *
-     * @return the Model
-     */
-    public Model getModel() {
-        return model;
-    }
-
-    /**
-     * get the Simulation Manager.
-     *
-     * @return the Simulation Manager
-     */
-    public SimulationManager getSimManager() {
-        return simulationManager;
-    }
-
-  
-    /**
-     * Set the timerSpeed.
-     *
-     * @param t interval in ms
-     */
-    public void setTimerSpeed(int t) {
-        globalController.setTimerSpeed(t);
-    }
-
-    /**
-     * Set the Canvas X Size.
-     *
-     * @param canvasX the cANVAS_X to set
-     */
-    public void setCanvasX(int canvasX) {
-        globalController.setCanvasX(canvasX);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    /**
-     * Set the Canvas Y Size.
-     *
-     * @param canvasY the cANVAS_Y to set
-     */
-    public void setCanvasY(int canvasY) {
-        globalController.setCanvasY(canvasY);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void setMaxCapacity(float cap) {
-        globalController.setMaxCapacity(cap);
-    }
-
-   
-
-
-    // ========================== MANAGING TRACKED OBJECTS END ================
-
-    /**
-     * Controlling Nodes of Nodes
-     */
-
-    public void addUpperNode(String nodeName, GroupNode upperNode, ArrayList<AbstractCanvasObject> toGroup) {
-        nodeController.doUpperNode(nodeName, upperNode, toGroup);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void ungroupGroupNode(GroupNode node, GroupNode upperNode) {
-        nodeController.undoUpperNode(node, upperNode);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void addObjUpperNode(AbstractCanvasObject object, GroupNode upperNode) {
-    	nodeController.addObjectInUpperNode(object, upperNode, true);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void delObjUpperNode(AbstractCanvasObject object, GroupNode upperNode) {
-    	nodeController.deleteObjectInUpperNode(object, upperNode);
-        if (object instanceof GroupNode)
-            canvasController.bfsNodeCleaner((GroupNode) object);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-
-    }
-
-    /**
-     * Replaces {@code toBePlaced} by {@code by} in {@code upperNode}
-     * @param toBeReplaced
-     * @param by
-     * @param upperNode
-     */
-	public void replaceObjUpperNode(AbstractCanvasObject toBeReplaced,
-			AbstractCanvasObject by, GroupNode upperNode) {
-		nodeController.replaceObjectInUpperNode(toBeReplaced, by, upperNode);
+	/**
+	 * Add a new Element into a Object on the Canvas.
+	 *
+	 * @param objectId  the Object ID
+	 * @param ele       the Name of the Element
+	 * @param energy    the Energy
+	 * @param elementId the Element ID
+	 */
+	public void addElementCanvasObject(int objectId, String ele, float energy, int elementId) {
+		objectController.addNewElementIntoCanvasObject(objectId, ele, energy, elementId);
+		tryAutoSave();
+	}
+
+	/**
+	 * Add a new Element into a Object in Category.
+	 *
+	 * @param catName the Category
+	 * @param objName the Object
+	 * @param eleName the Element Name
+	 * @param amount  the amount
+	 * @param energy  the Energy
+	 */
+	public void addElementCategoryObject(String catName, String objName, String eleName, float energy) {
+		objectController.addNewElementIntoCategoryObject(catName, objName, eleName, energy);
+	}
+
+	/**
+	 * deletes a Element from a given Canvas Object.
+	 *
+	 * @param id        the ID
+	 * @param elementid the Element ID
+	 */
+	public void deleteElementCanvas(int id, int elementid) {
+		objectController.deleteElementInCanvas(id, elementid);
+		tryAutoSave();
+	}
+
+	/**
+	 * Returns SCALE.
+	 *
+	 * @return SCALE
+	 */
+	public int getScale() {
+		return globalController.getScale();
+	}
+
+	/**
+	 * Changes the value of SCALE and SCALEDIV2.
+	 *
+	 * @param s Scale
+	 */
+	public void setScale(int s) {
+		globalController.setScale(s);
+	}
+
+	/**
+	 * Returns SCALE Divided by 2.
+	 *
+	 * @return SCALE Divided by 2
+	 */
+	public int getScaleDiv2() {
+		return globalController.getScaleDiv2();
+	}
+
+	/**
+	 * sets the current Iteration.
+	 *
+	 * @param curit the current Iteration
+	 */
+	public void setCurIteration(int curit) {
+		globalController.setCurIteration(curit);
+		// getGui().getTimePanel().getTimeSlider().setValue(curit);
+	}
+
+	/**
+	 * Writes the current State of the Modelling into a JSON File which can be
+	 * loaded.
+	 *
+	 * @param path the Path
+	 * @throws IOException exception
+	 */
+	public void saveFile(String path) throws IOException, ArchiveException {
+		saveController.writeSave(path);
+	}
+
+	/**
+	 * Reads the the Save File and load the state into the Model.
+	 *
+	 * @param path the Path
+	 * @throws IOException      exception
+	 * @throws ArchiveException
+	 */
+	public void loadFile(String path) throws IOException, ArchiveException {
+		loadController.readSave(path);
+		saveCategory();
+		autoSave();
+	}
+
+	/**
+	 * Reads the Json File from Autosave
+	 *
+	 * @param path
+	 * @throws IOException
+	 */
+	public void loadAutoSave(String path) throws IOException {
+		loadController.readJson(path);
+	}
+
+	public ArrayList<Integer> loadSavedWindowDimensionsIfExistent() {
 		try {
-            autoSave();
-        } catch (IOException e) {
-        	System.out.println("Error by Replacing "+toBeReplaced.toString() 
-        			+ " by " + by.toString() + " in UpperNode " + upperNode.toString());
-            e.printStackTrace();
-        }
-	}
-
-
-
-  
-
-    /**
-     * Get the number of HolonObjects in the given List
-     *
-     * @param list
-     */
-    public int getNumberHolonObjects(ArrayList<AbstractCanvasObject> list) {
-        return objectController.getNumberHolonObjects(list);
-    }
-    
-    /**
-     * Get the number of HolonObjects in the given List
-     *
-     * @param list
-     */
-    public ArrayList<HolonObject> getAllHolonObjects(ArrayList<AbstractCanvasObject> list) {
-        return objectController.getAllHolonObjects(list);
-    }
-
-    /**
-     * Copy all Selected Objects.
-     */
-    public void copy(GroupNode upperNode) {
-        clipboardController.copy(upperNode);
-    }
-
-    public void paste(GroupNode upperNode, Point point)
-            throws JsonParseException, UnsupportedFlavorException, IOException {
-        clipboardController.paste(upperNode, point);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-
-    public void cut(GroupNode upperNode) {
-        clipboardController.cut(upperNode);
-        try {
-            autoSave();
-        } catch (IOException e) {
-            e.printStackTrace();
-        }
-    }
-    
-    /**
-     * creates a new Template for the given cps Object
-     * @param cps Object, which should become a template
-     * @param parentFrame 
-     */
-    public void createTemplate(HolonObject cps, JFrame parentFrame) {
-        CreateTemplatePopUp t = new CreateTemplatePopUp(cps,model,parentFrame,this);
-        t.setVisible(true);
-    }
-
-    public void getObjectsInDepth() {
-        clipboardController.getObjectsInDepth();
-    }
-
-    public float getTotalProduction(ArrayList<AbstractCanvasObject> arrayList) {
-        return holonCanvasController.getTotalProduction(arrayList);
-    }
-
-    public float getTotalConsumption(ArrayList<AbstractCanvasObject> arrayList) {
-        return holonCanvasController.getTotalConsumption(arrayList);
-    }
-
-    public int getTotalElements(ArrayList<AbstractCanvasObject> arrayList) {
-        return holonCanvasController.getTotalElements(arrayList);
-    }
-
-    public int getTotalProducers(ArrayList<AbstractCanvasObject> arrayList) {
-        return holonCanvasController.getTotalProducers(arrayList);
-    }
-
-    public int getActiveElements(ArrayList<AbstractCanvasObject> arrayList) {
-        return holonCanvasController.getActiveElements(arrayList);
-    }
-
-    /**
-     * 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) {
-        canvasController.setBackgroundImage(imagePath, mode, width, height);
-    }
-
-    /**
-     * Sets show
-     * @param showSupplyBars wether the bars should be shown
-     */
+			return loadController.readWindowDimensions(otherDir + dimensionsFileName);
+		} catch (Exception e) {
+			return new ArrayList<>();
+		}
+	}
+
+	/**
+	 * calculates the flow of the edges and the supply for objects for the current
+	 * Timestep.
+	 */
+	public void calculateStateAndVisualForCurrentTimeStep() {
+		calculateStateAndVisualForTimeStep(model.getCurrentIteration());
+	}
+
+	public void calculateStateOnlyForCurrentTimeStep() {
+		simulationManager.calculateStateForTimeStep(model.getCurrentIteration(), false);
+	}
+
+	/**
+	 * calculates the flow of the edges and the supply for objects.
+	 *
+	 * @param x current Iteration
+	 */
+	public void calculateStateAndVisualForTimeStep(int x) {
+		simulationManager.calculateStateForTimeStep(x, true);
+		updateOutliner();
+		updateFlexWindow();
+		this.updateCanvas();
+	}
+
+	/**
+	 * resets the whole State of the simulation including a reset of all Edges to
+	 * the default "is working" state
+	 */
+	public void resetSimulation() {
+		simulationManager.resetFlexManager();
+	}
+
+	/**
+	 * make an autosave.
+	 *
+	 * @throws IOException Exception
+	 */
+	public void autoSave() throws IOException {
+		autoSaveController.increaseAutoSaveNr();
+		saveController.writeAutosave(autosaveDir + rand + autoSaveController.getAutoSaveNr());
+		if (autoSaveController.allowed()) {
+			new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr() - globalController.getNumbersOfSaves()))
+					.delete();
+		}
+	}
+
+	public void tryAutoSave() {
+		try {
+			autoSave();
+		} catch (IOException e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * find all old auto save files (with a file-name, that does not contain the
+	 * current rand)
+	 *
+	 * @return a list of files, that are not from the current run
+	 */
+	public ArrayList<File> filterOldAutoSaveFiles() {
+		File[] files = new File(autosaveDir).listFiles();
+		ArrayList<File> oldAutoSaves = new ArrayList<>();
+
+		for (File file : files) {
+			if (!file.getName().contains(String.valueOf(rand)))
+				oldAutoSaves.add(file);
+		}
+
+		return oldAutoSaves;
+	}
+
+	/**
+	 * deletes the old autosave files
+	 */
+	public void deleteObsoleteAutoSaveFiles() {
+		for (File file : filterOldAutoSaveFiles()) {
+			file.delete();
+		}
+	}
+
+	public void saveCategory() throws IOException {
+		saveController.writeCategory(categoryDir + "Category.json");
+	}
+
+	public void savePosAndSizeOfWindow(int x, int y, int width, int height) throws IOException, ArchiveException {
+		saveController.writeWindowStatus(otherDir + dimensionsFileName, x, y, width, height);
+	}
+
+	/**
+	 * Returns the undo save.
+	 *
+	 * @return the undo save
+	 */
+	public String getUndoSave() {
+		autoSaveController.decreaseAutoSaveNr();
+		if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
+			autoSaveController.increaseAutoSaveNr();
+		}
+		return autosaveDir + rand + (autoSaveController.getAutoSaveNr());
+	}
+
+	/**
+	 * Returns the redo save.
+	 *
+	 * @return the redo save
+	 */
+	public String getRedoSave() {
+		autoSaveController.increaseAutoSaveNr();
+		if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
+			autoSaveController.decreaseAutoSaveNr();
+
+			// if it still does not exist, try old autosaves
+			if (!new File(autosaveDir + rand + (autoSaveController.getAutoSaveNr())).exists()) {
+				ArrayList<File> oldAutoSaves = filterOldAutoSaveFiles();
+				if (oldAutoSaves.size() > 0) {
+					return autosaveDir + oldAutoSaves.get(oldAutoSaves.size() - 1).getName();
+				}
+			}
+		}
+		return autosaveDir + rand + (autoSaveController.getAutoSaveNr());
+	}
+
+	/**
+	 * Getter for Model.
+	 *
+	 * @return the Model
+	 */
+	public Model getModel() {
+		return model;
+	}
+
+	/**
+	 * get the Simulation Manager.
+	 *
+	 * @return the Simulation Manager
+	 */
+	public SimulationManager getSimManager() {
+		return simulationManager;
+	}
+
+	/**
+	 * Set the timerSpeed.
+	 *
+	 * @param t interval in ms
+	 */
+	public void setTimerSpeed(int t) {
+		globalController.setTimerSpeed(t);
+	}
+
+	/**
+	 * Set the Canvas X Size.
+	 *
+	 * @param canvasX the cANVAS_X to set
+	 */
+	public void setCanvasX(int canvasX) {
+		globalController.setCanvasX(canvasX);
+		tryAutoSave();
+	}
+
+	/**
+	 * Set the Canvas Y Size.
+	 *
+	 * @param canvasY the cANVAS_Y to set
+	 */
+	public void setCanvasY(int canvasY) {
+		globalController.setCanvasY(canvasY);
+		tryAutoSave();
+	}
+
+	public void setMaxCapacity(float cap) {
+		globalController.setMaxCapacity(cap);
+	}
+
+	// ========================== MANAGING TRACKED OBJECTS END ================
+
+	/**
+	 * Controlling Nodes of Nodes
+	 */
+
+	public void addUpperNode(String nodeName, GroupNode upperNode, ArrayList<AbstractCanvasObject> toGroup) {
+		nodeController.doUpperNode(nodeName, upperNode, toGroup);
+		tryAutoSave();
+	}
+
+	public void ungroupGroupNode(GroupNode node, GroupNode upperNode) {
+		nodeController.undoUpperNode(node, upperNode);
+		tryAutoSave();
+	}
+
+	public void addObjUpperNode(AbstractCanvasObject object, GroupNode upperNode) {
+		nodeController.addObjectInUpperNode(object, upperNode, true);
+		tryAutoSave();
+	}
+
+	public void delObjUpperNode(AbstractCanvasObject object, GroupNode upperNode) {
+		nodeController.deleteObjectInUpperNode(object, upperNode);
+		if (object instanceof GroupNode)
+			canvasController.bfsNodeCleaner((GroupNode) object);
+		tryAutoSave();
+
+	}
+
+	/**
+	 * Replaces {@code toBePlaced} by {@code by} in {@code upperNode}
+	 * 
+	 * @param toBeReplaced
+	 * @param by
+	 * @param upperNode
+	 */
+	public void replaceObjUpperNode(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by, GroupNode upperNode) {
+		nodeController.replaceObjectInUpperNode(toBeReplaced, by, upperNode);
+		tryAutoSave();
+	}
+
+	/**
+	 * Get the number of HolonObjects in the given List
+	 *
+	 * @param list
+	 */
+	public int getNumberHolonObjects(ArrayList<AbstractCanvasObject> list) {
+		return objectController.getNumberHolonObjects(list);
+	}
+
+
+	/**
+	 * Copy all Selected Objects.
+	 */
+	public void copy(GroupNode upperNode) {
+		clipboardController.copy(upperNode);
+	}
+
+	public void paste(GroupNode upperNode, Point point)
+			throws JsonParseException, UnsupportedFlavorException, IOException {
+		clipboardController.paste(upperNode, point);
+		OnSelectionChanged.broadcast();
+		tryAutoSave();
+	}
+
+	public void cut(GroupNode upperNode) {
+		clipboardController.cut(upperNode);
+		OnSelectionChanged.broadcast();
+		tryAutoSave();
+	}
+
+	/**
+	 * creates a new Template for the given cps Object
+	 * 
+	 * @param cps         Object, which should become a template
+	 * @param parentFrame
+	 */
+	public void createTemplate(HolonObject cps, JFrame parentFrame) {
+		CreateTemplatePopUp t = new CreateTemplatePopUp(cps, model, parentFrame, this);
+		t.setVisible(true);
+	}
+
+	public void getObjectsInDepth() {
+		clipboardController.getObjectsInDepth();
+	}
+
+
+	/**
+	 * 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) {
+		canvasController.setBackgroundImage(imagePath, mode, width, height);
+	}
+
+	/**
+	 * Sets show
+	 * 
+	 * @param showSupplyBars wether the bars should be shown
+	 */
 	public void setShowSupplyBars(boolean showSupplyBars) {
 		globalController.setShowSupplyBars(showSupplyBars);
 	}
-	
+
 	/**
-     * Sets fairness Model
-     * @param fairnessModel that should be used. 
-     */
+	 * Sets fairness Model
+	 * 
+	 * @param fairnessModel that should be used.
+	 */
 	public void setFairnessModel(FairnessModel fairnessModel) {
 		globalController.setFairnessModel(fairnessModel);
 	}
-	
+
 	public void updateOutliner() {
-		gui.updateOutliners(simulationManager.getActualDecorState());
+		this.canvasController.updateOutliner(simulationManager);
 	}
-	
+
 	public void updateFlexWindow() {
-		gui.updateFlexWindows();
+		canvasController.updateFlexWindow();
 	}
-	
-	
+
 	public void updateCanvas() {
-		gui.repaintCanvas();
-		gui.triggerUpdateController(null);
+		canvasController.updateCanvas();
 	}
+
 	public GUI getGui() {
-		return gui;
+		return canvasController.getGui();
 	}
 
 	public void guiDisable(boolean state) {
-		gui.guiDisable(state);
+		canvasController.guiDisable(state);
 	}
-	
+
 	public void setGui(GUI gui) {
-		this.gui = gui;
+		canvasController.setGui(gui);
 	}
+
 	
+
 }

+ 0 - 2
src/ui/controller/FlexManager.java

@@ -43,8 +43,6 @@ public class FlexManager {
 		//because when added not all flexes can see others
 		accessFlexMap.values().stream().forEach(flexWrapper -> flexWrapper.revalidateState());
 	}
-
-	
 	
 	
 	

+ 0 - 236
src/ui/controller/HolonCanvasController.java

@@ -1,236 +0,0 @@
-package ui.controller;
-
-import classes.*;
-import ui.model.Model;
-import utility.Vector2Float;
-
-import java.awt.*;
-import java.util.ArrayList;
-
-public class HolonCanvasController {
-
-	// Ball objects
-	private ArrayList<HolonBody> bodies = new ArrayList<>();
-	private int subCount;
-	private Dimension center;
-	private Model model;
-	private ArrayList<HolonBody> sortedSize = new ArrayList<>();
-	private ArrayList<HolonBody> sortedDist = new ArrayList<>();
-	private int toDrag;
-	private boolean beingDragged;
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param model
-	 *            the Model
-	 * @param mp
-	 *            the MultipurposeController
-	 */
-	public HolonCanvasController(Model model) {
-		this.model = model;
-	}
-
-	// sort the HolonBodys after size
-	public void rearrangeAfterSize() {
-		int j = 0;
-		sortedSize.addAll(bodies);
-		insertionSizeSort(sortedSize);
-		sortedDist.addAll(bodies);
-
-		ArrayList<Vector2Float> pos = insertionDistSort(sortedDist);
-		for (int i = 0; i < subCount; i++) {
-			int ID = sortedSize.get(subCount - 1 - i).getId();
-			for (j = 0; j < subCount; j++) {
-				if (ID == bodies.get(j).getId()) {
-					bodies.get(j).position = pos.get(i);
-					break;
-				}
-			}
-		}
-	}
-
-	public int getActiveElements(ArrayList<AbstractCanvasObject> objects) {
-		int val = 0;
-		for (AbstractCanvasObject obj : objects) {
-			if (obj instanceof HolonObject) {
-				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.isActive()) {
-                        val += 1;
-					}
-				}
-			} else if (obj instanceof GroupNode) {
-				val += getTotalProduction(((GroupNode) obj).getNodes());
-			}
-		}
-		return val;
-	}
-
-	public int getTotalProducers(ArrayList<AbstractCanvasObject> objects) {
-		float val = 0;
-		int prod = 0;
-		int tStep = model.getCurIteration();
-		for (AbstractCanvasObject obj : objects) {
-			if (obj instanceof HolonObject) {
-				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergyAtTimeStep(tStep) > 0 && ele.isActive()) {
-                        val += ele.getEnergyAtTimeStep(tStep) * ele.getAmount();
-                    }
-                }
-				if (val > 0)
-					prod += 1;
-			} else if (obj instanceof GroupNode) {
-				val += getTotalProduction(((GroupNode) obj).getNodes());
-			}
-		}
-		return prod;
-	}
-
-	public int getTotalElements(ArrayList<AbstractCanvasObject> objects) {
-		int val = 0;
-		for (AbstractCanvasObject obj : objects) {
-			if (obj instanceof HolonObject) {
-				val += ((HolonObject) obj).getElements().size();
-			} else if (obj instanceof GroupNode) {
-				val += getTotalConsumption(((GroupNode) obj).getNodes());
-			}
-		}
-		return val;
-	}
-
-	public float getTotalConsumption(ArrayList<AbstractCanvasObject> objects) {
-		float val = 0;
-		int tStep = model.getCurIteration();
-		for (AbstractCanvasObject obj : objects) {
-			if (obj instanceof HolonObject) {
-				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergyAtTimeStep(tStep) < 0 && ele.isActive()) {
-                        val += ele.getEnergyAtTimeStep(tStep) * ele.getAmount();
-                    }
-                }
-			} else if (obj instanceof GroupNode) {
-				val += getTotalConsumption(((GroupNode) obj).getNodes());
-			}
-		}
-		return val;
-	}
-
-	public float getTotalProduction(ArrayList<AbstractCanvasObject> objects) {
-		float val = 0;
-		int tStep = model.getCurIteration();
-		for (AbstractCanvasObject obj : objects) {
-			if (obj instanceof HolonObject) {
-				for (HolonElement ele : ((HolonObject) obj).getElements()) {
-                    if (ele.getEnergyAtTimeStep(tStep) > 0 && ele.isActive()) {
-                        val += ele.getEnergyAtTimeStep(tStep) * ele.getAmount();
-                    }
-                }
-			} else if (obj instanceof GroupNode) {
-				val += getTotalProduction(((GroupNode) obj).getNodes());
-			}
-		}
-		return val;
-	}
-
-	public void updateBodies(float elapsedSeconds) {
-		// step the position of movable objects based off their velocity/gravity
-		// and elapsedTime
-		for (int i = 0; i < subCount; i++) {
-			if (toDrag != bodies.get(i).getId() || !beingDragged) {
-				bodies.get(i).position.setX(
-						(float) (bodies.get(i).position.getX() + (bodies.get(i).velocity.getX() * (elapsedSeconds))
-								- ((bodies.get(i).position.getX() - center.getWidth()) / (50 + subCount))));
-				bodies.get(i).position.setY(
-						(float) (bodies.get(i).position.getY() + (bodies.get(i).velocity.getY() * (elapsedSeconds))
-								- ((bodies.get(i).position.getY() - center.getHeight()) / (50 + subCount))));
-				float epsilon = 0.000009f;
-				if (Math.abs(bodies.get(i).velocity.getX()) < epsilon)
-					bodies.get(i).velocity.setX(0);
-				if (Math.abs(bodies.get(i).velocity.getY()) < epsilon)
-					bodies.get(i).velocity.setY(0);
-			}
-		}
-		checkCollisions();
-	}
-
-	// Insertion sort for Sweep and Prune
-	public void insertionSort(ArrayList<HolonBody> a) {
-		for (int p = 1; p < subCount; p++) {
-			Comparable<HolonBody> tmp = a.get(p);
-			int j = p;
-
-			for (; j > 0 && tmp.compareTo(a.get(j - 1)) < 0; j--)
-				a.set(j, a.get(j - 1));
-
-			a.set(j, (HolonBody) tmp);
-		}
-	}
-
-	// Insertion sort for subnet size
-	private void insertionSizeSort(ArrayList<HolonBody> a) {
-		for (int p = 1; p < subCount; p++) {
-			HolonBody tmp = a.get(p);
-			int j = p;
-
-			for (; j > 0 && tmp.compareSizeTo(a.get(j - 1)) < 0; j--)
-				a.set(j, a.get(j - 1));
-
-			a.set(j, (HolonBody) tmp);
-		}
-	}
-
-	// Insertion sort for HolonBody distance
-	private ArrayList<Vector2Float> insertionDistSort(ArrayList<HolonBody> a) {
-		ArrayList<Vector2Float> pos = new ArrayList<>();
-		for (int p = 1; p < subCount; p++) {
-			HolonBody tmp = a.get(p);
-			int j = p;
-
-			for (; j > 0 && tmp.compareDistTo(a.get(j - 1), center) < 0; j--)
-				a.set(j, a.get(j - 1));
-
-			a.set(j, (HolonBody) tmp);
-		}
-		for (int i = 0; i < subCount; i++)
-			pos.add(a.get(i).position);
-		return pos;
-	}
-
-	public void checkCollisions() {
-		insertionSort(bodies);
-
-		for (int i = 0; i < subCount; i++) {
-			// Ball to Ball collision
-			float radiusI = bodies.get(i).getRadius();
-			float xPlusradius = (bodies.get(i).position.getX() + radiusI);
-			float yPlusradius = (bodies.get(i).position.getY() + radiusI);
-			float yMinusRadius = (bodies.get(i).position.getY()- radiusI);
-			for (int j = i + 1; j < subCount; j++) {
-				float radiusJ = bodies.get(j).getRadius();
-				if (xPlusradius < (bodies.get(j).position.getX()- radiusJ))
-					break;
-
-				if (yPlusradius < (bodies.get(j).position.getY()- radiusJ)
-					|| (bodies.get(j).position.getY() + radiusJ) < yMinusRadius)
-					continue;
-
-				bodies.get(i).resolveCollision(bodies.get(j));
-
-			}
-		}
-
-	}
-
-	public ArrayList<HolonBody> getBodies() {
-		return bodies;
-	}
-
-	public void setDrag(boolean beingDragged) {
-		this.beingDragged = beingDragged;
-	}
-
-	public void setBodyToDrag(int i) {
-		this.toDrag = i;
-	}
-
-}

+ 2 - 4
src/ui/view/IndexTranslator.java → src/ui/controller/IndexTranslator.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.controller;
 
 import interfaces.LocalMode;
 import ui.model.Model;
@@ -6,8 +6,6 @@ import ui.model.Model;
 
 public class IndexTranslator {
 	public static int STANDARD_GRAPH_ACCURACY = 100;
-	// TODO assign model
-	// this refrence should be updated with the model
 	public static Model model;
 	   /**
      * Determines the index of the internal value array
@@ -24,7 +22,7 @@ public class IndexTranslator {
     		return timeStep % e.getLocalPeriod()* 100 /e.getLocalPeriod();
     	}
     	else {
-    		return timeStep * 100 / (model == null?STANDARD_GRAPH_ACCURACY:model.getIterations());
+    		return timeStep * 100 / (model == null?STANDARD_GRAPH_ACCURACY:model.getMaxIterations());
     	}
     }
 }

+ 24 - 33
src/ui/controller/LoadController.java

@@ -1,6 +1,7 @@
 package ui.controller;
 
 import classes.*;
+import classes.HolonElement.Priority;
 import classes.IdCounter.CounterType;
 
 import com.google.gson.JsonElement;
@@ -166,22 +167,18 @@ public class LoadController {
         for (String key : keys) {
             if (key.contains("CATEGORY"))
                 loadCategory(json.get(key));
-            if (key.contains("CGOBJECT"))
+            else if (key.contains("CGOBJECT"))
                 loadCategoryObject(json.get(key).getAsJsonObject());
-            if (key.contains("CGELEMENT"))
-                loadCategoryElements(json.get(key), eleDispatch);//TODO
-            if (key.contains("CVSOBJECT"))
+            else if (key.contains("CGELEMENT"))
+                loadCategoryElements(json.get(key), eleDispatch);
+            else if (key.contains("CVSOBJECT"))
                 loadCanvasObject(json.get(key).getAsJsonObject(), objDispatch);
-            if (key.contains("CVSELEMENT"))
+            else if (key.contains("CVSELEMENT"))
                 loadCanvasElements(json.get(key), objDispatch, eleDispatch);
-            if (key.contains("SWUNITGRAPH"))
+            else if (key.contains("SWUNITGRAPH"))
                 loadUnitGraph(GRAPHTYPE.SWITCH, json.get(key), objDispatch, null);
-            if (key.contains("ELEUNITGRAPH"))
+            else if (key.contains("ELEUNITGRAPH") && key.contains("ELETESTUNITGRAPH"))
                 loadUnitGraph(GRAPHTYPE.ELEMENT, json.get(key), null, eleDispatch);
-            if (key.contains("ELETESTUNITGRAPH"))
-                loadUnitGraph(GRAPHTYPE.TESTELEMENT, json.get(key), null, eleDispatch);
-            if (key.contains("TRACKED"))
-                loadTracked(json.get(key), objDispatch);
         }
 
     }
@@ -245,8 +242,8 @@ public class LoadController {
         
         temp.setImage(checkOS(temp.getImage()));
         initObjects(temp);
-        if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getObjName()) != null)
-            cgC.deleteObject(temp.getSav(), temp.getObjName());
+        if (mpC.searchCatObj(mpC.searchCat(temp.getSav()), temp.getName()) != null)
+            cgC.deleteObject(temp.getSav(), temp.getName());
         cgC.addObject(mpC.searchCat(temp.getSav()), temp);
 
     }
@@ -267,6 +264,11 @@ public class LoadController {
         	flex.constrainList.forEach(con -> con.fixJson());
         	
         });
+        //Fix old amount
+        JsonElement amount = object.get("properties").getAsJsonObject().get("amount");
+        if(amount != null) {
+        	ele.setEnergyPerElement(amount.getAsInt() * ele.getEnergy());
+        }
         objC.addElementIntoCategoryObject(ele.getSaving().getKey(), ele.getSaving().getValue(), ele);
     }
 
@@ -286,7 +288,6 @@ public class LoadController {
         temp.setImage(checkOS(temp.getImage()));
         if (temp instanceof GroupNode) {
             model.getHashcodeMap().put(jsonObject.get("hash").getAsInt(), (GroupNode) temp);
-            ((GroupNode) temp).setLeftBorder(jsonObject.get("properties").getAsJsonObject().get("leftBorder").getAsInt());
         }
         // if its stored before on the canvas just put it there
         if (temp.getSav().equals("CVS")) {
@@ -336,7 +337,11 @@ public class LoadController {
         	
         });
         
-        
+        //Fix old amount
+        JsonElement amount = object.get("properties").getAsJsonObject().get("amount");
+        if(amount != null) {
+        	ele.setEnergyPerElement(amount.getAsInt() * ele.getEnergy());
+        }
         // id which Object it was stored before
         int stored = object.get("ID").getAsInt();
         // lookup that object
@@ -386,7 +391,6 @@ public class LoadController {
         }  
         
        
-
         switch (type) {
             case SWITCH:
                 HolonSwitch sw = (HolonSwitch) objDispatch.get(sav);
@@ -394,9 +398,6 @@ public class LoadController {
                 sw.sampleGraph();
                 break;
             case ELEMENT:
-            	System.out.println("Write me new");
-            	break;
-            case TESTELEMENT:
                 HolonElement ele1 = eleDispatch.get(sav);
                 ele1.setGraphPoints(graphpointTEST);
                 ele1.sampleGraph();
@@ -406,19 +407,6 @@ public class LoadController {
         }
     }
 
-    private void loadTracked(JsonElement jsonElement, HashMap<Integer, AbstractCanvasObject> objDispatch) {
-        JsonObject object = jsonElement.getAsJsonObject();
-        List<String> keys = getKeys(object);
-
-        for (String k : keys) {
-            int id = object.get(k).getAsInt();
-            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();
@@ -507,6 +495,9 @@ public class LoadController {
         ele.flexList = new ArrayList<Flexibility>();
         ele.setGraphPoints(new LinkedList<>());
         ele.reset();
+        if(ele.getPriority() == null) {
+        	ele.setPriority(Priority.Low);
+        }
     }
 
     /**
@@ -542,7 +533,7 @@ public class LoadController {
     }
 
     public enum GRAPHTYPE {
-        SWITCH, ELEMENT, TESTELEMENT
+        SWITCH, ELEMENT
     }
 
 }

+ 6 - 9
src/ui/controller/NodeController.java

@@ -9,6 +9,7 @@ import utility.Vector2Int;
 
 import java.awt.*;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.LinkedList;
 
 
@@ -128,11 +129,8 @@ class NodeController {
 	/**
 	 * Calculate new Position of the Upper Node
 	 */
-    Vector2Int calculatePos(ArrayList<AbstractCanvasObject> toGroup) {
-
+    Vector2Int calculatePos(Collection<AbstractCanvasObject> toGroup) {
 		Vector2Int pos = new Vector2Int(0, 0);
-
-		// sum(x0 .. xn) / numOfPos, y analog
 		for (AbstractCanvasObject abs : toGroup) {
 			pos = pos.add(abs.getPosition());
 		}
@@ -248,9 +246,8 @@ class NodeController {
 			}
 			
 			/** if edge from an object to itself -> remove it */
-			if(e.getA() == e.getB())
-				;//TODO Delte me if not nessesary
-			else/** else add edge to 'by' */
+			/** else add edge to 'by' */
+			if(e.getA() != e.getB())
 				by.addConnection(e);
 		}
 		/** delete 'toBeReplaced' new empty connections, to prevent Nullpointer*/
@@ -274,8 +271,8 @@ class NodeController {
 		if (y < 0)
 			y = 0 + model.getScaleDiv2() + 1;
 		if (upperNode != null) {
-			if (x < upperNode.getLeftBorder() + model.getScaleDiv2() + 1)
-				x = upperNode.getLeftBorder() + model.getScaleDiv2() + 1;
+			if (x < model.getScaleDiv2() + 1)
+				x = model.getScaleDiv2() + 1;
 		} else if (x < 0)
 			x = 0 + model.getScaleDiv2() + 1;
 		if (x > model.getCanvasX())

+ 188 - 187
src/ui/controller/ObjectController.java

@@ -1,9 +1,14 @@
 package ui.controller;
 
-import classes.*;
-import ui.model.Model;
-
 import java.util.ArrayList;
+import java.util.Collection;
+
+import classes.AbstractCanvasObject;
+import classes.GroupNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import classes.Pair;
+import ui.model.Model;
 
 /**
  * Controller for Objects.
@@ -12,188 +17,184 @@ import java.util.ArrayList;
  */
 public class ObjectController {
 
-    private Model model;
-    private MultiPurposeController mpC;
-
-    /**
-     * Constructor.
-     *
-     * @param model Model
-     * @param mp    MultiPurposeController
-     */
-    public ObjectController(Model model, MultiPurposeController mp) {
-        this.model = model;
-        this.mpC = mp;
-        initHolonElements();
-    }
-
-    /**
-     * init default Power supply of the Power Plant.
-     */
-    public void initHolonElements() {
-        addNewElementIntoCategoryObject("Energy", "Power Plant", "Power", 1, 10000);
-        addNewElementIntoCategoryObject("Building", "House", "TV", 2, -250);
-        addNewElementIntoCategoryObject("Building", "House", "Fridge", 1, -500);
-        addNewElementIntoCategoryObject("Building", "House", "Radio", 1, -100);
-        addNewElementIntoCategoryObject("Building", "House", "PC", 3, -250);
-        addNewElementIntoCategoryObject("Building", "House", "Light", 5, -50);
-        addNewElementIntoCategoryObject("Building", "House", "Solar Panels", 1, 300);
-    }
-
-    /**
-     * Adds Element into a Object.
-     *
-     * @param object  the Object
-     * @param element the Element
-     */
-    public void addElement(HolonObject object, HolonElement element) {
-        object.addElement(element);
-    }
-
-    /**
-     * Adds Element into a Object on the Canvas.
-     *
-     * @param object  the Object
-     * @param element the Element
-     */
-    public void addElementIntoCanvasObject(HolonObject object, HolonElement element) {
-        element.setSaving(null);
-        addElement(object, element);
-    }
-
-    /**
-     * Add a new Element into a Object on the Canvas.
-     *
-     * @param objectId  the Object ID
-     * @param element   the Name of the Element
-     * @param amount    the Amount
-     * @param energy    the Energy
-     * @param elementId the Element ID
-     */
-    public void addNewElementIntoCanvasObject(int objectId, String element, int amount, float energy, int elementId) {
-    	HolonObject hObject;
-    	if (mpC.searchByID(objectId) == null) {
-        	hObject = (HolonObject) model.getSelectedCpsObjects().get(0);
-        } else {
-        	hObject = ((HolonObject) mpC.searchByID(objectId));
-        }
-        HolonElement ele = new HolonElement(hObject, element, amount, energy, elementId);
-        addElementIntoCanvasObject(hObject, ele);
-    }
-
-    /**
-     * Add Element into a Object in Category.
-     *
-     * @param category the Category
-     * @param object   the Object
-     * @param element  the Element
-     */
-    public void addElementIntoCategoryObject(String category, String object, HolonElement element) {
-        element.setSaving(new Pair<>(category, object));
-        addElement((HolonObject) mpC.searchCatObj(mpC.searchCat(category), object), element);
-    }
-
-    /**
-     * Add a new Element into a Object in Category.
-     *
-     * @param category the Category
-     * @param object   the Object
-     * @param element  the Element Name
-     * @param energy   the Energy
-     * @param amount   the amount
-     */
-    public void addNewElementIntoCategoryObject(String category, String object, String element, int amount,
-                                                float energy) {
-
-        HolonElement ele = new HolonElement((HolonObject) mpC.searchCatObj(mpC.searchCat(category), object),element, amount, energy);
-        addElementIntoCategoryObject(category, object, ele);
-    }
-
-    /**
-     * deletes a Element from a given Object.
-     *
-     * @param obj the Oject
-     * @param ele the Element
-     */
-    public void deleteElement(HolonObject obj, HolonElement ele) {
-        obj.getElements().remove(ele);
-    }
-
-    /**
-     * deletes a selectedObject.
-     *
-     * @param obj Cpsobject
-     */
-    public void deleteSelectedObject(AbstractCanvasObject obj) {
-        model.getSelectedCpsObjects().remove(obj);
-    }
-
-    /**
-     * add an Object to selectedObject.
-     *
-     * @param obj AbstractCpsobject
-     */
-    public void addSelectedObject(AbstractCanvasObject obj) {
-        model.getSelectedCpsObjects().add(obj);
-    }
-
-    /**
-     * deletes a Element from a given Canvas Object.
-     *
-     * @param id    the ID
-     * @param eleid the Element ID
-     */
-    public void deleteElementInCanvas(int id, int eleid) {
-        HolonObject object = (HolonObject) mpC.searchByID(id);
-        if (object == null) {
-            object = (HolonObject) model.getSelectedCpsObjects().get(0);
-        }
-        HolonElement element = mpC.searchEleById(object, eleid);
-        deleteElement(object, element);
-    }
-
-    /**
-     * Returns the ID of the selected Object 0 = no Object is selected.
-     *
-     * @param id the ID of the selected Object
-     */
-    public void setSelectedObjectID(int id) {
-        model.setSelectedObjectID(id);
-    }
-
-    /**
-     * Get the number of HolonObjects in the given List
-     *
-     * @param list
-     */
-    public int getNumberHolonObjects(ArrayList<AbstractCanvasObject> list) {
-        int val = 0;
-
-        for (AbstractCanvasObject obj : list) {
-            if (obj instanceof HolonObject) {
-                val++;
-            } else if (obj instanceof GroupNode) {
-                val += getNumberHolonObjects(((GroupNode) obj).getNodes());
-            }
-        }
-        return val;
-    }
-/**
- * Helper added by Rolf TODO: macht hier vll keinen Sinn...
- */
-    public ArrayList<HolonObject> getAllHolonObjects(ArrayList<AbstractCanvasObject> list){
-    	ArrayList<HolonObject> allObj = new ArrayList<HolonObject>();
-    	
-    	for (AbstractCanvasObject obj : list) {
-            if (obj instanceof HolonObject) {
-                allObj.add((HolonObject)obj);
-            } else if (obj instanceof GroupNode) {
-                 allObj.addAll(getAllHolonObjects(((GroupNode) obj).getNodes()));
-            }
-        }
-    	
-    	
-    	return allObj;
-    }
-   
+	private Model model;
+	private MultiPurposeController mpC;
+
+	/**
+	 * Constructor.
+	 *
+	 * @param model Model
+	 * @param mp    MultiPurposeController
+	 */
+	public ObjectController(Model model, MultiPurposeController mp) {
+		this.model = model;
+		this.mpC = mp;
+		initHolonElements();
+	}
+
+	/**
+	 * init default Power supply of the Power Plant.
+	 */
+	public void initHolonElements() {
+		addNewElementIntoCategoryObject("Energy", "Power Plant", "Power", 10000);
+		addNewElementIntoCategoryObject("Building", "House", "TV", -250);
+		addNewElementIntoCategoryObject("Building", "House", "TV", -250);
+		addNewElementIntoCategoryObject("Building", "House", "Fridge", -500);
+		addNewElementIntoCategoryObject("Building", "House", "Radio", -100);
+		addNewElementIntoCategoryObject("Building", "House", "PC", -250);
+		addNewElementIntoCategoryObject("Building", "House", "PC", -250);
+		addNewElementIntoCategoryObject("Building", "House", "PC", -250);
+		addNewElementIntoCategoryObject("Building", "House", "Light", -50);
+		addNewElementIntoCategoryObject("Building", "House", "Light", -50);
+		addNewElementIntoCategoryObject("Building", "House", "Light", -50);
+		addNewElementIntoCategoryObject("Building", "House", "Light", -50);
+		addNewElementIntoCategoryObject("Building", "House", "Light", -50);
+		addNewElementIntoCategoryObject("Building", "House", "Solar Panels", 300);
+	}
+
+	/**
+	 * Adds Element into a Object.
+	 *
+	 * @param object  the Object
+	 * @param element the Element
+	 */
+	public void addElement(HolonObject object, HolonElement element) {
+		object.addElement(element);
+	}
+
+	/**
+	 * Adds Element into a Object on the Canvas.
+	 *
+	 * @param object  the Object
+	 * @param element the Element
+	 */
+	public void addElementIntoCanvasObject(HolonObject object, HolonElement element) {
+		element.setSaving(null);
+		addElement(object, element);
+	}
+
+	/**
+	 * Add a new Element into a Object on the Canvas.
+	 *
+	 * @param objectId  the Object ID
+	 * @param element   the Name of the Element
+	 * @param amount    the Amount
+	 * @param energy    the Energy
+	 * @param elementId the Element ID
+	 */
+	public void addNewElementIntoCanvasObject(int objectId, String element, float energy, int elementId) {
+		HolonObject hObject = (HolonObject) mpC.searchByID(objectId);
+		if (hObject == null) {
+			hObject = (HolonObject) model.getSelectedObjects().stream().findFirst().get();
+		}
+		HolonElement ele = new HolonElement(hObject, element, energy, elementId);
+		addElementIntoCanvasObject(hObject, ele);
+	}
+
+	/**
+	 * Add Element into a Object in Category.
+	 *
+	 * @param category the Category
+	 * @param object   the Object
+	 * @param element  the Element
+	 */
+	public void addElementIntoCategoryObject(String category, String object, HolonElement element) {
+		element.setSaving(new Pair<>(category, object));
+		addElement((HolonObject) mpC.searchCatObj(mpC.searchCat(category), object), element);
+	}
+
+	/**
+	 * Add a new Element into a Object in Category.
+	 *
+	 * @param category the Category
+	 * @param object   the Object
+	 * @param element  the Element Name
+	 * @param energy   the Energy
+	 */
+	public void addNewElementIntoCategoryObject(String category, String object, String element, float energy) {
+
+		HolonElement ele = new HolonElement((HolonObject) mpC.searchCatObj(mpC.searchCat(category), object), element,
+				energy);
+		addElementIntoCategoryObject(category, object, ele);
+	}
+
+	/**
+	 * deletes a Element from a given Object.
+	 *
+	 * @param obj the Oject
+	 * @param ele the Element
+	 */
+	public void deleteElement(HolonObject obj, HolonElement ele) {
+		obj.getElements().remove(ele);
+	}
+
+	/**
+	 * deletes a selectedObject.
+	 *
+	 * @param obj Cpsobject
+	 */
+	public void removeObjectFromSelection(AbstractCanvasObject obj) {
+		model.getSelectedObjects().remove(obj);
+	}
+
+	/**
+	 * add an Object to selectedObject.
+	 *
+	 * @param obj AbstractCpsobject
+	 */
+	public void addSelectedObject(AbstractCanvasObject obj) {
+		model.getSelectedObjects().add(obj);
+	}
+
+	/**
+	 * add an Object to selectedObject.
+	 *
+	 * @param obj AbstractCpsobject
+	 */
+	public void addSelectedObjects(Collection<AbstractCanvasObject> objects) {
+		model.getSelectedObjects().addAll(objects);
+	}
+
+	/**
+	 * deletes a Element from a given Canvas Object.
+	 *
+	 * @param id    the ID
+	 * @param eleid the Element ID
+	 */
+	public void deleteElementInCanvas(int id, int eleid) {
+		HolonObject hObject = (HolonObject) mpC.searchByID(id);
+		if (hObject == null) {
+			hObject = (HolonObject) model.getSelectedObjects().stream().findFirst().get();
+		}
+		HolonElement element = mpC.searchEleById(hObject, eleid);
+		deleteElement(hObject, element);
+	}
+
+	/**
+	 * Returns the ID of the selected Object 0 = no Object is selected.
+	 *
+	 * @param id the ID of the selected Object
+	 */
+	public void setSelectedObjectID(int id) {
+		model.setSelectedObjectID(id);
+	}
+
+	/**
+	 * Get the number of HolonObjects in the given List
+	 *
+	 * @param list
+	 */
+	public int getNumberHolonObjects(ArrayList<AbstractCanvasObject> list) {
+		int val = 0;
+
+		for (AbstractCanvasObject obj : list) {
+			if (obj instanceof HolonObject) {
+				val++;
+			} else if (obj instanceof GroupNode) {
+				val += getNumberHolonObjects(((GroupNode) obj).getNodes());
+			}
+		}
+		return val;
+	}
+
 }

+ 2 - 1
src/ui/controller/SimulationManager.java

@@ -55,7 +55,8 @@ public class SimulationManager {
 	 *
 	 * @param timestep
 	 *            current Iteration
-	 * @param updateVisual TODO
+	 * @param updateVisual 
+	 * Determine if the Visuals should also be calculated
 	 */
 	public void calculateStateForTimeStep(int timestep, boolean updateVisual) {
 		boolean doesFlexManagerExist = savesFlexManger.containsKey(timestep);

+ 0 - 487
src/ui/controller/UpdateController.java

@@ -1,487 +0,0 @@
-package ui.controller;
-
-import classes.*;
-import classes.comparator.elementComparator.ElemCompOnEleName;
-import classes.comparator.elementComparator.ElemCompOnEnergy;
-import classes.comparator.elementComparator.ElemCompOnId;
-import classes.comparator.elementComparator.ElemCompOnIsActivated;
-import classes.comparator.elementComparator.ElemCompOnObj;
-import classes.comparator.elementComparator.ElemCompOnQuantity;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.Model;
-import ui.view.DefaulTable;
-import ui.view.PropertyTable;
-import ui.view.GroupNodeCanvas;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.LinkedList;
-
-/**
- * This class is for all update methods and more ;)
- * 
- * @author Gruppe14
- *
- */
-public class UpdateController {
-
-	Model model;
-	Control controller;
-	private int sortBy;
-
-	public UpdateController(Model model, Control control) {
-		this.model = model;
-		this.controller = control;
-		sortBy= 1;
-	}
-
-	/**
-	 * Update the information concerning properties of the selected CpsObject.
-	 */
-	public void refreshTableProperties(DefaulTable table) {
-		if (model.getSelectedCpsObjects().size() == 1) {
-			AbstractCanvasObject tempCps = model.getSelectedCpsObjects().get(0);
-			if (tempCps != null && tempCps.getClass() == HolonObject.class) {
-				if (table.getRowCount() != 0) {
-					table.removeRow(2);
-					Object[] tempEnergy = { "Total Energy", ((HolonObject) tempCps).getEnergyNeededFromConsumingElements(model.getCurIteration()) };
-					table.insertRow(2, tempEnergy);
-					table.removeRow(3);
-					Object[] tempFlex = { "Flexibility", ((HolonObject) tempCps).getTotalFlex() };
-					table.insertRow(3, tempFlex);
-				}
-			}
-		}
-	}
-
-	    
-	/**
-	 * Add the Information of the given ArrayList in the HolonElement Model as
-	 * Name,Energy and Amount.
-	 * 
-	 * @param objects
-	 *            ArrayList to be displayed
-	 */
-	public void fillElementTable(ArrayList<AbstractCanvasObject> objects, PropertyTable table) {
-		LinkedList<HolonElement> elemList = new LinkedList<HolonElement>();
-		
-		if (objects.size() > 1) {
-			for (AbstractCanvasObject o : objects) {
-				if (o instanceof HolonObject) {
-					for (HolonElement he : ((HolonObject) o).getElements()) {
-						he.setObjName(o.getName() + ", " + o.getId());
-						elemList.add(he);
-						elemList=sortElemList(elemList);
-					}
-				}
-			}
-			for (HolonElement e1 : elemList) {
-				Object[] temp2 = { e1.getObjName(), e1.getId(), e1.getEleName(), e1.getEnergyPerElement(),
-						controller.getSimManager().getActualFlexManager().isAFlexInUseOfHolonElement(e1), e1.getAmount(), e1.isActive()};
-				table.addRow(temp2);
-			}
-
-		} else if (objects.size() == 1) {
-			AbstractCanvasObject o = objects.get(0);
-			if (o instanceof HolonObject) {
-				for (HolonElement he : ((HolonObject) o).getElements()) {
-					elemList.add(he);
-					elemList=sortElemList(elemList);
-				}
-				
-				for (HolonElement e1 : elemList) {
-					Object[] temp2 = { e1.getId(), e1.getEleName(), e1.getEnergyPerElement(),
-							controller.getSimManager().getActualFlexManager().isAFlexInUseOfHolonElement(e1), e1.getAmount(), e1.isActive()};
-					table.addRow(temp2);
-				}
-			}
-		}
-	}
-	
-	/**
-	 * @param elemList - HolonElement-List (unsorted)
-	 * @return sorted HolonElement-List! 
-	 */
-	public LinkedList<HolonElement> sortElemList(LinkedList<HolonElement> elemList) {
-		switch(sortBy) {
-		case 0://"Object": 
-			elemList.sort(new ElemCompOnObj());
-			break;
-		case 1://ID
-			elemList.sort(new ElemCompOnId());
-			break;
-		case 2://"Device": 
-			elemList.sort(new ElemCompOnEleName());
-			break;
-		case 3://"Energy": 
-			elemList.sort(new ElemCompOnEnergy());
-			break;
-		case 4://"Flexible Energy Available": 
-			elemList.sort(null);
-			break;
-		case 5://"Quantity": 
-			elemList.sort(new ElemCompOnQuantity());
-			break;
-		case 6://"Activated": 
-			elemList.sort(new ElemCompOnIsActivated());
-			break;
-		case 7://"Flexible": 
-			elemList.sort(null);
-			break;
-		default: 
-			elemList.sort(new ElemCompOnId());
-			break;
-		}
-		return elemList;
-	};
-
-	/**
-	 * Update the HolonElement Table, that means erase all rows and add the new
-	 * rows with new data.
-	 */
-	public void refreshTableHolonElement(PropertyTable multiTable, PropertyTable singleTable) {
-		// Update of the Information about the HolonElements - only for
-		// HolonObjects
-		if(multiTable == null || singleTable == null ) return;
-		if (model.getSelectedCpsObjects().size() > 1) {
-			deleteRows(multiTable);
-			fillElementTable(model.getSelectedCpsObjects(), multiTable);
-			multiTable.fireTableDataChanged();
-		} else if (model.getSelectedCpsObjects().size() == 1) {
-			deleteRows(singleTable);
-			fillElementTable(model.getSelectedCpsObjects(), singleTable);
-			singleTable.fireTableDataChanged();
-		}
-	}
-
-	/**
-	 * Erase all information of the HolonElement Model.
-	 * 
-	 * @param t
-	 *            the Table
-	 */
-	public void deleteRows(PropertyTable t) {
-		if (t.getRowCount() > 0) {
-			for (int i = t.getRowCount() - 1; i > -1; i--) {
-				t.removeRow(i);
-			}
-		}
-	}
-
-	/**
-	 * Search for clicked HolonObject through the mouse's y-Coord.
-	 * 
-	 * @param yValue
-	 *            the Y Coordination
-	 * @return clicked HolonObject
-	 */
-	public HolonObject getHolonObj(int yValue, PropertyTable table) {
-		final int yTemp = (int) Math.floor(yValue / 16);
-		HolonObject obtTemp = null;
-		String temp = table.getValueAt(yTemp, 0).toString();
-		int idTemp = Integer.parseInt(temp.split(", ")[1]);
-		obtTemp = (HolonObject) controller.searchByID(idTemp);
-		return obtTemp;
-	}
-
-	/**
-	 * Search for actual selected HolonElement.
-	 * 
-	 * @param obj
-	 *            selected HolonObject, if obj==null means multi-selection
-	 *            active
-	 * @param yValue
-	 *            Y-Coord in the HolonElementsTable
-	 * @param toMultiHash
-	 *            0 means no MultiSelection, 1 means MultiSelection without
-	 *            Control, 2 means MultiSelection with Control
-	 * @return the selected HolonElement
-	 */
-	public HolonElement getActualHolonElement(HolonObject obj, int yValue, int toMultiHash,
-			ArrayList<PropertyTable> tables) {
-		final int yTemp = (int) Math.floor(yValue / 16);
-		int rowsTotal = 0;
-		// Filter for search --> single and multi selection
-		if (obj == null) {
-			rowsTotal = tables.get(1).getRowCount();
-		} else {
-			rowsTotal = tables.get(0).getRowCount();
-		}
-		// search for the clicked HolonObject and HolonElement --> in the
-		// HolonElementTable
-		HolonObject obtTemp = null;
-		HolonElement toReturnEle = null;
-		int id = 0;
-		if (rowsTotal != 0 && rowsTotal > yTemp) {
-			// Multi-Selection search
-			if (obj == null) {
-				String tempStringObj = tables.get(1).getValueAt(yTemp, 0).toString();
-				int idTempObj = Integer.parseInt(tempStringObj.split(", ")[1]);
-				if (model.getSelectedCpsObjects() != null) {
-					obtTemp = (HolonObject) getHolonObjSelected(idTempObj);
-				}
-				id = Integer.parseInt(tables.get(1).getValueAt(yTemp, 1).toString());
-				ArrayList<HolonElement> eleTemp = new ArrayList<HolonElement>();
-				if (model.getEleToDelete().containsKey(idTempObj) && toMultiHash == 2) {
-					eleTemp = model.getEleToDelete().get(idTempObj);
-					if (!eleTemp.contains(obtTemp.searchElementById(id))) {
-						eleTemp.add(obtTemp.searchElementById(id));
-						model.getEleToDelete().replace(idTempObj, eleTemp);
-					}
-				} else if (toMultiHash == 2) {
-					eleTemp.add(obtTemp.searchElementById(id));
-					model.getEleToDelete().put(idTempObj, eleTemp);
-				} else if (toMultiHash == 1) {
-					model.setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
-					eleTemp.add(obtTemp.searchElementById(id));
-					model.getEleToDelete().put(idTempObj, eleTemp);
-				} else if (toMultiHash == 0) {
-					toReturnEle = obtTemp.searchElementById(id);
-				}
-			} // Single-Selection search
-			else {
-				model.setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
-				id = Integer.parseInt(tables.get(0).getValueAt(yTemp, 0).toString());
-				toReturnEle = obj.searchElementById(id);
-			}
-			model.setSelectedHolonElement(toReturnEle);
-			return toReturnEle;
-		} // If no HolonObject selected
-		else {
-			model.setEleToDelete(new HashMap<Integer, ArrayList<HolonElement>>());
-			model.setSelectedHolonElement(null);
-			return null;
-		}
-	}
-
-	/**
-	 * Getter for selected CpsObject.
-	 * 
-	 * @return selected CpsObject
-	 */
-	public AbstractCanvasObject getActualCps() {
-        AbstractCanvasObject tempCps;
-        if (model.getSelectedCpsObjects().size() == 1) {
-			tempCps = model.getSelectedCpsObjects().get(0);
-		} else {
-			int tempID = model.getSelectedObjectID();
-			tempCps = controller.searchByID(tempID);
-		}
-		return tempCps;
-	}
-
-	/**
-	 * Getter for selected CpsObject.
-	 * 
-	 * @return selected CpsObject
-	 */
-	public AbstractCanvasObject getActualCpsUpperNode(GroupNodeCanvas canvas) {
-		int tempID = model.getSelectedObjectID();
-		AbstractCanvasObject tempCps = controller.searchByIDUpperNode(tempID, canvas.upperNode);
-		return tempCps;
-	}
-
-	public void paintProperties(AbstractCanvasObject obj) {
-		if (obj != null) {
-			// Name of the CpsObject
-			Object[] tempName = { "Name", obj.getName() };
-			model.getPropertyTable().addRow(tempName);
-			// Id of the CpsObject
-			Object[] tempId = { "ID", obj.getId() };
-			model.getPropertyTable().addRow(tempId);
-			// For HolonObjects the Total Energy (production or
-			// consumption) is calculated
-			if (obj instanceof HolonObject) {
-				refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-				Object[] tempEnergy = { "Total Energy", ((HolonObject) obj).getEnergyNeededFromConsumingElements(model.getCurIteration()) };
-				Object[] tempFlex = { "Flexibility", ((HolonObject) obj).getTotalFlex() };
-				model.getPropertyTable().addRow(tempEnergy);
-				model.getPropertyTable().addRow(tempFlex);
-				model.getPropertyTable().setCellEditable(0, 1, false);
-				model.getPropertyTable().setCellEditable(2, 1, false);
-				model.getPropertyTable().setCellEditable(3, 1, false);
-				model.getPropertyTable().setCellEditable(4, 1, false);
-			} // For HolonSwitches is showed the actual status (active
-				// or inactive)
-			else if (obj instanceof HolonSwitch) {
-				deleteRows(model.getSingleTable());
-				deleteRows(model.getMultiTable());
-				Object[] tempMode = { "Manual", ((HolonSwitch) obj).getManualMode() };
-				model.getPropertyTable().addRow(tempMode);
-				if (((HolonSwitch) obj).getManualMode()) {
-					Object[] tempActive = { "Active", ((HolonSwitch) obj).getManualState() };
-					model.getPropertyTable().addRow(tempActive);
-					model.getPropertyTable().setCellEditable(3, 1, true);
-				} else {
-					Object[] tempActive = { "Active",
-							((HolonSwitch) obj).getState(model.getCurIteration()) };
-					model.getPropertyTable().addRow(tempActive);
-					model.getPropertyTable().setCellEditable(3, 1, false);
-				}
-				// unitGraph.repaintWithNewSwitch((HolonSwitch) obj);
-				// elementGraph.setText(obj.getName());
-				model.getPropertyTable().setCellEditable(0, 1, true);
-				model.getPropertyTable().setCellEditable(2, 1, true);
-			} else if (obj instanceof GroupNode) {
-				deleteRows(model.getSingleTable());
-				deleteRows(model.getMultiTable());
-				//short fix please make me new
-				DecoratedGroupNode dGroupNode = controller.getSimManager().getVisualRepresentationalState(model.getCurIteration()).getCreatedGroupNodes().get((GroupNode) obj);
-				Object[] info = { "Statistics:", "" };
-				
-				Object[] numEle = { "Number of Objects (total)", ((GroupNode) obj).getNodes().size() };
-				Object[] numObj = { "Number of HolonObjects", ((GroupNode) obj).getNumHolonObj().size() };
-				Object[] numSwi = { "Number of HolonSwitches", ((GroupNode) obj).getNumSwitches().size() };
-				Object[] numUpp = { "Number of GroupNodes", ((GroupNode) obj).getNumUpperNodes().size() };
-				model.getPropertyTable().addRow(info);
-				model.getPropertyTable().addRow(numEle);
-				model.getPropertyTable().addRow(numObj);
-				model.getPropertyTable().addRow(numSwi);
-				model.getPropertyTable().addRow(numUpp);
-				if(dGroupNode != null) {
-					int numerator, denominator;
-					Object[] title = { "HolonObject Statistics:", "" };
-					
-					denominator	= dGroupNode.getAmountOfConsumer() + dGroupNode.getAmountOfSupplier() + dGroupNode.getAmountOfPassiv();
-					
-					numerator = dGroupNode.getAmountOfSupplier();
-					Object[] producer = { "Producer:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};					
-					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-					Object[] notSupplied = { "UnSupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
-					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-					Object[] partiallySupplied = { "PartriallySupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
-					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-					Object[] supplied = { "Supplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
-					numerator = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-					Object[] overSupplied = { "OverSupplied:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
-					numerator = dGroupNode.getAmountOfPassiv();
-					Object[] passiv = { "Passiv(%):",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
-					
-					Object[] nothing= {"", ""};
-					numerator = dGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
-					denominator = dGroupNode.getAmountOfElemntsFromHolonObjects();
-					Object[] aktiv = { "Active HolonElements:",  numerator + "/" + denominator + "("+ (float)numerator/(float)denominator * 100 + "%)"};
-					float consumption = dGroupNode.getConsumptionFromConsumer();
-					float production = dGroupNode.getProductionFromSupplier();
-					Object[] consumptionObj = { "Total Consumption:",  consumption};
-					Object[] productionObj = { "Total Production:",  production};
-					Object[] difference = { "Difference:", production - consumption};
-					
-					
-					model.getPropertyTable().addRow(title);
-					model.getPropertyTable().addRow(producer);
-					model.getPropertyTable().addRow(notSupplied);
-					model.getPropertyTable().addRow(partiallySupplied);
-					model.getPropertyTable().addRow(supplied);
-					model.getPropertyTable().addRow(overSupplied);
-					model.getPropertyTable().addRow(passiv);
-					model.getPropertyTable().addRow(nothing);
-					model.getPropertyTable().addRow(aktiv);
-					model.getPropertyTable().addRow(nothing);
-					model.getPropertyTable().addRow(consumptionObj);
-					model.getPropertyTable().addRow(productionObj);
-					model.getPropertyTable().addRow(difference);
-				}
-				
-			} else {
-				deleteRows(model.getSingleTable());
-				deleteRows(model.getMultiTable());
-			}
-			// For Objects the only editable cell is the name
-			ArrayList<Edge> tempArray = obj.getConnections();
-			// If the clicked object has connections
-			if (!tempArray.isEmpty()) {
-				boolean first = true;
-				for (Edge temp2 : tempArray) {
-					if (first) {
-						first = false;
-						if (obj.getId() != temp2.getA().getId()) {
-							Object[] tempConnection = { obj.getName() + " is connected to",
-									temp2.getA().getName() + " with ID: " + temp2.getA().getId() };
-							model.getPropertyTable().addRow(tempConnection);
-						} else {
-							Object[] tempConnection = { obj.getName() + " is connected to",
-									temp2.getB().getName() + " with ID: " + temp2.getB().getId() };
-							model.getPropertyTable().addRow(tempConnection);
-						}
-					} else {
-						if (obj.getId() != temp2.getA().getId()) {
-							Object[] tempConnection = { "",
-									temp2.getA().getName() + " with ID: " + temp2.getA().getId() };
-							model.getPropertyTable().addRow(tempConnection);
-						} else {
-							Object[] tempConnection = { "",
-									temp2.getB().getName() + " with ID: " + temp2.getB().getId() };
-							model.getPropertyTable().addRow(tempConnection);
-						}
-					}
-				}
-			}
-		} // If the clicked Object is an edge
-		else if (model.getSelectedEdge() != null) {
-			// Name displayed
-			Object[] tempName = { "Name",
-					"Edge: " + model.getSelectedEdge().getA().getName() + " to "
-							+ model.getSelectedEdge().getB().getName() };
-			model.getPropertyTable().addRow(tempName);
-			// Current Flow displayed
-			Object[] tempFlow = { "Current flow", "" };
-			model.getPropertyTable().addRow(tempFlow);
-			// Max Capacity displayed
-			Object[] tempCapacity = { "Max. Capacity", model.getSelectedEdge().getCapacity() };
-			model.getPropertyTable().addRow(tempCapacity);
-			// Status displayed
-            Object[] tempStatus = {"Length", model.getSelectedEdge().getLength() };
-            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);
-			model.getPropertyTable().setCellEditable(3, 1, true);
-		} else if (getActualCps() == null) {
-			deleteRows(model.getSingleTable());
-			deleteRows(model.getMultiTable());
-		}
-		// Update of the HolonElementTable (Single- or Multi-Selection)
-		if (model.getSelectedCpsObjects().size() > 1) {
-			model.getTableHolonElement().setModel(model.getMultiTable());
-		} else if (model.getSelectedCpsObjects().size() == 1) {
-			model.getTableHolonElement().setModel(model.getSingleTable());
-		}
-	}
-
-	public AbstractCanvasObject getHolonObjSelected(int id) {
-		AbstractCanvasObject obj = null;
-		for (AbstractCanvasObject o : model.getSelectedCpsObjects()) {
-			if (o.getId() == id) {
-				obj = o;
-				break;
-			}
-		}
-		return obj;
-	}
-
-
-	/**
-	 * 
-	 * @return id of column that should be sorted
-	 */
-	public int getSortBy() {
-		return sortBy;
-	}
-
-	/**
-	 * sets the column id that should be sorted
-	 * @param column
-	 */
-	public void setSortBy(int column) {
-		/**
-		 * if there is no "Object" column, assume coloumn 0 is
-		 */
-		if(model.getTableHolonElement().getColumnCount()==7)
-			this.sortBy = column+1;
-		else
-			this.sortBy = column;
-	}
-}

+ 1 - 1
src/ui/model/MinimumNetwork.java

@@ -24,7 +24,7 @@ public class MinimumNetwork {
 	{
 		String objecte = "[";
 		for(HolonObject object :holonObjectList) {
-			objecte += " " + object.getObjName();
+			objecte += " " + object.getName();
 		}
 		objecte += "]";
 		String edges = "[";

+ 29 - 92
src/ui/model/Model.java

@@ -3,12 +3,12 @@ package ui.model;
 import java.awt.Color;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Set;
 import java.util.stream.Collectors;
 
-import javax.swing.JTable;
-
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 
@@ -27,8 +27,6 @@ import classes.Node;
 import classes.Pair;
 import interfaces.GraphListener;
 import interfaces.ObjectListener;
-import ui.view.DefaulTable;
-import ui.view.PropertyTable;
 import utility.Vector2Int;
 
 /**
@@ -54,18 +52,13 @@ public class Model {
     private int canvasY = 3000;
     private int curIteration = 0;
     // ID of the Selected Object
-    private AbstractCanvasObject selectedCpsObject = null;
     private HolonElement selectedHolonElement;
     private Edge selectedEdge;
-    private ArrayList<AbstractCanvasObject> selectedObjects = new ArrayList<>();
-    private ArrayList<AbstractCanvasObject> clipboardObjects = new ArrayList<>();
+    private Set<AbstractCanvasObject> selectedObjects = new HashSet<>();
+    private Set<AbstractCanvasObject> clipboardObjects = new HashSet<>();
     private HashMap<Integer, ArrayList<HolonElement>> eleToDelete;
     // Capacity for Edge
     private float maxCapacity;
-    // Table for HolonElements --> all cells are editable
-    private JTable tableHolonElement;
-    /** Table for the properties of HolonObjects, Edges etc */
-    private JTable propertyTable;
     
     private ArrayList<GraphListener> graphListeners = new ArrayList<GraphListener>();
     // Iteration Speed
@@ -77,7 +70,7 @@ public class Model {
     private int numberOfSaves = 35;
     /** whether the supplyBars should be shown or not */
     private boolean showSupplyBars = true;
-    //TODO:
+    /** the amount of iterations */
     private int iterations=100;
     
     /**
@@ -125,9 +118,6 @@ public class Model {
     private ArrayList<HolonSwitch> switchsOnCanvas= new ArrayList<HolonSwitch>();
     
     private List<ObjectListener> objectListeners;
-    private PropertyTable tableModelHolonElementMulti;
-    private PropertyTable tableModelHolonElementSingle;
-    private DefaulTable tableModelProperties;
     private HashMap<Integer, GroupNode> hashcodeMap = new HashMap<>();
 
 
@@ -145,13 +135,7 @@ public class Model {
         setObjectListeners(new LinkedList<>());
         setCgIdx(new HashMap<>());
         setCvsObjIdx(new HashMap<>());
-        setClipboradObjects(new ArrayList<>());
         setEleToDelete(new HashMap<>());
-        setSingleTable(new PropertyTable());
-        setMultiTable(new PropertyTable());
-        setPropertyTable(new DefaulTable(1000, colNames.length));
-        getPropertyTable().setColumnIdentifiers(colNames);
-        setTableHolonElement(new JTable());
         initGson();
     }
 
@@ -281,30 +265,12 @@ public class Model {
         this.selectedID = id;
     }
 
-    /**
-     * Returns the Selected Cps Object.
-     *
-     * @return selected Cps Object
-     */
-    public AbstractCanvasObject getSelectedCpsObject() {
-        return selectedCpsObject;
-    }
-
-    /**
-     * Set the Selected Objecs.
-     *
-     * @param selectedCpsObject Objects that are selected
-     */
-    public void setSelectedCpsObject(AbstractCanvasObject selectedCpsObject) {
-        this.selectedCpsObject = selectedCpsObject;
-    }
-
     /**
      * Returns all selected Objects on the Canvas.
      *
      * @return The selected Objects
      */
-    public ArrayList<AbstractCanvasObject> getSelectedCpsObjects() {
+    public Set<AbstractCanvasObject> getSelectedObjects() {
         return selectedObjects;
     }
 
@@ -313,7 +279,7 @@ public class Model {
      *
      * @return The selected Objects
      */
-    public void setSelectedCpsObjects(ArrayList<AbstractCanvasObject> arr) {
+    public void setSelectedCpsObjects(Set<AbstractCanvasObject> arr) {
         this.selectedObjects = arr;
     }
 
@@ -371,7 +337,7 @@ public class Model {
      *
      * @return ITERATIONS
      */
-    public int getIterations() {
+    public int getMaxIterations() {
         return iterations;
     }
 
@@ -387,7 +353,7 @@ public class Model {
      *
      * @return cURiTERATION
      */
-    public int getCurIteration() {
+    public int getCurrentIteration() {
         return curIteration;
     }
 
@@ -496,7 +462,7 @@ public class Model {
      *
      * @return Objects in the Clipboard
      */
-    public ArrayList<AbstractCanvasObject> getClipboradObjects() {
+    public Set<AbstractCanvasObject> getClipboradObjects() {
         return clipboardObjects;
     }
 
@@ -505,7 +471,7 @@ public class Model {
      *
      * @param c Array of Objects
      */
-    public void setClipboradObjects(ArrayList<AbstractCanvasObject> c) {
+    public void setClipboradObjects(Set<AbstractCanvasObject> c) {
         this.clipboardObjects = c;
     }
 
@@ -581,57 +547,11 @@ public class Model {
     public HashMap<Integer, ArrayList<HolonElement>> getEleToDelete() {
         return this.eleToDelete;
     }
-
+    //TODO eleToDelete is this necessary
     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 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;
-    }
-    
-	/**
-	 * @return the tableProperties
-	 */
-	public JTable getTableProperties() {
-		return propertyTable;
-	}
-	
-	/**
-	 * @return the tableProperties
-	 */
-	public void setTableProperties(JTable propertyTable) {
-		this.propertyTable = propertyTable;
-	}
 
     public List<HolonElement> getAllHolonElemnts() {
     	return getAllHolonObjectsOnCanvas().stream().flatMap(hO -> hO.getElements().stream()).collect(Collectors.toList());
@@ -654,6 +574,23 @@ public class Model {
     	}
     }
     
+    public ArrayList<AbstractCanvasObject> getAllAbstractObjectsOnCanvas(){
+		ArrayList<AbstractCanvasObject> objectToReturn = new ArrayList<AbstractCanvasObject>();
+		getAllAsbtractObjectsRecursive(objectToReturn, getObjectsOnCanvas());
+    	return objectToReturn;
+    }
+    private void getAllAsbtractObjectsRecursive(ArrayList<AbstractCanvasObject> addObjectsToThisList, List<AbstractCanvasObject> listOfObjectsToSearch){
+    	for(AbstractCanvasObject aCps : listOfObjectsToSearch) {
+    		if(aCps instanceof GroupNode){
+    			getAllAsbtractObjectsRecursive(addObjectsToThisList, ((GroupNode)aCps).getNodes());
+    		}
+    		else{
+    			addObjectsToThisList.add(aCps);
+    		}
+    	}
+    }
+    
+    
     
     /**
      * get all Switches

+ 0 - 49
src/ui/view/DefaulTable.java

@@ -1,49 +0,0 @@
-package ui.view;
-
-import javax.swing.table.DefaultTableModel;
-
-/**
- * Default Table.
- * 
- * @author Gruppe14
- */
-public class DefaulTable extends DefaultTableModel {
-
-	private static final long serialVersionUID = 1L;
-	private boolean[][] editableCells; // 2d array to represent rows and
-										// columns
-
-	/**
-	 * Constructor.
-	 * 
-	 * @param rows
-	 *            the Rows
-	 * @param cols
-	 *            the Cols
-	 */
-	public DefaulTable(int rows, int cols) { // constructor
-		super(rows, cols);
-		this.editableCells = new boolean[rows][cols];
-	}
-
-	@Override
-	public boolean isCellEditable(int row, int column) {
-		return this.editableCells[row][column];
-	}
-
-	/**
-	 * Set Cell Editable.
-	 * 
-	 * @param row
-	 *            the Rows
-	 * @param col
-	 *            the Cols
-	 * @param value
-	 *            true or false
-	 */
-	public void setCellEditable(int row, int col, boolean value) {
-		this.editableCells[row][col] = value; // set cell true/false
-		this.fireTableCellUpdated(row, col);
-	}
-
-}

+ 0 - 2830
src/ui/view/GUI.java

@@ -1,2830 +0,0 @@
-package ui.view;
-
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Cursor;
-import java.awt.Dimension;
-import java.awt.GraphicsDevice;
-import java.awt.GraphicsEnvironment;
-import java.awt.HeadlessException;
-import java.awt.Image;
-import java.awt.Point;
-import java.awt.Rectangle;
-import java.awt.Toolkit;
-import java.awt.datatransfer.UnsupportedFlavorException;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.awt.event.ComponentAdapter;
-import java.awt.event.ComponentEvent;
-import java.awt.event.ItemEvent;
-import java.awt.event.KeyAdapter;
-import java.awt.event.KeyEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseMotionAdapter;
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Timer;
-import java.util.TimerTask;
-
-import javax.swing.AbstractAction;
-import javax.swing.ActionMap;
-import javax.swing.Box;
-import javax.swing.BoxLayout;
-import javax.swing.CellEditor;
-import javax.swing.GrayFilter;
-import javax.swing.ImageIcon;
-import javax.swing.InputMap;
-import javax.swing.JButton;
-import javax.swing.JCheckBoxMenuItem;
-import javax.swing.JComboBox;
-import javax.swing.JComponent;
-import javax.swing.JDialog;
-import javax.swing.JFileChooser;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JMenu;
-import javax.swing.JMenuBar;
-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 javax.swing.JTable;
-import javax.swing.JTextField;
-import javax.swing.JToolBar;
-import javax.swing.JTree;
-import javax.swing.KeyStroke;
-import javax.swing.SwingUtilities;
-import javax.swing.filechooser.FileNameExtensionFilter;
-import javax.swing.table.DefaultTableModel;
-import javax.swing.table.JTableHeader;
-import javax.swing.table.TableCellEditor;
-import javax.swing.table.TableCellRenderer;
-import javax.swing.tree.DefaultMutableTreeNode;
-import javax.swing.tree.DefaultTreeModel;
-import javax.swing.tree.TreeCellRenderer;
-
-import org.apache.commons.compress.archivers.ArchiveException;
-import com.google.gson.JsonParseException;
-
-import classes.AbstractCanvasObject;
-import classes.Category;
-import classes.Edge;
-import classes.GroupNode;
-import classes.HolonElement;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.IdCounter;
-import classes.IdCounter.CounterType;
-import interfaces.GraphEditable;
-import ui.controller.Control;
-import ui.controller.UpdateController;
-import ui.model.DecoratedState;
-import ui.model.Model;
-import ui.model.Model.FairnessModel;
-import ui.view.CreateNewDialog.Option;
-import utility.ImageImport;
-
-/**
- * Graphical User Interface.
- *
- * @author Gruppe14
- */
-public class GUI{
-	
-	static final Color PALE_RED=new Color(255, 192, 192);
-	
-	/**
-	 * Menu on the Top containing File, Edit View Help etc
-	 */
-	private final JMenuBar menuBar = new JMenuBar();
-	private final JMenu mnNewMenu = new JMenu("File");
-	private final JMenu mnNewMenuEdit = new JMenu("Edit");
-	private final JMenu mnNewMenuOptions = new JMenu("Options");
-	private final JMenu mnNewMenuView = new JMenu("View");
-	private final JMenu menuWindow = new JMenu("Window");
-	
-	/** Help Menu containing helpful Informations and the AboutUs Popup */
-	private final JMenu mnHelp = new JMenu("Help");
-	
-	/** 
-	 * Help -> Introduction
-	 * A small Introduction of the Application, SmartGrids and Holons 
-	 */
-	private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
-
-	/** 
-	 * Help -> UserManual
-	 */
-	private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
-	
-	/** Help -> Algorithm Help Menu */
-	private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
-	
-	/** Help -> CodeDocumentation */
-	private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
-	
-	/** Help -> AboutUs */
-	private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
-	/** checked if supplyBars should be shown */
-	private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem(
-			"Show supply bars.");
-	/** menu for the different fairness Models */
-	private final JMenu mnFairnessModel = new JMenu("Fairness Model");
-	/** press to supply minimum demand first */
-	private final JMenuItem mntmFairMinFirst = new JMenuItem(
-			"Minimum demand first");
-	/** press to give everyone the same energy */
-	private final JMenuItem mntmFairAlleEqual = new JMenuItem(
-			"Equal supply for everyone");
-	private final JMenuItem mntmOpen = new JMenuItem("Open");
-	private final JMenuItem mntmNew = new JMenuItem("New");
-	private final JMenuItem mntmSave = new JMenuItem("Save");
-	private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
-	private final JMenuItem mntmBackground = new JMenuItem("Set Background Image");
-	private final JSplitPane splitPane = new JSplitPane();
-	private final JSplitPane splitPane1 = new JSplitPane();
-	// the tabbed canvas containing the different sub-net tabs of the grid (Main
-	// Grid + Nodes of Nodes)
-
-	private final JPanel myPanel = new JPanel(new BorderLayout());
-	private final JTabbedPane tabbedPaneInnerOriginal = 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();
-	// private final JScrollPane holonSP = new JScrollPane();
-	// the original tabbed Pane (containing tabs for view, statistics, holon,
-	// flexibility)
-	private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(
-			JTabbedPane.TOP);
-	// the same tabbed Pane that appears once the view is split
-	private final JTabbedPane tabbedPaneSplit = new JTabbedPane(JTabbedPane.TOP);
-	private final JPopupMenu popmenuEdit = new JPopupMenu();
-	private final JMenuItem editItem = new JMenuItem("Edit Object");
-	private final JLabel maxGraph = new JLabel("100%");
-	private final JLabel medGraph = new JLabel("50%");
-	private final JLabel minGraph = new JLabel("0%");
-	private final JLabel elementGraph = new JLabel("None ");
-	private final ArrayList<HolonElement> selectedElements = new ArrayList<>();
-	private final JTree categoryTree = new JTree();
-	/******************************************
-	 ************* Right Container*************
-	 ******************************************
-	 * Right Container: here comes the information about the HolonObject, such
-	 * as HolonElements Information, Properties and Consumption/Production
-	 * graph.
-	 **/
-	private final JSplitPane splitHolonElPro = new JSplitPane(
-			JSplitPane.VERTICAL_SPLIT);
-	private final JSplitPane splitGraphHolonEl = new JSplitPane(
-			JSplitPane.VERTICAL_SPLIT);
-	private final int distanceBetweenElementsAndGraph = 350;
-	// Model for single or multi selection
-	private final JPanel scrollElements = new JPanel();
-	private final JScrollPane tableHolonElementScrollPane = new JScrollPane();
-	// In this section are all the properties that correspond to the clicked
-	// HolonObject, such as connections, name, Type, etc.
-	// Table for Properties --> Cell with (0,1) is editable by CpsObjt and
-	// Cell(3,1) is editable by Edges
-	private final JTable tableProperties = new JTable() {
-
-		@Override
-		public TableCellRenderer getCellRenderer(int row, int column) {
-			if (getValueAt(row, column) instanceof Boolean) {
-				return super.getDefaultRenderer(Boolean.class);
-			} else {
-				return super.getCellRenderer(row, column);
-			}
-		}
-
-		@Override
-		public TableCellEditor getCellEditor(int row, int column) {
-			if (getValueAt(row, column) instanceof Boolean) {
-				return super.getDefaultEditor(Boolean.class);
-			} else {
-				return super.getCellEditor(row, column);
-			}
-		}
-
-	};
-	//Prechoosed local Periods
-	private String[] comboContext = {
-	         "", "5", "10", "20" ,"100", "1000"
-	};
-	private JComboBox<String> localPeriodInput = new JComboBox<String>(comboContext);
-	JButton resetButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Images/resetIcon3.png")));
-	ImageIcon localPeriodButtonImage = new ImageIcon(GrayFilter.createDisabledImage(ImageImport.loadImage("/Images/Graph.png")));
-	private JButton localPeriodButton = new JButton("", localPeriodButtonImage);
-	private final JPanel graphLabel = new JPanel();
-	private final JScrollPane scrollProperties = new JScrollPane();
-	// In this section is the graph for the selected HolonElement of the clicked
-	// HolonObject
-	private final JTable tableGraph = new JTable();
-	private final DefaultTableModel tableModelGraph = new DefaultTableModel();
-	private final JScrollPane scrollGraph = new JScrollPane();
-	private final Model model;
-	private final Control controller;
-
-	// In this section are all the Holonelements that correspond to the clicked
-	// HolonObject with consumption/production, name and amount.
-	private final JPanel panel = new JPanel();
-	private final JPanel panelHolonEl = new JPanel();
-	// Buttons
-
-	private final JButton btnAdd = new JButton();
-	private final JPopupMenu btnAddPopUp = new JPopupMenu("Newacac");
-	private final JMenuItem mItemNew = new JMenuItem("New..");
-	private final JMenuItem mItemCategory = new JMenuItem("Category");
-	private final JMenuItem mItemObject = new JMenuItem("Object");
-	private final JMenuItem mItemSwitch = new JMenuItem("Switch");
-	private final JButton btnDel = new JButton();
-	private final JButton btnAddHolEL = new JButton();
-	private final JButton btnDelHolEL = new JButton();
-
-	private final JToolBar toolBar = new JToolBar();
-	private final JToolBar toolBarHolonEl = new JToolBar();
-	private final JToolBar toolBarGraph = new JToolBar();
-	// Languages
-	private final MyCanvas canvas;
-	private final UnitGraph unitGraph;
-	/** Textfield to show the period of an element */
-	private final JTextField unitGraphLocalPeriod = new JTextField(6);
-	private final JMenuItem mntmUndo = new JMenuItem("Undo");
-	private final JMenuItem mntmRedo = new JMenuItem("Redo");
-	private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
-	private final JMenuItem mntmFindReplace = new JMenuItem("Find/ Replace");
-	private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
-	private final JMenuItem mntmResetCategory = new JMenuItem(
-			"Reset Categories");
-	private final String[] columnNamesMulti = { "Object", "Nr.", "Device",
-			"Energy", "Flexibility active", "Quantity", "Activated" };
-	private final String[] columnNamesSingle = { "Nr.", "Device", "Energy",
-			"Flexibility active", "Quantity", "Activated" };
-	private final ArrayList<PropertyTable> tables = new ArrayList<>();
-	private final UpdateController updCon;
-	// for doubleclick
-	private boolean click = false;
-	private JFrame holegJFrame;
-	private JTabbedPane tabTemp; // tabbedPaneOriginal or tabbedPaneSplit
-	private boolean initSplit = true;
-	private String catOfObjToBeEdited;
-	private GroupNodeCanvas unc;
-	private JPanel contentPane;
-	private String holonEleNamesDisplayed = "None ";
-	// Pop up Windows
-	private AddObjectPopUp addObjectPopUP;
-	private AboutUsPopUp aboutUsPopUp;
-	private AddElementPopUp addElementPopUp;
-	// variables
-	private boolean dragging = false;
-	private String actualObjectClicked;
-	private Image img = null;
-	private AbstractCanvasObject tempCps = null;
-	private int yValueElements = 0;
-	// Time Stuff
-	private TimePanel timePanel;
-	public TimePanel getTimePanel() {
-		return timePanel;
-	}
-
-	// Coord for all Cells with text
-	private int yThis;
-	private int xThis;
-	// Coord for all Cells with boolean values (checkbox)
-	private int yBTis;
-	private int xBThis;
-	// Coord for the Edit-Modus in the PropertieTable
-	private int yProThis;
-	private int xProThis;
-	private int yProThisOneClick;
-	private int xProThisOneClick;
-	private AbstractCanvasObject temp = null;
-	private String warningText = "Warning";
-	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 the left library in order to delete something.";
-
-	
-	private List<Outliner> outlinerList = new ArrayList<Outliner>();
-	private List<FlexWindow> flexList = new ArrayList<FlexWindow>();
-
-	private JMenuItem removeItem = new JMenuItem("Remove");
-
-	
-	/**
-	 * Create the application.
-	 *
-	 * @param control
-	 *            the Controller
-	 */
-	GUI(Control control) {
-		this.controller = control;
-		this.model = control.getModel();
-		control.setGui(this);
-		this.unitGraph = new UnitGraph(model, control);
-		this.canvas = new MyCanvas(model, control, unitGraph);
-		model.setTableProperties(tableProperties);
-		initialize();
-		updateCategories(model.getCategories());
-		updCon = new UpdateController(model, controller);
-		control.OnCategoryChanged.addListener(() -> this.updateCategoryUI(model.getCategories()));
-	}
-
-
-	/**
-	 * Initialize the contents of the frame.
-	 */
-	private void initialize() {
-		holegJFrame = new JFrame();
-		holegJFrame.setTitle("HOLEG Simulator");
-		// try to restore old position/dimensions
-		ArrayList<Integer> savedWindowDim = controller
-				.loadSavedWindowDimensionsIfExistent();
-		if (savedWindowDim.size() == 4) {
-			holegJFrame.setBounds(savedWindowDim.get(0),
-					savedWindowDim.get(1), savedWindowDim.get(2),
-					savedWindowDim.get(3));
-		}
-
-		// if the upper part of the window is showing, the windows can still be
-		// moved,
-		// but if it is not, we need to move it to somewhere else
-		if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
-			holegJFrame.setBounds(100, 100, 1000, 800);
-			holegJFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
-		}
-		holegJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
-
-		holegJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
-			@Override
-			public void windowClosing(java.awt.event.WindowEvent windowEvent) {
-				if (JOptionPane.showConfirmDialog(holegJFrame,
-						"Are you sure you want to exit?",
-						"HOLEG",
-						JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
-					controller.deleteDirectory(new File(System
-							.getProperty("user.home")
-							+ "/.config/HolonGUI/Autosave"));
-
-					// try to save the position and size of the window, such
-					// that (if possible)
-					// it can be opened in the same position the next time
-					try {
-						controller.savePosAndSizeOfWindow(
-								holegJFrame.getX(),
-								holegJFrame.getY(),
-								holegJFrame.getWidth(),
-								holegJFrame.getHeight());
-					} catch (Exception e) {
-						e.printStackTrace();
-					}
-					System.exit(1);
-				}
-				System.exit(0);
-			}
-		});
-
-		contentPane = (JPanel) holegJFrame.getContentPane();
-
-		int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
-		InputMap inputMap = contentPane.getInputMap(condition);
-		ActionMap actionMap = contentPane.getActionMap();
-
-		String cntrlZDown = "controlZ";
-		inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
-		actionMap.put(cntrlZDown, new AbstractAction() {
-
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				try {
-					controller.loadAutoSave(controller.getUndoSave());
-					closeInvalidUpperNodeTabs();
-					
-					controller.calculateStateAndVisualForCurrentTimeStep();
-					canvas.repaint();
-					updateUpperNodes();
-				} catch (IOException eex) {
-					eex.printStackTrace();
-				}
-			}
-		});
-
-		String cntrlYDown = "controlY";
-		inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
-		actionMap.put(cntrlYDown, new AbstractAction() {
-
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				try {
-					controller.loadAutoSave(controller.getRedoSave());
-
-					closeInvalidUpperNodeTabs();
-					
-					controller.calculateStateAndVisualForCurrentTimeStep();
-					canvas.repaint();
-					updateUpperNodes();
-				} catch (IOException ex) {
-					ex.printStackTrace();
-				}
-			}
-		});
-
-		String cntrlADown = "controlA";
-		inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
-		AbstractAction controlA = new AbstractAction() {
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				chooseTabTemp();
-
-				model.getSelectedCpsObjects().clear();
-
-				// Uppernode Canvas?
-				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-				Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
-						.getComponent(0);
-
-				if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-					GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
-					for (AbstractCanvasObject cps : uNC.upperNode.getNodes()) {
-						controller.addSelectedObject(cps);
-					}
-					uNC.repaint();
-					// or Canvas?
-				} else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
-					for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-						controller.addSelectedObject(cps);
-					}
-					canvas.repaint();
-				}
-				controller.getObjectsInDepth();
-
-			}
-		};
-		actionMap.put(cntrlADown, controlA);
-
-		String delDown = "delete";
-		inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false),
-				delDown);
-		actionMap.put(delDown, new AbstractAction() {
-
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				chooseTabTemp();
-
-				// Uppernode Canvas?
-				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 = true;
-
-				if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-					GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
-					for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-						if (uNC.upperNode.getNodes().contains(cps)) {
-							controller.delObjUpperNode(cps, uNC.upperNode);
-							unc.setToolTip(false);
-
-							// remove UpperNodeTab if UpperNode deleted
-							removeUpperNodeTab(cps);
-						}
-					}
-					uNC.repaint();
-
-					// or Canvas?
-				} else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
-					boolean save = false;
-					// Edge Deleting
-					Edge edgeHighlight = model.getSelectedEdge();
-					if (edgeHighlight != null) {
-						controller.removeEdgesOnCanvas(edgeHighlight);
-						((MyCanvas) canvasOrUpperNodeCanvas).edgeHighlight = null;
-					}
-					for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
-						AbstractCanvasObject cps = model.getSelectedCpsObjects()
-								.get(j);
-						if (j < model.getSelectedCpsObjects().size() - 1)
-							save = true;
-						controller.delCanvasObject(cps, save);
-						canvas.setToolTip(false);
-
-						// remove UpperNodeTab if UpperNode deleted
-						removeUpperNodeTab(cps);
-					}
-					canvas.repaint();
-				}
-
-				// recalculate net if a producer was deleted
-				if (wasProducerDeleted) {
-					controller.resetSimulation();
-					controller.calculateStateAndVisualForCurrentTimeStep();
-				}
-
-				model.getSelectedCpsObjects().clear();
-				hideScrollGraph();
-			}
-		});
-
-		String cntrlFDown = "controlF";
-		inputMap.put(KeyStroke.getKeyStroke("control F"), cntrlFDown);
-		actionMap.put(cntrlFDown, new AbstractAction() {
-
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				SearchPopUp dialog = new SearchPopUp(controller, canvas,
-						holegJFrame);
-				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-				dialog.setVisible(true);
-			}
-		});
-
-		String cntrlCDown = "controlC";
-		inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
-		AbstractAction controlC = new AbstractAction() {
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				chooseTabTemp();
-
-				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-				if (!model.getSelectedCpsObjects().isEmpty()) {
-					if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas)
-						controller.copy(((GroupNodeCanvas) scrollPane
-								.getViewport().getComponent(0)).upperNode);
-					else
-						controller.copy(null);
-					if (!model.getClipboradObjects().isEmpty()) {
-						canvas.itemPaste.setEnabled(true);
-					}
-				}
-			}
-		};
-		actionMap.put(cntrlCDown, controlC);
-
-		String cntrlVDown = "controlV";
-		inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
-		AbstractAction controlV = new AbstractAction() {
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				try {
-					tabTemp = null;
-					if (tabbedPaneOriginal.getMousePosition() != null) {
-						tabTemp = tabbedPaneOriginal;
-					} else {
-						if (!initSplit) {
-							tabTemp = tabbedPaneSplit;
-						}
-					}
-
-					if(tabTemp == null)return;
-					JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-					Component canvasOrUpperNodeCanvas = scrollPane
-							.getViewport().getComponent(0);
-
-					if (tabTemp != null
-							&& canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-
-						controller
-								.paste(((GroupNodeCanvas) canvasOrUpperNodeCanvas).upperNode,
-										canvasOrUpperNodeCanvas
-												.getMousePosition());
-						controller.calculateStateAndVisualForCurrentTimeStep();
-						scrollPane.getViewport().getComponent(0).repaint();
-					} else {
-						controller.paste(null, canvas.getMousePosition());
-						controller.calculateStateAndVisualForCurrentTimeStep();
-						canvas.repaint();
-					}
-				} catch (HeadlessException | JsonParseException
-						| UnsupportedFlavorException | IOException e1) {
-					JLabel message = new JLabel(
-							"The Clipboard information cannot be pasted into Application.");
-					JOptionPane.showMessageDialog(holegJFrame, message,
-							"", JOptionPane.ERROR_MESSAGE);
-				}
-
-			}
-		};
-		actionMap.put(cntrlVDown, controlV);
-
-		String cntrlXDown = "controlX";
-		inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
-		AbstractAction controlX = new AbstractAction() {
-			private static final long serialVersionUID = 1L;
-
-			@Override
-			public void actionPerformed(ActionEvent e) {
-				chooseTabTemp();
-
-				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-				if (!model.getSelectedCpsObjects().isEmpty()) {
-					if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
-						controller.cut(((GroupNodeCanvas) scrollPane
-								.getViewport().getComponent(0)).upperNode);
-						controller.calculateStateAndVisualForCurrentTimeStep();
-						scrollPane.getViewport().getComponent(0).repaint();
-					} else {
-						controller.cut(null);
-						controller.calculateStateAndVisualForCurrentTimeStep();
-						canvas.repaint();
-					}
-					if (!model.getClipboradObjects().isEmpty()) {
-						canvas.itemPaste.setEnabled(true);
-					}
-				}
-			}
-		};
-		actionMap.put(cntrlXDown, controlX);
-
-		holegJFrame.setJMenuBar(menuBar);
-
-		holegJFrame.setIconImage(ImageImport.loadImage(
-				"/Images/Holeg.png", 30, 30));
-
-		menuBar.add(mnNewMenu);
-
-		mnNewMenu.add(mntmNew);
-
-		mnNewMenu.add(mntmOpen);
-
-		mnNewMenu.add(mntmSave);
-
-		menuBar.add(mnNewMenuEdit);
-
-		mnNewMenuEdit.add(mntmUndo);
-
-		mnNewMenuEdit.add(mntmRedo);
-		mntmFindReplace.addActionListener(actionEvent -> {
-			try {
-				SearchPopUp dialog = new SearchPopUp(controller, canvas,
-						holegJFrame);
-				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-				dialog.setVisible(true);
-				controller.getObjectsInDepth();
-			} catch (Exception ex) {
-				ex.printStackTrace();
-			}
-		});
-
-		mnNewMenuEdit.add(mntmFindReplace);
-		mnNewMenuEdit.add(mntmEditEdges);
-		mntmEditEdges.addActionListener(actionEvent -> {
-			EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
-			edgePopUp.setCanvas(canvas);
-			edgePopUp.setController(controller);
-			edgePopUp.setVisible(true);
-		});
-		
-		
-		//Edit -> Align All
-		
-		mnNewMenuEdit.add(mntmAlignAll);
-		mntmAlignAll.addActionListener(actionEvent -> {
-			// getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the active canvas
-			AbstractCanvas activeCanvas = ((AbstractCanvas) getScrollPaneFromTabbedPane().getViewport().getComponent(0));
-			if (activeCanvas != null) {
-				activeCanvas.tryToAlignObjects();
-				activeCanvas.repaint();
-			}
-		});
-		
-		
-		menuBar.add(mnNewMenuOptions);
-
-		mnNewMenuOptions.add(mntmResetCategory);
-		mntmResetCategory.addActionListener(actionEvent -> {
-			ArrayList<Category> cat = model.getCategories();
-			try {
-				while (!cat.isEmpty()) {
-					controller.deleteCategory(cat.get(0).getName());
-
-				}
-				controller.resetCategorys();
-			} catch (Exception e2) {
-				System.out.println(e2.getMessage());
-			}
-			categoryTree.revalidate();
-			categoryTree.repaint();
-		});
-
-
-		/**
-		 * Add Fairness Model Option to the option Menu
-		 */
-		mnNewMenuOptions.add(mnFairnessModel);
-
-		mnFairnessModel.add(mntmFairMinFirst);
-		mntmFairMinFirst.setForeground(Color.BLUE);
-		mntmFairMinFirst
-				.setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
-						+ "After that as many HolonObjects as possible will get fully supplied.");
-
-		mntmFairMinFirst
-				.addActionListener(arg0 -> {
-					controller.setFairnessModel(FairnessModel.MininumDemandFirst);
-					mntmFairMinFirst.setForeground(Color.BLUE);
-					mntmFairAlleEqual.setForeground(mnFairnessModel
-							.getForeground());
-					controller.calculateStateAndVisualForCurrentTimeStep();
-					// Update UpperNodes
-					Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
-							.getViewport().getComponent(0);
-					if (canvasOrUpperNodeCanvas != null
-							&& canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-						((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
-					}
-				});
-
-		mnFairnessModel.add(mntmFairAlleEqual);
-		mntmFairAlleEqual
-				.setToolTipText("HolonObjects will all get the same amount of energy.");
-
-		mntmFairAlleEqual.addActionListener(arg0 -> {
-			controller.setFairnessModel(FairnessModel.AllEqual);
-			mntmFairAlleEqual.setForeground(Color.BLUE);
-			mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
-			controller.calculateStateAndVisualForCurrentTimeStep();
-			// Update UpperNodes
-				Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
-						.getViewport().getComponent(0);
-				if (canvasOrUpperNodeCanvas != null
-						&& canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-					((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
-				}
-			});
-
-		menuBar.add(mnNewMenuView);
-
-		mnNewMenuView.add(mntmCanvasSize);
-		mntmCanvasSize.addActionListener(actionEvent -> {
-			CanvasResizePopUp popUp = new CanvasResizePopUp(model, controller,
-					canvas, tabbedPaneOriginal, tabbedPaneSplit,
-					holegJFrame);
-			popUp.setVisible(true);
-		});
-		
-		mnNewMenuView.add(mntmCanvasSize);
-
-		/*
-		 * Adds Checkbox to turn supply bars on/off
-		 */
-		mnNewMenuView.add(showSupplyBarsCheckBox);
-		showSupplyBarsCheckBox.setSelected(true);
-		showSupplyBarsCheckBox.addActionListener(arg0 -> {
-			controller.setShowSupplyBars(showSupplyBarsCheckBox.isSelected());
-
-			canvas.repaint();
-
-			// Update UpperNodes
-				JScrollPane spane = getScrollPaneFromTabbedPane();
-				if(spane != null){
-					Component canvasOrUpperNodeCanvas = spane.getViewport().getComponent(0);
-					if (canvasOrUpperNodeCanvas != null
-							&& canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-						((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
-					}
-				}
-			});
-		initWindowMenu();
-		
-		
-		
-		
-		mnNewMenuView.add(mntmBackground);
-
-		mntmBackground
-				.addActionListener(actionEvent -> {
-					tabTemp = tabbedPaneOriginal;
-					JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-
-					if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
-						BackgroundPopUp backgroundDialog = new BackgroundPopUp(
-								model, controller, canvas, null,
-								holegJFrame);
-						backgroundDialog
-								.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-						backgroundDialog.setVisible(true);
-					} else if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
-						GroupNodeCanvas uNodeCanvas = (GroupNodeCanvas) (scrollPane
-								.getViewport().getComponent(0));
-						BackgroundPopUp backgroundDialog = new BackgroundPopUp(
-								model, controller, null, uNodeCanvas.upperNode,
-								holegJFrame);
-						backgroundDialog
-								.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-						backgroundDialog.setVisible(true);
-						uNodeCanvas.repaint();
-					}
-				});
-
-
-
-
-
-		/**
-		 * add Help Menu and its items
-		 */
-		menuBar.add(mnHelp);
-		mnHelp.add(mntmIntroduction); 
-		mnHelp.add(mntmUserManual); 
-		mnHelp.add(mntmAlgorithmHelp); 
-		mnHelp.add(mntmCodeDoc);
-		mnHelp.add(mntmAboutUs);
-
-		tabbedPaneOriginal.addChangeListener(changeEvent -> {
-			if (tabbedPaneOriginal.getSelectedComponent() == null) {
-				Component tempC = tabbedPaneSplit.getSelectedComponent();
-				tabbedPaneSplit.setComponentAt(
-						tabbedPaneOriginal.getSelectedIndex(), null);
-				tabbedPaneOriginal.setComponentAt(
-						tabbedPaneOriginal.getSelectedIndex(), tempC);
-				tempC = tabbedPaneOriginal.getComponentAt((tabbedPaneOriginal
-						.getSelectedIndex() + 1)
-						% (tabbedPaneOriginal.getTabCount()));
-				tabbedPaneOriginal.setComponentAt(
-						(tabbedPaneOriginal.getSelectedIndex() + 1)
-								% (tabbedPaneOriginal.getTabCount()), null);
-				tabbedPaneSplit.setComponentAt(
-						(tabbedPaneOriginal.getSelectedIndex() + 1)
-								% (tabbedPaneOriginal.getTabCount()), tempC);
-				tabbedPaneSplit.setSelectedIndex((tabbedPaneOriginal
-						.getSelectedIndex() + 1)
-						% (tabbedPaneOriginal.getTabCount()));
-				contentPane.updateUI();
-			}
-		});
-
-		tabbedPaneSplit.addChangeListener(changeEvent -> {
-			if (tabbedPaneSplit.getSelectedComponent() == null && !initSplit) {
-				Component tempC = tabbedPaneOriginal
-						.getComponentAt(tabbedPaneSplit.getSelectedIndex());
-				tabbedPaneOriginal.setComponentAt(
-						tabbedPaneSplit.getSelectedIndex(), null);
-				tabbedPaneSplit.setComponentAt(
-						tabbedPaneSplit.getSelectedIndex(), tempC);
-
-				for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
-					if (tabbedPaneSplit.getComponentAt(i) != null
-							&& tabbedPaneSplit.getComponentAt(i) != tempC) {
-						tempC = tabbedPaneSplit.getComponentAt(i);
-						tabbedPaneSplit.setComponentAt(i, null);
-						tabbedPaneOriginal.setComponentAt(i, tempC);
-						break;
-					}
-				}
-				if (tabbedPaneOriginal.getSelectedIndex() == tabbedPaneSplit
-						.getSelectedIndex()) {
-					tabbedPaneOriginal.setSelectedIndex((tabbedPaneSplit
-							.getSelectedIndex() + 1)
-							% tabbedPaneOriginal.getTabCount());
-				}
-				contentPane.updateUI();
-			}
-		});
-		canvas.setBackground(Color.WHITE);
-		canvas.setPreferredSize(new Dimension(model.getCanvasX(), model
-				.getCanvasY()));
-		/********************
-		 * RIGHT CONTAINER (INFORMATION)
-		 **********************/
-		// Set up of the HolonElements section
-		// Two different Models: Multi for multi-selection mode and Single for
-		// single-selection mode (CPS-Object)
-		model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
-		model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
-		model.getTableHolonElement().setBorder(null);
-		model.getTableHolonElement().setFillsViewportHeight(true);
-		model.getTableHolonElement().setCellSelectionEnabled(true);
-		model.getTableHolonElement().setColumnSelectionAllowed(true);
-		/*
-		 * Register Clicks on ColumNames for sorting:
-		 */
-		model.getTableHolonElement().getTableHeader()
-				.addMouseListener(new MouseAdapter() {
-					public void mouseClicked(MouseEvent e) {
-						//TODO: sort
-						//clicked column
-						int col = model.getTableHolonElement().columnAtPoint(
-								e.getPoint());
-						//insert column into UpdateController
-						updCon.setSortBy(col);
-						//refresh HolonElementTable
-						updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-					}
-					
-
-					@Override
-					public void mouseExited(MouseEvent e) {
-						/**
-						 * Stop Editing, if mouse exits the Table
-						 */
-						JTable holElem = model.getTableHolonElement();
-						JTableHeader holElemHead = holElem.getTableHeader();
-						if(e.getX()<=0 || e.getX()>=holElemHead.getWidth() 
-								|| e.getY() <= 0){
-							CellEditor cellEditor = holElem.getCellEditor();
-							if (cellEditor != null) {
-							    if (cellEditor.getCellEditorValue() != null) {
-							    	/** TODO: Maybe try to save current Data */
-							        cellEditor.stopCellEditing();
-							    } else {
-							        cellEditor.cancelCellEditing();
-							    }
-							}
-						}
-						
-					}
-				});
-		model.getTableHolonElement().getTableHeader().setReorderingAllowed(false);
-
-		tableHolonElementScrollPane.setViewportView(model
-				.getTableHolonElement());
-		scrollElements.setLayout(new BorderLayout(0, 0));
-		scrollElements.add(panelHolonEl, BorderLayout.NORTH);
-		scrollElements.add(tableHolonElementScrollPane);
-		panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
-		toolBarHolonEl.add(btnAddHolEL);
-		toolBarHolonEl.add(btnDelHolEL);
-		toolBarHolonEl.setFloatable(false);
-		panelHolonEl.add(toolBarHolonEl);
-
-		// Set up of the Properties section
-		tableProperties.setModel(model.getPropertyTable());
-		tableProperties.setFillsViewportHeight(true);
-		tableProperties.setCellSelectionEnabled(true);
-		tableProperties.setColumnSelectionAllowed(true);
-		scrollProperties.setViewportView(tableProperties);
-
-		// Set up of the Graph section
-		tableGraph.setModel(tableModelGraph);
-		tableGraph.setFillsViewportHeight(true);
-		tableGraph.setCellSelectionEnabled(true);
-		tableGraph.setColumnSelectionAllowed(true);
-		scrollGraph.setViewportView(unitGraph);
-		graphLabel.setLayout(new BorderLayout(0, 10));
-		graphLabel.add(maxGraph, BorderLayout.NORTH);
-		graphLabel.add(medGraph, BorderLayout.CENTER);
-		graphLabel.add(minGraph, BorderLayout.SOUTH);
-
-		
-		
-		
-		
-		toolBarGraph.setFloatable(false);
-		toolBarGraph.setAlignmentY(Component.RIGHT_ALIGNMENT);	
-		
-		
-		localPeriodButton.setToolTipText("Toggle Local/Global Mode");
-		toolBarGraph.add(localPeriodButton);
-		//ComboBox
-		localPeriodInput.setEditable(true);
-		localPeriodInput.setVisible(false);
-		localPeriodInput.setMaximumSize(new Dimension(20,23));
-		localPeriodInput.addItemListener(aListener->{
-			if(aListener.getStateChange() == ItemEvent.DESELECTED) {
-				validateInput(localPeriodInput.getEditor().getItem().toString(), true);
-			}
-			
-		});
-		
-		toolBarGraph.add(localPeriodInput);
-				
-		//localPeriodButtonFunction
-		localPeriodButton.addActionListener(actionEvent->{
-			boolean newState= !localPeriodInput.isVisible();
-			changeLocalPeriodButtonAppeareance(newState);
-			unitGraph.setUseLocalPeriod(newState);
-		});
-		
-		
-		toolBarGraph.add(Box.createHorizontalGlue());
-		resetButton.setToolTipText("Reset");
-		resetButton.addActionListener(actionEvent ->  unitGraph.reset());
-		toolBarGraph.add(resetButton);
-		
-		
-		
-		
-		
-		scrollGraph.setRowHeaderView(graphLabel);
-		scrollGraph.setColumnHeaderView(toolBarGraph);
-
-		tables.add(model.getSingleTable());
-		tables.add(model.getMultiTable());
-		/***********************
-		 * HolonElement Table Actions
-		 **********************/
-		/*
-		 * Add HolonElement to given HolonObject
-		 */
-		btnAddHolEL.addActionListener(actionEvent -> {
-			if (model.getSelectedCpsObjects().size() == 1) {
-				AbstractCanvasObject tempCpsObject = updCon.getActualCps();
-				if (tempCpsObject != null
-						&& tempCpsObject.getClass() == HolonObject.class
-						&& tempCpsObject.getId() != 0) {
-					addElementPopUp = new AddElementPopUp(holegJFrame);
-					addElementPopUp.setActualHolonObject((HolonObject)updCon.getActualCps());
-					addElementPopUp.setVisible(true);
-					HolonElement ele = addElementPopUp.getElement();
-					if (ele != null) {
-						controller.addElementCanvasObject(
-								tempCpsObject.getId(), ele.getEleName(),
-								ele.getAmount(), ele.getEnergyPerElement(),
-								ele.getId());
-					}
-					controller.calculateStateAndVisualForTimeStep(model
-							.getCurIteration());
-					triggerUpdateController(null);
-					contentPane.updateUI();
-				}
-			}else
-			{
-				JOptionPane.showMessageDialog(contentPane, "No object selected.\nPlease select a object first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
-			}
-		});
-		btnAddHolEL.setIcon(new ImageIcon(ImageImport.loadImage("Images/plus.png", 16, 16)));
-		btnAddHolEL.setToolTipText("<html><b>Add Element</b><br>Add a new HolonElement to the HolonObject.</html>");
-		
-		
-		/*
-		 * Delete the chosen HolonElement of the selected HolonObject,
-		 * Multi-Selection for CpsObjects as well as for HolonElements possible
-		 */
-		btnDelHolEL.addActionListener(actionEvent -> {
-			// For Single Selection of CpsObject
-				if (model.getSelectedCpsObjects().size() == 1) {
-					if (updCon.getActualCps().getClass() == HolonObject.class) {
-						HolonObject obj = (HolonObject) updCon.getActualCps();
-						if(selectedElements.isEmpty())
-						{
-							JOptionPane.showMessageDialog(contentPane, "No element selectet.\nPlease select a element in the list first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
-						}
-						for (HolonElement e : selectedElements) {
-							controller.deleteElementCanvas(obj.getId(),
-									e.getId());
-							controller.calculateStateAndVisualForTimeStep(model
-									.getCurIteration());
-							triggerUpdateController(null);
-							contentPane.updateUI();
-							// Names displayed in graph are not updated
-			}
-			model.getEleToDelete().clear();
-			selectedElements.clear();
-		}
-		// For MultiSelection of CpsObject
-	} else if (model.getSelectedCpsObjects().size() > 1) {
-		for (Integer i : model.getEleToDelete().keySet()) {
-			for (HolonElement e : model.getEleToDelete().get(i)) {
-				controller.deleteElementCanvas(i, e.getId());
-			}
-		}
-		triggerUpdateController(null);
-		model.getEleToDelete().clear();
-		selectedElements.clear();
-	}else
-			{
-				JOptionPane.showMessageDialog(contentPane, "No object selectet.\nPlease select a object first." , "No object selectet" , JOptionPane.INFORMATION_MESSAGE);
-			}
-	triggerUpdateController(null);
-	elementGraph.setText("None");
-	holonEleNamesDisplayed = "None";
-})		;
-		btnDelHolEL.setIcon(new ImageIcon(ImageImport.loadImage("Images/minus.png", 16, 16)));
-		btnDelHolEL.setToolTipText("<html><b>Remove Element</b><br>Removes the selected HolonElement from the HolonObject.</html>");
-		/*
-		 * Communication between HolonElement Table and displayed Graph and
-		 * Properties, as well as selection of different HolonElements
-		 */
-		model.getTableHolonElement().addMouseListener(new MouseAdapter() {
-			public void mousePressed(MouseEvent e) {
-				HolonObject obj = null;
-				if (model.getSelectedCpsObjects().size() == 1
-						&& model.getSelectedCpsObjects().get(0) instanceof HolonObject) {
-					obj = (HolonObject) updCon.getActualCps();
-				}
-				yValueElements = e.getY();
-				HolonElement ele;
-				// Search for current clicked HolonElement
-				if (model.getSelectedCpsObjects().size() == 1) {
-					ele = updCon.getActualHolonElement(obj, yValueElements, 0,
-							tables);
-				} else {
-					ele = updCon.getActualHolonElement(null, yValueElements, 0,
-							tables);
-				}
-				// Multi-Selection of HolonElements through control button +
-				// mouse click
-				if (ele != null) {
-					// make energy-consumption graph visible
-					showScrollGraph();
-
-					if (e.isControlDown()) {
-						if (!selectedElements.contains(ele)) {
-							selectedElements.add(ele);
-							if (!holonEleNamesDisplayed.equals("None")) {
-								holonEleNamesDisplayed = holonEleNamesDisplayed
-										+ "; " + ele.getEleName() + " ";
-							} else {
-								holonEleNamesDisplayed = ele.getEleName() + " ";
-							}
-							updateUnitGraph((GraphEditable)selectedElements.get(selectedElements.size()-1));
-						}
-						updCon.getActualHolonElement(null, yValueElements, 2,
-								tables);
-					}
-					// if no control-button pressed but a HolonElement chosen
-					else {
-						selectedElements.clear();
-						selectedElements.add(ele);
-						updCon.getActualHolonElement(null, yValueElements, 1,
-								tables);
-						holonEleNamesDisplayed = ele.getEleName() + " ";
-						updateUnitGraph((GraphEditable)selectedElements.get(selectedElements.size()-1));
-					}
-				} else {
-					elementGraph.setText("None");
-					hideScrollGraph();
-				}
-				// if any HolonElement is double-clicked --> Edit-Mode started
-				// for selected HolonElement
-				if (e.getClickCount() == 2) {
-					yThis = e.getY();
-					xThis = e.getX();
-				}
-				// for single click and empty slot
-				if (e.getClickCount() == 1 && ele == null) {
-					selectedElements.clear();
-					holonEleNamesDisplayed = "None";
-				}
-				elementGraph.setText(holonEleNamesDisplayed);
-				yBTis = e.getY();
-				xBThis = e.getX();
-
-			}
-			
-			@Override
-			public void mouseExited(MouseEvent e) {
-				/**
-				 * Stop Editing, if mouse exits the Table
-				 */
-				JTable holElem = model.getTableHolonElement();
-				if(e.getX()<=0 || e.getX()>=holElem.getWidth() 
-						/*|| e.getY() <= 0*/|| e.getY()>= holElem.getHeight()){
-					CellEditor cellEditor = holElem.getCellEditor();
-					if (cellEditor != null) {
-					    if (cellEditor.getCellEditorValue() != null) {
-					    	/** TODO: Maybe try to save current Data */
-					        cellEditor.stopCellEditing();
-					    } else {
-					        cellEditor.cancelCellEditing();
-					    }
-					}
-				}
-				
-			}
-			
-		});
-		
-		/*
-		 * Triggered every time a change is made
-		 */
-		model.getTableHolonElement()
-				.addPropertyChangeListener(propertyChangeEvent -> {
-					try {
-						int yMouse = yThis;
-						int yBMouse = yBTis;
-						int selectedValueY = (int) Math.floor(yMouse / 16);
-						int selectedValueBY = (int) Math.floor(yBMouse / 16);
-						// ------------------ 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));
-							if (updCon.getHolonObj(yMouse,
-									model.getMultiTable()) != null) {
-								// For active column (boolean with a checkbox)
-								if (selectedValueBX == 6) {
-									System.out.println("selectedValueBX == 6");
-									HolonElement eleBTemp = updCon
-											.getActualHolonElement(null,
-													yBMouse, 0, tables);
-									String newBStuff = model
-											.getMultiTable()
-											.getValueAt(selectedValueBY,
-													selectedValueBX).toString();
-									Boolean bTemp = Boolean
-											.parseBoolean(newBStuff);
-									eleBTemp.setActive(bTemp);
-								}
-								// For activeFlex column (boolean with a
-								// checkbox)
-								else if (selectedValueBX == 7) {
-									HolonElement eleBTemp = updCon
-											.getActualHolonElement(null,
-													yBMouse, 0, tables);
-									String newBStuff = model
-											.getMultiTable()
-											.getValueAt(selectedValueBY,
-													selectedValueBX).toString();
-									Boolean bTemp = Boolean
-											.parseBoolean(newBStuff);
-									eleBTemp.setActive(bTemp);
-								} else {
-									//TODO: check all possible fields.
-									// Update of HolonElement
-									HolonElement eleTemp = updCon
-											.getActualHolonElement(null,
-													yMouse, 0, tables);
-									String newStuff = model
-											.getMultiTable()
-											.getValueAt(selectedValueY,
-													selectedValueX).toString();
-									
-									// Name update
-									if (selectedValueX == 2) {
-										eleTemp.setEleName(newStuff);
-									}
-									// Energy Update
-									else if (selectedValueX == 3) {
-										Float ftemp = Float
-												.parseFloat(newStuff);
-										eleTemp.setEnergyPerElement(ftemp);
-									}
-									// Flexibility
-									else if (selectedValueX == 4) {
-										
-										
-										
-									}
-									// Amount of Elements update
-									else if (selectedValueX == 5) {
-										Integer iTemp = Integer
-												.parseInt(newStuff);
-										eleTemp.setAmount(iTemp);
-									}
-									else if (selectedValueX == 6) {
-									}
-								}
-							}
-						} // ------------------ 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) {
-									eleTemp = updCon.getActualHolonElement(
-											(HolonObject) updCon.getActualCps(),
-											yBMouse, 0, tables);
-									String newBStuff = model
-											.getSingleTable()
-											.getValueAt(selectedValueBY,
-													selectedValueBX).toString();
-									Boolean bTemp = Boolean
-											.parseBoolean(newBStuff);
-									eleTemp.setActive(bTemp);
-
-								} // For activeFlex column (boolean with a
-									// checkbox)
-								else if (selectedValueBX == 6) {
-									eleTemp = updCon.getActualHolonElement(
-											(HolonObject) updCon.getActualCps(),
-											yBMouse, 0, tables);
-									String newBStuff = model
-											.getSingleTable()
-											.getValueAt(selectedValueBY,
-													selectedValueBX -1).toString();
-									eleTemp.setActive(Boolean
-											.parseBoolean(newBStuff));
-
-								} else {
-									//TODO check all possible assignements.
-									// Update of HolonElement
-									eleTemp = updCon.getActualHolonElement(
-											(HolonObject) updCon.getActualCps(),
-											yMouse, 0, tables);
-									String newStuff = model
-											.getSingleTable()
-											.getValueAt(selectedValueY,
-													selectedValueX).toString();
-									// Name update
-									if (selectedValueX == 1) {
-										eleTemp.setEleName(newStuff);
-									} // Energy Update
-									else if (selectedValueX == 2) {
-										Float ftemp = Float
-												.parseFloat(newStuff);
-										eleTemp.setEnergyPerElement(ftemp);
-									} // Flexibility
-									else if (selectedValueX == 3) {
-									}
-									// Amount of Elements update
-									else if (selectedValueX == 4) {
-										Integer iTemp = Integer
-												.parseInt(newStuff);
-										eleTemp.setAmount(iTemp);
-									}
-								}
-
-								// set all cells anew, if anything was changed
-								updateElementTableAfterChange(eleTemp,
-										selectedValueBY);
-							}
-						}
-						controller.calculateStateAndVisualForTimeStep(model
-								.getCurIteration());
-						model.getSingleTable().fireTableDataChanged();
-						triggerUpdateController(null);
-						contentPane.updateUI();
-						unitGraph.repaint();
-
-						// trigger update of table after UnitGraph was painted
-						SwingUtilities.invokeLater(() -> {
-							triggerUpdateController(null);
-						});
-					} catch (Exception e) {
-					}
-				});
-		/***********************
-		 * HolonElement Properties Actions
-		 **********************/
-
-		/*
-		 * Update of the mouse coord for Edit-Mode
-		 */
-		tableProperties.addMouseListener(new MouseAdapter() {
-			public void mousePressed(MouseEvent e) {
-				if (e.getClickCount() == 2) {
-					yProThis = e.getY();
-					xProThis = e.getX();
-				}
-				yProThisOneClick = e.getY();
-				xProThisOneClick = e.getX();
-			}
-		});
-
-		/*
-		 * Update any change in the Property table
-		 */
-		tableProperties.addPropertyChangeListener(propertyChangeEvent -> {
-			try {
-				Object temp;
-				Object btemp;
-				int selValueY = (int) Math.floor(yProThis / 16);
-				int selValueX = (int) Math.floor(xProThis
-						/ (tableProperties.getWidth() / 2));
-				int selValueYBool = (int) Math.floor(yProThisOneClick / 16);
-				int selValueXBool = (int) Math.floor(xProThisOneClick
-						/ (tableProperties.getWidth() / 2));
-				if (updCon.getActualCps() != null) {
-					temp = model.getPropertyTable().getValueAt(selValueY,
-							selValueX);
-					btemp = model.getPropertyTable().getValueAt(selValueYBool,
-							selValueXBool);
-					// Case: Switch selected
-
-				if (updCon.getActualCps() instanceof HolonSwitch) {
-					if (selValueY == 0 && selValueX != 0) {
-						updCon.getActualCps().setName(temp.toString());
-					}
-					if (selValueYBool == 2) {
-						Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
-						((HolonSwitch) updCon.getActualCps())
-								.setManualMode(bbTemp);
-						if (bbTemp) {
-							model.getPropertyTable()
-									.setCellEditable(3, 1, true);
-						} else {
-							model.getPropertyTable().setCellEditable(3, 1,
-									false);
-						}
-					} else if (selValueYBool == 3) {
-						if (((HolonSwitch) updCon.getActualCps())
-								.getManualMode()) {
-							model.getPropertyTable()
-									.setCellEditable(3, 1, true);
-							Boolean bTemp = Boolean.parseBoolean(btemp
-									.toString());
-							((HolonSwitch) updCon.getActualCps())
-									.setManualState(bTemp);
-						}
-					}
-				} // Case: UpperNode selected
-				else if (updCon.getActualCps() instanceof GroupNode
-						&& selValueX != 0) {
-					// Name edition through double click
-					updCon.getActualCps().setName(temp.toString());
-					// Update of name on the tab in the tab section
-					for (int index = 4; index < tabbedPaneOriginal
-							.getTabCount(); index++) {
-						tabTemp = tabbedPaneOriginal;
-						JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-
-						GroupNodeCanvas unc = ((GroupNodeCanvas) scrollPane
-								.getViewport().getComponent(0));
-
-						if (unc.upperNode.getId() == updCon.getActualCps()
-								.getId()) {
-							tabbedPaneOriginal.setTitleAt(index,
-									unc.upperNode.getName());
-							tabbedPaneOriginal.updateUI();
-							if (!initSplit) {
-								tabbedPaneSplit.setTitleAt(index,
-										unc.upperNode.getName());
-								tabbedPaneSplit.updateUI();
-							}
-						}
-					}
-				} // Case: HolonObject is selected
-				else if (updCon.getActualCps() instanceof HolonObject
-						&& selValueX != 0) {
-					// Name edition through double click
-					updCon.getActualCps().setName(temp.toString());
-				}
-			} // Case: Edge is selected
-			else {
-				temp = model.getPropertyTable()
-						.getValueAt(selValueY, selValueX);
-				btemp = model.getPropertyTable().getValueAt(selValueYBool,
-						selValueXBool);
-				// Edit modus for capacity by double clicking
-				if (selValueY == 2) {
-					Float ftemp;
-					if (Float.parseFloat(temp.toString()) >= 0.0) {
-						ftemp = Float.parseFloat(temp.toString());
-					} else {
-						ftemp = model.getSelectedEdge().getCapacity();
-					}
-					model.getSelectedEdge().setCapacity(ftemp);
-				}
-			}
-			canvas.repaint();
-		} catch (Exception e) {
-		}
-	})	;
-
-		/***********************
-		 * HolonElement Graph Actions
-		 **********************/
-		
-		/*
-		 * Update Local Period of an Element Graph
-		 */
-		unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
-			@Override
-			 public void keyReleased(KeyEvent e) {
-				try{
-					int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
-					unitGraphLocalPeriod.setBackground(Color.WHITE);
-					/**
-					 * set local graph Period
-					 */
-					if(e.getKeyCode() == KeyEvent.VK_ENTER)
-						unitGraph.setLocalPeriod(localLength);						
-				}catch(NumberFormatException ex){
-					unitGraphLocalPeriod.setBackground(PALE_RED);
-				}
-				
-			}
-		});
-		
-		/*****************************
-		 * RIGHT CONTAINER DONE
-		 *****************************/
-
-		holegJFrame.getContentPane().setLayout(new BorderLayout(0, 0));
-		/****************
-		 * Tree Stuff
-		 ****************/
-
-		// Override Key Actions
-		inputMap = categoryTree.getInputMap();
-		inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
-		inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
-		inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
-		inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
-
-		TreeCellRenderer customRenderer = new TreeCellRenderer() {
-			@Override
-			public Component getTreeCellRendererComponent(JTree tree,
-					Object value, boolean selected, boolean expanded,
-					boolean leaf, int row, boolean hasFocus) {
-				JLabel label = new JLabel();
-				Image imgR;
-				if (leaf) {
-					for (Category cat : model.getCategories()) {
-						for (AbstractCanvasObject cps : cat.getObjects()) {
-							if (value.toString().compareTo(cps.getObjName()) == 0) {
-								imgR = ImageImport.loadImage(cps.getImage(), 50,
-										50);
-								if (imgR != null) {
-									label.setIcon(new ImageIcon(imgR));
-								}
-								label.setText(cps.getName());
-							}
-						}
-					}
-				}
-				tree.setRowHeight(50);
-				if (hasFocus) {
-					label.setForeground(new Color(0, 0, 255));
-					label.setOpaque(true);
-				}
-				if (label.getText().length() == 0) {
-					label.setText(value.toString());
-					if (value.toString().compareTo("Categories") != 0) {
-						label.setIcon(new ImageIcon(ImageImport.loadImage(
-								"/Images/folder.png")));
-					}
-				}
-
-				return label;
-
-			}
-		};
-		
-		categoryTree.setCellRenderer(customRenderer);
-
-		categoryTree.addMouseMotionListener(new MouseMotionAdapter() {
-
-			public void mouseDragged(MouseEvent e){
-				checkForDragAndDrop(e);
-			}
-			
-			/**
-			 * checks if an object of the current Panel
-			 * could be replaced by the dragged object
-			 * @param e
-			 */
-			private void checkForDragAndDrop(MouseEvent e){
-				try {
-					/**
-					 * if no object gets dragged -> finished
-					 */
-					if(!dragging)return;
-					
-					/**
-					 * select the current Panel
-					 */
-					chooseTabTemp();				
-					JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-					if(scrollPane == null)return;
-					Component canvasOrUpperNodeCanvas = scrollPane
-							.getViewport().getComponent(0);
-					
-					/**
-					 * check for replacements on the canvas
-					 */
-					if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-						GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
-						if(unc.getMousePosition()==null)return;
-						int x = (int) unc.getMousePosition().getX()+16;
-						int y = (int) unc.getMousePosition().getY()+16;
-						
-						/**
-						 * if in upperNode
-						 */
-						if (x <= unc.upperNode.getLeftBorder()) return;
-						
-						/**
-						 * check for replacement
-						 */
-						unc.checkForReplacement(x, y);
-						
-						/**
-						 * repaint 
-						 */
-						unc.invalidate();
-						unc.repaint();
-					} else {
-						if(canvas.getMousePosition()==null)return;
-						int x = (int) canvas.getMousePosition().getX()+16;
-						int y = (int) canvas.getMousePosition().getY()+16;
-						
-						/**
-						 * check for replacement
-						 */
-						canvas.checkForReplacement(x, y);
-						
-						/**
-						 * repaint
-						 */
-						canvas.invalidate();
-						canvas.repaint();
-					}
-					contentPane.updateUI();
-					
-				} catch (Exception eex) {
-					eex.printStackTrace();
-				}
-			}});
-
-		
-		categoryTree.addMouseListener(new MouseAdapter() {
-			
-			public void mouseReleased(MouseEvent e) {
-				try {
-					if (dragging) {
-						chooseTabTemp();
-						JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-						Component canvasOrUpperNodeCanvas = scrollPane
-								.getViewport().getComponent(0);
-
-						if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
-							GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
-							int x = (int) unc.getMousePosition().getX() + 16;
-							int y = (int) unc.getMousePosition().getY() + 16;
-
-							if (x > unc.upperNode.getLeftBorder()) {
-
-								AbstractCanvasObject h = null;
-								if (tempCps instanceof HolonObject) {
-									h = new HolonObject((HolonObject)tempCps);
-								}
-								if (tempCps instanceof HolonSwitch) {
-									h = new HolonSwitch(tempCps);
-								}
-								h.setPosition(x, y);
-
-								/**
-								 * close UpperNodeTabs of replaced UpperNode
-								 */
-								if(unc.mayBeReplaced!=null &&unc.mayBeReplaced instanceof GroupNode){
-									unc.closeUpperNodeTab(unc.mayBeReplaced.getId());
-								}
-								controller.addObjUpperNode(h, unc.upperNode);
-								
-								/**
-								 * object would be replaced
-								 */
-								unc.mayBeReplaced = null; 
-								unc.invalidate();
-								controller.calculateStateAndVisualForCurrentTimeStep();
-								unc.repaint();
-								unc.setXY((int) canvas.getMousePosition()
-										.getX(), (int) canvas
-										.getMousePosition().getY());
-							}
-						} else {
-							int x = (int) canvas.getMousePosition().getX() + 16;
-							int y = (int) canvas.getMousePosition().getY() + 16;
-
-							AbstractCanvasObject h = null;
-							if (tempCps instanceof HolonObject) {
-								h = new HolonObject((HolonObject)tempCps);
-							}
-							if (tempCps instanceof HolonSwitch) {
-								h = new HolonSwitch(tempCps);
-							}
-							
-							h.setPosition(x, y);
-							
-							/**
-							 * close UpperNodeTabs of replaced UpperNode
-							 */
-							if(canvas.mayBeReplaced!=null &&canvas.mayBeReplaced instanceof GroupNode){
-								canvas.closeUpperNodeTab(canvas.mayBeReplaced.getId());
-							}
-							controller.addObjectCanvas(h);
-							/**
-							 * no object should get replaced
-							 */
-							canvas.mayBeReplaced = null;
-							canvas.invalidate();
-							canvas.setXY(
-									(int) canvas.getMousePosition().getX(),
-									(int) canvas.getMousePosition().getY());
-							canvas.repaint();
-						}
-						controller.calculateStateAndVisualForCurrentTimeStep();
-						contentPane.updateUI();
-						dragging = false;
-					}
-				} catch (Exception eex) {
-				}
-				holegJFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
-			}
-		});
-		
-
-		popmenuEdit.add(editItem);
-		popmenuEdit.add(removeItem);
-		editItem.setEnabled(false);
-		editItem.addActionListener(actionEvent -> {
-		});
-		categoryTree.addMouseListener(new MouseAdapter() {
-		
-			public void mousePressed(MouseEvent e) {
-				try {
-					actualObjectClicked = categoryTree
-							.getPathForLocation(e.getX(), e.getY())
-							.getLastPathComponent().toString();
-					// if an Object was selected, the porperties are shown in
-					// the table
-					DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) categoryTree
-							.getPathForLocation(e.getX(), e.getY())
-							.getLastPathComponent();
-					if (selectedNode.getLevel() == 2) {
-						controller.searchCategoryObject(selectedNode
-								.getParent().toString(), selectedNode
-								.toString());
-						updCon.deleteRows(model.getSingleTable());
-						updCon.deleteRows(model.getMultiTable());
-						// if (selected instanceof HolonObject && selected !=
-						// null) {
-						// selected = (HolonObject) selected;
-						// fillElementTable(((HolonObject)
-						// selected).getElements());
-						// }
-					}
-					if (SwingUtilities.isRightMouseButton(e)) {
-						for (Category cat : model.getCategories()) {
-							for (AbstractCanvasObject cps : cat.getObjects()) {
-								if (actualObjectClicked.compareTo(cps
-										.getObjName()) == 0
-										&& !(cps instanceof HolonSwitch)) {
-									editItem.setEnabled(true);
-									popmenuEdit.show(e.getComponent(),
-											e.getX(), e.getY());
-									catOfObjToBeEdited = selectedNode
-											.getParent().toString();
-									tempCps = cps;
-								}
-							}
-						}
-					} else {
-						for (Category cat : model.getCategories()) {
-							for (AbstractCanvasObject cps : cat.getObjects()) {
-								if (actualObjectClicked.compareTo(cps
-										.getObjName()) == 0) {
-									File checkPath = new File(cps.getImage());
-									if (checkPath.exists()) {
-										img = new ImageIcon(cps.getImage())
-												.getImage()
-												.getScaledInstance(
-														32,
-														32,
-														java.awt.Image.SCALE_SMOOTH);
-									} else {
-										img = ImageImport.loadImage(
-												cps.getImage(), 32, 32);
-									}
-									tempCps = cps;
-									dragging = true;
-									Cursor cursor = Toolkit.getDefaultToolkit()
-											.createCustomCursor(img,
-													new Point(0, 0), "Image");
-									holegJFrame.setCursor(cursor);
-								}
-							}
-						}
-					}
-				} catch (Exception eex) {
-				}
-			}
-		});
-		editItem.addActionListener(actionEvent -> {
-			// Remove the selected Object object
-			//AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame parentFrame)
-			System.out.println("Edit");
-			addObjectPopUP = new AddObjectPopUp(true, tempCps,
-					catOfObjToBeEdited, holegJFrame);
-			addObjectPopUP.setCategory(catOfObjToBeEdited);
-			addObjectPopUP.setController(controller);
-			addObjectPopUP.setVisible(true);
-		});
-		removeItem.addActionListener(actionEvent -> {
-			// Remove the selected Object object
-			try {
-				System.out.println("catOfObjToBeEdited:" + catOfObjToBeEdited + ", tempCps:" + tempCps);
-				controller.delObjectCategory(catOfObjToBeEdited, tempCps.getName());				
-			}catch(IOException e) {
-				System.err.println("IOException");
-				e.printStackTrace();
-			}
-		});
-		scrollPane1.setViewportView(categoryTree);
-
-		scrollPane1.setColumnHeaderView(panel);
-		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
-		toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
-		toolBar.setFloatable(false);
-
-		panel.add(toolBar);
-		btnAddPopUp.add(mItemNew);
-		mItemNew.addActionListener(actionEvent -> {
-			new CreateNewDialog(controller, holegJFrame);
-		});
-		btnAddPopUp.addSeparator();
-		btnAddPopUp.add(mItemCategory);
-		mItemCategory.addActionListener(actionEvent -> {
-			new CreateNewDialog(controller,Option.Category, holegJFrame);
-		});
-		btnAddPopUp.add(mItemObject);
-		mItemObject.addActionListener(actionEvent -> {
-			new CreateNewDialog(controller,Option.Object, holegJFrame);
-		});
-		btnAddPopUp.add(mItemSwitch);
-		mItemSwitch.addActionListener(actionEvent -> {
-			new CreateNewDialog(controller,Option.Switch, holegJFrame);
-		});
-		btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
-		btnAdd.setIcon(new ImageIcon(ImageImport.loadImage("Images/plus.png", 16, 16)));
-		btnAdd.setToolTipText("<html><b>New</b><br>Add a new Category or Item to the library.</html>");
-		toolBar.add(btnAdd);
-		/**
-		 * Help Menu Action Listeners
-		 */
-		
-		/**
-		 * URL of the telecommunication git Wiki
-		 */
-		String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
-		
-		/** open Introduction Web Page */
-		mntmIntroduction.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e){
-				openWebpage(tkWikiWebpage + "Introduction+V2.1");
-			}
-		});
-		
-		/** open UserManual WebPage */
-		mntmUserManual.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e){
-				openWebpage(tkWikiWebpage + "User+Manual+V2.1");
-			}
-		});
-		
-		/** open Algorithm Help Web Page*/
-		mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e){
-				openWebpage(tkWikiWebpage + "Algorithms+V2.1");
-			}
-		});
-		
-		/** open Code Documentation Web Page */
-		mntmCodeDoc.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e){
-				openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
-			}
-		});
-		
-		/**
-		 * Pop up - About Us with some important information about the
-		 * developers, source and programming stuff
-		 */
-		mntmAboutUs.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e) {
-				aboutUsPopUp = new AboutUsPopUp(holegJFrame);
-				aboutUsPopUp.setVisible(true);
-			}
-		});
-
-		/**
-		 * Update of every interaction between the user and the canvas (only on
-		 * the canvas). Basically the update of all the information concerning
-		 * the clicked HolonObject. For multi-selection, the propertyTable would
-		 * be disabled
-		 */
-		canvas.addMouseListener(new MouseAdapter() {
-			@Override
-			public void mousePressed(MouseEvent e) {
-
-			}
-
-			@Override
-			public void mouseReleased(MouseEvent e) {
-				holonEleNamesDisplayed = "None";
-				// If any empty space is clicked
-				if (temp == null || temp.getId() != model.getSelectedObjectID()) {
-					hideScrollGraph();
-					elementGraph.setText("None");
-				}
-				temp = updCon.getActualCps();
-				// 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.isControlDown() && temp != null) {
-					if (model.getSelectedCpsObjects().contains(temp)) {
-						controller.deleteSelectedObject(temp);
-					} else {
-						controller.addSelectedObject(temp);
-					}
-				}
-				if (temp instanceof HolonSwitch) {
-					showScrollGraph();
-					updateUnitGraph((GraphEditable)temp);
-				}
-				// Write new data in the PropertyTable
-				triggerUpdateController(temp);
-
-				// New Tab with NodeOfNode
-				if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
-						&& temp instanceof GroupNode) {
-					openNewUpperNodeTab();
-					try {
-						controller.autoSave();
-					} catch (IOException e1) {
-						e1.printStackTrace();
-					}
-				}
-				if (model.getSelectedCpsObjects().size() > 1) {
-					model.getTableHolonElement()
-							.setModel(model.getMultiTable());
-				} else if (model.getSelectedCpsObjects().size() == 1) {
-					model.getTableHolonElement().setModel(
-							model.getSingleTable());
-				}
-
-			}
-
-		});
-
-
-		
-
-		// Del Button
-		btnDel.addActionListener(actionEvent -> {
-			Object nodeInfo = categoryTree.getLastSelectedPathComponent();
-			if (nodeInfo != null) {
-				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
-				String nodeName = selectedNode.getUserObject().toString();
-				int depthOfNode = selectedNode.getLevel();
-				try {
-					switch (depthOfNode) {
-					case 1:
-						int dialogResult = JOptionPane.showConfirmDialog(
-								holegJFrame, eraseCategory + nodeName
-										+ "?", warningText,
-								JOptionPane.YES_NO_OPTION);
-						if (dialogResult == JOptionPane.YES_OPTION) {
-							controller.deleteCategory(nodeName);
-						}
-						break;
-					case 2:
-						DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode
-								.getParent();
-						controller.delObjectCategory(parent.getUserObject()
-								.toString(), nodeName);
-						break;
-
-					default:
-						JOptionPane.showMessageDialog(holegJFrame,
-								selectObjBeforeErase);
-					}
-				} catch (Exception e2) {
-				}
-
-			} else {
-				JOptionPane.showMessageDialog(holegJFrame,
-						selectObjBeforeErase);
-			}
-			categoryTree.repaint();
-		});
-		btnDel.setIcon(new ImageIcon(ImageImport.loadImage("Images/minus.png", 16, 16)));
-		btnDel.setToolTipText("<html><b>Delete</b><br>Removes a Category or a Category Item.</html>");
-		toolBar.add(btnDel);
-		
-
-		holegJFrame.getContentPane().add(splitPane);
-
-		mntmNew.addActionListener(actionEvent -> {
-			if (model.getObjectsOnCanvas().size() != 0) {
-				int newWarning = JOptionPane.YES_NO_OPTION;
-				int dialogForNewWarning = JOptionPane.showConfirmDialog(
-						holegJFrame, saveBeforeNew, warningText,
-						newWarning);
-				if (dialogForNewWarning == JOptionPane.YES_OPTION) {
-					mntmSave.doClick();
-				}
-			}
-
-			model.getEdgesOnCanvas().removeAll(model.getEdgesOnCanvas());
-			model.getObjectsOnCanvas().removeAll(model.getObjectsOnCanvas());
-			controller.setSelectedObjectID(0);
-			controller.setSelecteEdge(null);
-			controller.setCurIteration(0);
-			hideScrollGraph();
-			elementGraph.setText("None");
-			canvas.tempCps = null;
-			canvas.repaint();
-			IdCounter.resetObjectCounter(CounterType.Object);
-			IdCounter.resetObjectCounter(CounterType.Element);
-			controller.calculateStateAndVisualForCurrentTimeStep();
-		});
-
-		mntmOpen.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent evt) {
-				menuFileExitActionPerformed();
-			}
-
-			private void menuFileExitActionPerformed() {
-				JFileChooser fileChooser = new JFileChooser();
-				fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/exampleNetworks/"));
-				FileNameExtensionFilter holonFilter = new FileNameExtensionFilter(
-						"Holon Save File(*.holon)", "holon");
-				fileChooser.setFileFilter(holonFilter);
-
-				if (fileChooser.showOpenDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
-					File file = fileChooser.getSelectedFile();
-
-					try {
-						controller.loadFile(file.getAbsolutePath());
-						canvas.repaint();
-						categoryTree.repaint();
-						controller.calculateStateAndVisualForCurrentTimeStep();
-					} catch (IOException | ArchiveException e) {
-						e.printStackTrace();
-						JLabel message = new JLabel(
-								"The savefile is corrupt and cannot be opened.");
-						JOptionPane.showMessageDialog(holegJFrame,
-								message, "", JOptionPane.ERROR_MESSAGE);
-					}
-				}
-			}
-		});
-
-		mntmSave.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent evt) {
-				menuSaveActionPerformed();
-			}
-
-			private void menuSaveActionPerformed() {
-				JFileChooser fileChooser = new JFileChooser();
-				FileNameExtensionFilter holonFilter = new FileNameExtensionFilter(
-						"Holon Save File(*.holon)", "holon");
-				fileChooser.setFileFilter(holonFilter);
-
-				if (fileChooser.showSaveDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
-					File selectedFile = fileChooser.getSelectedFile();
-					String fileName = selectedFile.getName();
-					String fullPath = fileChooser.getSelectedFile().getPath();
-					if (fileChooser.getFileFilter().equals(holonFilter)) {
-						if (!fileName.contains("."))
-							fullPath += ".holon";
-					}
-					if (!fullPath.endsWith(".holon")) {
-						String suffix = fullPath.substring(fullPath.lastIndexOf("."),
-								fullPath.length());
-						String[] options = new String[] { "keep .holon",
-								"use " + suffix };
-
-						JLabel message = new JLabel(
-								"Are you sure to use the extension \"" + suffix
-										+ "\" instead of \".holon\"?");
-
-						int response = JOptionPane.showOptionDialog(
-								holegJFrame, message, "",
-								JOptionPane.DEFAULT_OPTION,
-								JOptionPane.QUESTION_MESSAGE, null, options,
-								options[1]);
-
-						if (response == 0)
-							fullPath = fullPath.replace(suffix, ".holon");
-					}
-
-					try {
-						controller.saveFile(new File(fullPath).getAbsolutePath());
-					} catch (IOException | ArchiveException e) {
-						e.printStackTrace();
-					}
-				}
-			}
-		});
-
-
-		mntmUndo.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent evt) {
-				menuUndoActionPerformed();
-			}
-
-			private void menuUndoActionPerformed() {
-				try {
-					controller.loadAutoSave(controller.getUndoSave());
-					
-					closeInvalidUpperNodeTabs();
-					
-					controller.calculateStateAndVisualForCurrentTimeStep();
-					canvas.repaint();
-					hideScrollGraph();
-				} catch (IOException e) {
-					e.printStackTrace();
-				}
-			}
-		});
-
-		mntmRedo.addActionListener(new ActionListener() {
-			@Override
-			public void actionPerformed(ActionEvent evt) {
-				menuRedoActionPerformed();
-			}
-
-			private void menuRedoActionPerformed() {
-				try {
-					controller.loadAutoSave(controller.getRedoSave());
-					
-					closeInvalidUpperNodeTabs();
-					
-					controller.calculateStateAndVisualForCurrentTimeStep();
-					canvas.repaint();
-					hideScrollGraph();
-				} catch (IOException e) {
-					e.printStackTrace();
-				}
-			}
-		});
-
-		timePanel = new TimePanel(controller);
-		timePanel.setBorder(null);
-		timePanel.getTimeSlider()
-				.addChangeListener(changeEvent -> {
-					//TimeSliderChanged event
-					controller.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
-					unitGraph.repaint();
-					contentPane.updateUI();
-				});
-		splitPane1.setMinimumSize(new Dimension(0, 25));
-		splitPane.setRightComponent(splitPane1);
-		splitPane.setDividerLocation(200);
-		splitPane1.setDividerLocation(500);
-
-		splitPane.setLeftComponent(scrollPane1);
-		tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
-		
-		
-		myPanel.add(canvasSP, BorderLayout.CENTER);
-		
-		
-		tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
-		splitPane1.setLeftComponent(tabbedPaneOriginal);
-		splitPane1.setRightComponent(splitHolonElPro);
-
-		splitPane1.setResizeWeight(0.9);
-
-		splitHolonElPro.setDividerLocation(700);
-		// containing the graph and the elements-list
-		splitHolonElPro.setTopComponent(splitGraphHolonEl);
-		// containing the object's properties
-		splitHolonElPro.setBottomComponent(scrollProperties);
-
-		splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
-		splitGraphHolonEl.setTopComponent(scrollElements);
-		splitGraphHolonEl.setBottomComponent(scrollGraph);
-		canvasSP.setViewportView(canvas);
-
-		tabbedPaneOriginal.setBorder(null);
-		scrollProperties.setBorder(null);
-		scrollGraph.setBorder(null);
-		scrollElements.setBorder(null);
-		splitPane.setBorder(null);
-		splitPane1.setBorder(null);
-		splitHolonElPro.setBorder(null);
-		splitGraphHolonEl.setBorder(null);
-		panelHolonEl.setBorder(null);
-		canvasSP.setBorder(null);
-		hideScrollGraph();
-		tableHolonElementScrollPane.setBorder(null);
-
-		holegJFrame.getContentPane().add(timePanel, BorderLayout.SOUTH);
-
-
-
-		try {
-			controller.loadAutoSave(System.getProperty("user.home")
-					+ "/.config/HolonGUI/Category/Category.json");
-		} catch (IOException e1) {
-		}
-
-		String autoPath = System.getProperty("user.home")
-				+ "/.config/HolonGUI/Autosave/";
-		File dest = new File(autoPath);
-		ArrayList<File> oldAutoSaves = controller.filterOldAutoSaveFiles();
-		int nrOfOldSaves = oldAutoSaves.size();
-
-		if (nrOfOldSaves > 0) {
-			int dialogButton = JOptionPane.YES_NO_OPTION;
-			int dialogResult = JOptionPane.showConfirmDialog(holegJFrame,
-					"Old autosave file was found, should it be loaded?",
-					warningText, dialogButton);
-			if (dialogResult == JOptionPane.YES_OPTION) {
-				if (dest.exists()) {
-					model.setAutoSaveNr(nrOfOldSaves - 1);
-					mntmRedo.doClick();
-				} else {
-					JOptionPane.showMessageDialog(holegJFrame,
-							"Autosave could not be loaded.");
-					setUpAutoSave(dest);
-				}
-			} else {
-				setUpAutoSave(dest);
-			}
-
-			// after all: delete the obsolete/old autosave files from the
-			// directory
-			controller.deleteObsoleteAutoSaveFiles();
-		}
-
-		canvasSP.addComponentListener(new ComponentAdapter() {
-			@Override
-			public void componentResized(ComponentEvent e) {
-				controller.setCanvasX(Math.max(model.getCanvasX(), canvasSP
-						.getViewport().getWidth()));
-				controller.setCanvasY(Math.max(model.getCanvasY(), canvasSP
-						.getViewport().getHeight()));
-				canvas.repaint();
-			}
-		});
-	}
-
-	private void initWindowMenu() {
-		menuBar.add(menuWindow);
-		//Algo
-		JMenuItem openMenu =  new JMenuItem("Open Algorithm Panel", new ImageIcon(ImageImport.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
-		openMenu.addActionListener(actionEvent -> {
-			new AddOnWindow(holegJFrame, controller);
-		});
-		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()));
-		menuWindow.add(openMenu);
-		//Outliner
-		JMenuItem openOutliner =  new JMenuItem("Open Outliner", new ImageIcon(ImageImport.loadImage("/Button_Images/iconOutliner.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
-		openOutliner.addActionListener(actionEvent -> {
-			outlinerList.add(new Outliner(holegJFrame, model, controller));
-		});
-		openOutliner.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()));
-		menuWindow.add(openOutliner);
-		//FlexWindow
-		JMenuItem openFlexMenuItem =  new JMenuItem("Open Flexibility Panel", new ImageIcon(ImageImport.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
-		openFlexMenuItem.addActionListener(actionEvent -> {
-			flexList.add(new FlexWindow(holegJFrame, controller));
-		});
-		openFlexMenuItem.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()));
-		menuWindow.add(openFlexMenuItem);
-	}
-
-
-	public void updateOutliners(DecoratedState state)
-	{
-		//remove closed Outliner
-		ListIterator<Outliner> iter = outlinerList.listIterator();
-		while(iter.hasNext())
-		{
-			if(iter.next().isClosed) iter.remove();
-		}
-		//update open Outliner
-		for(Outliner out : outlinerList) {
-			out.repaintWithDecoratedState(state);
-		}
-	}
-	public void updateFlexWindows()
-	{
-		//remove closed Outliner
-		ListIterator<FlexWindow> iter = flexList.listIterator();
-		while(iter.hasNext())
-		{
-			if(iter.next().isClosed) iter.remove();
-		}
-		//update open Flex
-		for(FlexWindow out : flexList) {
-			out.update();
-		}
-	}
-	
-	
-	
-	private void showScrollGraph() {
-		scrollGraph.setVisible(true);
-		splitGraphHolonEl.setBottomComponent(scrollGraph);
-		splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
-	}
-
-	private void hideScrollGraph() {
-		scrollGraph.setVisible(false);
-		splitGraphHolonEl.remove(scrollGraph);
-		splitGraphHolonEl.setDividerLocation(0);
-	}
-
-	private boolean isUpperPanelInsideBounds() {
-		int x = holegJFrame.getX();
-		int y = holegJFrame.getY();
-		int width = holegJFrame.getWidth();
-
-		// get all connected screen devices
-		GraphicsDevice[] screenDevices = GraphicsEnvironment
-				.getLocalGraphicsEnvironment().getScreenDevices();
-		boolean isUpperPanelVisible = false;
-
-		// and check whether they contain the upper left or upper right point of
-		// the frame
-		for (GraphicsDevice device : screenDevices) {
-			Rectangle bounds = device.getDefaultConfiguration().getBounds();
-			if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
-				isUpperPanelVisible = true;
-				break;
-			}
-		}
-
-		return isUpperPanelVisible;
-	}
-
-	/**
-	 * Sets up autosave if no old one is loaded at the beginning
-	 *
-	 * @param dest
-	 *            path to save-folder
-	 */
-	private void setUpAutoSave(File dest) {
-		dest.mkdirs();
-		try {
-			controller.autoSave();
-		} catch (IOException e1) {
-			e1.printStackTrace();
-		}
-	}
-
-	/**
-	 * reloads the Categories from Model.
-	 *
-	 * @param categories
-	 *            the current categories
-	 */
-	private void updateCategories(final ArrayList<Category> categories) {
-		DefaultTreeModel treemodel = new DefaultTreeModel(new DefaultMutableTreeNode(
-				"Categories") {
-
-			private static final long serialVersionUID = 1L;
-
-			{
-				DefaultMutableTreeNode node1;
-				for (Category c : categories) {
-					node1 = new DefaultMutableTreeNode(c.getName());
-					
-					for (AbstractCanvasObject obj : c.getObjects()) {
-						node1.add(new DefaultMutableTreeNode(obj.getObjName()));
-					}
-					add(node1);
-				}
-
-			}
-		});
-		categoryTree.setModel(treemodel);
-	}
-
-	/**
-	 * When changes are made to the Categories.
-	 *
-	 * @param categories
-	 *            the Categories
-	 */
-	public void updateCategoryUI(ArrayList<Category> categories) {
-		DefaultTreeModel model = (DefaultTreeModel) categoryTree.getModel();
-		updateCategories(categories);
-		model.reload();
-	}
-
-	/**
-	 * Get the Frame.
-	 *
-	 * @return the Frame
-	 */
-	JFrame getFrmCyberPhysical() {
-		return holegJFrame;
-	}
-
-
-	/**
-	 * 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;
-				}
-			}, 350);
-		}
-		return false;
-	}
-
-	/*
-	 * Open a new Tab with an UpperNodeCanvas
-	 */
-	private void openNewUpperNodeTab() {
-		chooseTabTemp();
-
-		JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-		if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
-			unc = new GroupNodeCanvas(model, controller, unitGraph,
-					(GroupNode) temp, "", scrollPane.getViewport().getComponent(0));
-
-		} else {
-			unc = new GroupNodeCanvas(model, controller, unitGraph,
-					(GroupNode) temp, ((GroupNodeCanvas) scrollPane
-							.getViewport().getComponent(0)).path + " -> ", scrollPane.getViewport().getComponent(0));
-		}
-		unc.setShowedInformation(canvas.getShowedInformation());
-
-		// check if tab already open for clicked NodeOfNode
-		boolean dupl = false;
-
-		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
-			JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal
-					.getComponentAt(i);
-			if (paneOriginal != null
-					&& ((GroupNodeCanvas) paneOriginal.getViewport()
-							.getComponent(0)).upperNode.getId() == temp.getId()) {
-				dupl = true;
-				// set selected component to view
-				tabbedPaneOriginal
-						.setSelectedComponent(tabbedPaneInnerOriginal);
-				// set selected tab in view to found upper-node-canvas
-				tabbedPaneInnerOriginal
-						.setSelectedComponent(tabbedPaneInnerOriginal
-								.getComponentAt(i));
-			}
-
-			if (tabbedPaneSplit.getTabCount() > 0) {
-				JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
-						.getComponentAt(0);
-				if (tabbedPaneInnerSplit != null) {
-					JScrollPane paneSplit = (JScrollPane) tabbedPaneInnerSplit
-							.getComponentAt(i);
-					if (!initSplit
-							&& paneSplit != null
-							&& ((GroupNodeCanvas) paneSplit.getViewport()
-									.getComponent(0)).upperNode.getId() == temp
-									.getId()) {
-						dupl = true;
-						// set selected component to view
-						tabbedPaneSplit
-								.setSelectedComponent(tabbedPaneInnerSplit);
-						// set selected tab in view to found upper-node-canvas
-						tabbedPaneInnerSplit
-								.setSelectedComponent(tabbedPaneInnerSplit
-										.getComponentAt(i));
-					}
-				}
-			}
-
-			// if we found a duplicate, break
-			if (dupl) {
-				break;
-			}
-		}
-		if (!dupl) {
-			unc.setBorder(null);
-			unc.setBackground(Color.WHITE);
-			unc.setPreferredSize(new Dimension(model.getCanvasX(), model
-					.getCanvasY()));
-
-			unc.addMouseListener(new MouseAdapter() {
-				@Override
-				public void mousePressed(MouseEvent e) {
-					hideScrollGraph();
-					holonEleNamesDisplayed = "None";
-					elementGraph.setText(holonEleNamesDisplayed);
-
-					chooseTabTemp();
-
-					JScrollPane scrollPane1 = getScrollPaneFromTabbedPane();
-					temp = ((GroupNodeCanvas) scrollPane1.getViewport()
-							.getComponent(0)).tempCps;
-					if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
-							&& temp instanceof GroupNode) {
-						openNewUpperNodeTab();
-					}
-					if (temp instanceof HolonSwitch) {
-						updateUnitGraph((GraphEditable)temp);
-					}
-				}
-
-			});
-
-			JScrollPane sp = new JScrollPane(unc);
-			sp.setBorder(null);
-
-			// Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
-			if (tabTemp == tabbedPaneOriginal) {
-				this.tabbedPaneInnerOriginal.add(temp.getName(), sp);
-				this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
-				this.tabbedPaneInnerOriginal.setTabComponentAt(
-						this.tabbedPaneInnerOriginal.getTabCount() - 1,
-						new ButtonTabComponent(this.tabbedPaneInnerOriginal,
-								tabbedPaneSplit));
-
-			} else {
-				JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
-						.getComponentAt(0);
-				tabbedPaneInnerSplit.add(temp.getName(), sp);
-				Component tempC = tabbedPaneInnerSplit.getSelectedComponent();
-				tabbedPaneInnerSplit.setComponentAt(
-						tabbedPaneInnerSplit.getSelectedIndex(), null);
-				tabbedPaneOriginal.setComponentAt(
-						tabbedPaneInnerSplit.getSelectedIndex(), tempC);
-				tabbedPaneInnerSplit.setSelectedComponent(sp);
-
-				tabbedPaneInnerOriginal.add(temp.getName(), null);
-				tabbedPaneInnerOriginal.setTabComponentAt(
-						tabbedPaneInnerOriginal.getTabCount() - 1,
-						new ButtonTabComponent(tabbedPaneInnerOriginal,
-								tabbedPaneInnerSplit));
-			}
-
-			temp = null;
-		}
-	}
-
-	private void updateUpperNodes() {
-		for (Component c : tabbedPaneInnerOriginal.getComponents()) {
-			if (!(c instanceof JScrollPane)) {
-				continue;
-			}
-			Component pane = ((JScrollPane) c).getViewport().getComponent(0);
-			if (pane instanceof GroupNodeCanvas) {
-				temp = model.getHashcodeMap()
-						.get(((GroupNodeCanvas) pane).code);
-				((GroupNodeCanvas) pane).upperNode = (GroupNode) temp;
-			}
-		}
-	}
-
-	/**
-	 * Removes UpperNodeTab if UpperNode was deleted
-	 *
-	 * @param cps
-	 *            the CPS object that is currently selected
-	 */
-	private void removeUpperNodeTab(AbstractCanvasObject cps) {
-		if (cps instanceof GroupNode) {
-			boolean splitView = false;
-			for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
-				JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
-						.getComponentAt(i);
-
-				if (scrollPaneOriginal == null) {
-					splitView = true;
-				} else if (((GroupNodeCanvas) scrollPaneOriginal.getViewport()
-						.getComponent(0)).upperNode.getId() == cps.getId()) {
-					((ButtonTabComponent) tabbedPaneInnerOriginal
-							.getTabComponentAt(i)).removeTabs();
-					break;
-				}
-			}
-			// If SplitView is on and the view on
-			// tabbedPaneSplit is the deleted upperNode
-			if (splitView && tabbedPaneSplit.getComponentCount() > 0) {
-				JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
-						.getComponentAt(0);
-
-				if (((GroupNodeCanvas) ((JScrollPane) tabbedPaneInnerSplit
-						.getSelectedComponent()).getViewport().getComponent(0)).upperNode
-						.getId() == cps.getId()) {
-					((ButtonTabComponent) tabbedPaneInnerOriginal
-							.getTabComponentAt(tabbedPaneInnerSplit
-									.getSelectedIndex())).removeTabs();
-				}
-			}
-		}
-	}
-
-
-	/**
-	 * chooses whether to set the tabTemp to tabbedPaneOriginal or
-	 * tabbedPaneSplit
-	 */
-	private void chooseTabTemp() {
-		// is the uppernode on tabbedPaneOriginal or tabbedPaneSplit
-		/* TODO: Fix or Remove SplitView */
-		if (tabbedPaneOriginal.getMousePosition() != null || initSplit) {
-			tabTemp = tabbedPaneOriginal;
-		} else {
-			tabTemp = tabbedPaneSplit;
-		}
-	}
-
-	private JScrollPane getScrollPaneFromTabbedPane() {
-		return getScrollPaneFromTabbedPane(-1);
-	}
-
-	private JScrollPane getScrollPaneFromTabbedPane(int index) {
-		Component upperLevelSelectedComponent;
-		if(tabTemp == null)
-		{
-			return null;
-		}
-		if (index == -1) {
-			upperLevelSelectedComponent = tabTemp.getSelectedComponent();
-		} else {
-			upperLevelSelectedComponent = tabTemp.getComponentAt(index);
-		}
-		if (upperLevelSelectedComponent instanceof JTabbedPane) {
-			Component nextLevel = ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
-			if(nextLevel instanceof JPanel)
-				return (JScrollPane) ((JPanel)nextLevel).getComponent(0);
-			else
-				return (JScrollPane) nextLevel;
-			
-		} else if (upperLevelSelectedComponent instanceof JScrollPane) {
-			return (JScrollPane) upperLevelSelectedComponent;
-		} else {
-			return null;
-		}
-	}
-
-
-	/**
-	 * 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(false,
-//				selectedValueBY, 6);
-		model.getSingleTable().setValueAt(eleBTemp.isActive(), selectedValueBY,
-				5);
-		model.getSingleTable().setValueAt(eleBTemp.getAmount(),
-				selectedValueBY, 4);
-		model.getSingleTable().setValueAt(
-				controller.getSimManager().getActualFlexManager().isAFlexInUseOfHolonElement(eleBTemp),
-				selectedValueBY, 3);
-		model.getSingleTable().setValueAt(eleBTemp.getEnergyPerElement(),
-				selectedValueBY, 2);
-	}
-
-	public void triggerUpdateController(AbstractCanvasObject temp) {
-		if(model != null) { return;}
-		if (temp != null) {
-			updCon.paintProperties(temp);
-		}
-		updCon.refreshTableHolonElement(model.getMultiTable(),
-				model.getSingleTable());
-		updCon.refreshTableProperties(model.getPropertyTable());
-	}
-
-	/**
-	 * This Method updates the UnitGraph, saves the old LocalModeState and load the new LocalModeState.
-	 * @param element The new Element to load the UnitGraph
-	 */
-	private void updateUnitGraph(GraphEditable element){
-		//SaveOld LocalMode State.
-		if(localPeriodInput.isVisible())
-		{
-			//Save Old State
-			validateInput(localPeriodInput.getEditor().getItem().toString(), false);
-		}
-		//Update UnitGraph
-		unitGraph.initNewElement(element);
-		//Load LocalMode State.
-		changeLocalPeriodButtonAppeareance(unitGraph.isUsingLocalPeriod());
-		localPeriodInput.getEditor().setItem(unitGraph.getLocalPeriod());
-	}
-	
-	/**
-	 * Displayed the actual LocalModeState.
-	 * @param enabled
-	 */
-	private void changeLocalPeriodButtonAppeareance(boolean enabled) {
-		localPeriodInput.setVisible(enabled);
-		if(enabled)
-		{
-			localPeriodButtonImage.setImage(ImageImport.loadImage("/Images/Graph.png"));
-		}else {
-			localPeriodButtonImage.setImage(GrayFilter.createDisabledImage(ImageImport.loadImage("/Images/Graph.png")));
-		}
-	}
-	/**
-	 * Validate the LocalMode Input and when its valid save on the Element.
-	 * @param text the inputText to validate. 
-	 * @param bShowMessage when true, open a MessageDialog when text invalid.
-	 */
-	private void validateInput(String text, boolean bShowMessage) {
-		int localPeriodInputValue;
-		try {
-		      localPeriodInputValue = Integer.parseInt(text);
-		} catch (NumberFormatException e) {
-			if(bShowMessage)
-				JOptionPane.showMessageDialog(contentPane, '"' +text + '"'+ " is not a valid Input. \n Use whole numbers.");
-			return;
-		}
-		unitGraph.setLocalPeriod(localPeriodInputValue);
-	}
-
-	
-	private void openWebpage(String URL){
-		try {
-			java.awt.Desktop.getDesktop().browse(new URI(URL));
-		} catch (IOException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		} catch (URISyntaxException e1) {
-			// TODO Auto-generated catch block
-			e1.printStackTrace();
-		}
-	}
-	
-	/**
-	 * closes all UpperNodeTabs, that don't have a
-	 * valid UpperNode (e.g. if it was ungrouped/deleted/replaced and so on)
-	 */
-	private void closeInvalidUpperNodeTabs() {
-		/**
-		 * close bugged Tabs
-		 */
-		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
-			JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
-					.getComponentAt(i);
-			if (((GroupNodeCanvas) scrollPaneOriginal.getViewport()
-					.getComponent(0)).upperNode == null) {
-				((ButtonTabComponent) tabbedPaneInnerOriginal
-						.getTabComponentAt(i)).removeTabs();
-				break;
-			}
-		}
-	}
-	
-	public void repaintCanvas() {
-		tabbedPaneInnerOriginal.repaint();
-	}
-	
-	/**
-	 * Class should be reworked as soon as possible!
-	 * @param state
-	 */
-	public void guiDisable(boolean state) {
-		canvas.disabled = state;
-		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
-			JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
-					.getComponentAt(i);
-			if (((GroupNodeCanvas) scrollPaneOriginal.getViewport()
-					.getComponent(0)).upperNode != null) {
-				((GroupNodeCanvas) scrollPaneOriginal.getViewport()
-						.getComponent(0)).disable = state;
-			}
-		}
-	}
-}

+ 0 - 1272
src/ui/view/GroupNodeCanvas.java

@@ -1,1272 +0,0 @@
-package ui.view;
-
-import java.awt.BasicStroke;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.Font;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
-import java.awt.datatransfer.UnsupportedFlavorException;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
-import java.awt.geom.Line2D;
-import java.awt.image.BufferedImage;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-
-import javax.swing.ImageIcon;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTabbedPane;
-import javax.swing.SwingUtilities;
-
-import com.google.gson.JsonParseException;
-
-import classes.AbstractCanvasObject;
-import classes.Edge;
-import classes.GroupNode;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.Node;
-import ui.controller.Control;
-import ui.controller.UpdateController;
-import ui.model.Consumer;
-import ui.model.DecoratedCable;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedHolonObject;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.DecoratedSwitch;
-import ui.model.ExitCable;
-import ui.model.DecoratedSwitch.SwitchState;
-import ui.model.Model;
-import ui.model.Passiv;
-import ui.model.Supplier;
-import utility.ImageImport;
-import utility.Vector2Float;
-import utility.Vector2Int;
-
-/**
- * This Class is the Canvas. All Objects will be visualized here
- *
- * @author Gruppe14
- */
-public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, MouseMotionListener {
-
-    private static final long serialVersionUID = 1L;
-    // The UpperNode
-    public GroupNode upperNode;
-    // Path
-    protected String path;
-    int code;
-    public boolean disable = false;
-    /**
-     * Constructor.
-     *
-     * @param mod       the Model
-     * @param control   the Controller
-     * @param unitGraph
-     */
-    GroupNodeCanvas(Model mod, Control control, UnitGraph unitGraph, GroupNode UpperNode, String parentPath, Component parentComponent) {
-        toolTip = false;
-
-        this.controller = control;
-        this.model = mod;
-        this.upperNode = UpperNode;
-        this.code = UpperNode.hashCode();
-        this.path = parentPath + upperNode.getName();
-        scalediv20 = model.getScale() / 20;
-
-        // Cps objecte aus dem border links schieben
-        upperNode.setLeftBorder(/*(int) (50 + scalediv20 + scalediv20 + 10)*/ 0);
-        for (AbstractCanvasObject cps : upperNode.getNodes()) {
-            if (cps.getPosition().getX() < model.getScaleDiv2() + upperNode.getLeftBorder() + 5) {
-                cps.setPosition(
-                        new Vector2Int(upperNode.getLeftBorder() + 5 + model.getScaleDiv2(), cps.getPosition().getY()));
-            }
-        }
-
-        showedInformation[0] = true;
-        showedInformation[1] = true;
-        showedInformation[4] = true;
-
-        popmenu.add(itemCut);
-        popmenu.add(itemCopy);
-        popmenu.add(itemPaste);
-        popmenu.add(itemDelete);
-        popmenu.add(itemAlign);
-        popmenu.addSeparator();
-        popmenu.add(itemGroup);
-        popmenu.add(itemUngroup);
-        popmenu.add(itemCreateTemplate);
-        
-        itemAlign.setEnabled(true);
-        itemDelete.setEnabled(false);
-        itemCut.setEnabled(false);
-        itemCopy.setEnabled(false);
-        itemPaste.setEnabled(true);
-        itemGroup.setEnabled(false);
-        itemUngroup.setEnabled(false);
-        
-        updCon = new UpdateController(model, controller);
-        
-        itemAlign.addActionListener(actionEvent -> {
-        	for(AbstractCanvasObject cps: model.getSelectedCpsObjects())
-        		align(cps, model.getScaleDiv2());
-        	repaint();
-        });
-        
-        itemGroup.addActionListener(actionEvent -> {
-            // calculate uppernode pos (taken from the controller)
-            unPos = new Vector2Int(0, 0);
-            animCps = new ArrayList<>();
-            for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-                animCps.add(cps); // add to animation Cps ArrayList
-                unPos = unPos.add(cps.getPosition());
-            }
-            unPos = unPos.divide(animCps.size());
-
-            // save old Position
-            savePos = new ArrayList<>();
-            for (int i = 0; i < animCps.size(); i++) {
-                savePos.add(animCps.get(i).getPosition().clone());
-            }
-
-            animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
-                if (animDuration - animDelay > 0 && animCps.size() > 1) {
-                    for (AbstractCanvasObject currentAnimCps : animCps) {
-                    	Vector2Int pos = currentAnimCps.getPosition();
-                    	Vector2Int difference = pos.subtract(unPos);
-                    	Vector2Int result = pos.subtract(difference.divide(animSteps));
-                    	pos.set(result);
-                    }
-                    repaint();
-                    animDuration -= animDelay;
-                    animSteps--;
-                } else {
-                    animDuration = ANIMTIME;
-                    animSteps = animDuration / animDelay;
-                    animT.stop();
-                    for (int i = 0; i < animCps.size(); i++) {
-                        animCps.get(i).getPosition().set(savePos.get(i));
-                    }
-                    controller.addUpperNode("GroupNode", upperNode, model.getSelectedCpsObjects());
-                    controller.calculateStateAndVisualForCurrentTimeStep();
-                    repaint();
-                }
-            });
-            animT.start();
-        });
-
-        itemUngroup.addActionListener(actionEvent -> {
-            // save old Position
-        	closeUpperNodeTab(tempCps.getId());
-
-            savePos = new ArrayList<>();
-            animCps = ((GroupNode) tempCps).getNodes();
-            controller.ungroupGroupNode((GroupNode) tempCps, upperNode);
-
-            for (int i = 0; i < animCps.size(); i++) {
-                savePos.add(animCps.get(i).getPosition().clone());
-            }
-            for (AbstractCanvasObject cps : animCps) {
-                cps.setPosition(tempCps.getPosition().clone());
-            }
-
-            animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
-                if (animDuration - animDelay >= 0) {
-                    for (int i = 0; i < animCps.size(); i++) {
-                        Vector2Int pos = animCps.get(i).getPosition();
-                    	Vector2Int difference = pos.subtract(savePos.get(i));
-                    	Vector2Int result = pos.subtract(difference.divide(animSteps));
-                    	pos.set(result);
-                    }
-                    repaint();
-                    animDuration -= animDelay;
-                    animSteps--;
-                } else {
-                    animDuration = ANIMTIME;
-                    animSteps = animDuration / animDelay;
-                    animT.stop();
-                    for (int i = 0; i < animCps.size(); i++) {
-                        animCps.get(i).getPosition().set(savePos.get(i));
-                    }
-
-                    controller.calculateStateAndVisualForCurrentTimeStep();
-                    repaint();
-                }
-            });
-            animT.start();
-        });
-
-        
-
-        itemDelete.addActionListener(actionEvent -> {
-            // Remove the selected Object objects
-            for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-                if (upperNode.getNodes().contains(cps)) {
-                    controller.delObjUpperNode(cps, upperNode);
-                    // Remove UpperNodeTab if UpperNode deleted
-                    if (cps instanceof GroupNode) {
-                        JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent().getParent().getParent();
-                        // Look if the uppernode is open in a Tab
-                        for (int i = 4; i < tabbedPane.getTabCount(); i++) {
-
-                            if (tabbedPane.getComponentAt(i) != null &&
-                                    ((GroupNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
-                                            .getComponent(0)).upperNode.getId() == cps.getId()) {
-                                ((ButtonTabComponent) tabbedPane.getTabComponentAt(i)).removeTabs();
-                                break;
-                            }
-                        }
-                      
-                    }
-                }
-            }
-            toolTip = false;
-            model.getSelectedCpsObjects().clear();
-            tempCps = null;
-            repaint();
-        });
-
-        itemCut.addActionListener(actionEvent -> {
-            controller.cut(upperNode);
-            itemPaste.setEnabled(true);
-            repaint();
-        });
-
-        itemCopy.addActionListener(actionEvent -> {
-        	if(tempCps instanceof GroupNode)
-				controller.getObjectsInDepth();
-            controller.copy(upperNode);
-            itemPaste.setEnabled(true);
-            repaint();
-        });
-
-        itemPaste.addActionListener(actionEvent -> {
-            try {
-                controller.paste(upperNode, mousePosition);
-            } 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();
-        });
-        
-        /*
-		 * create Template
-		 */
-		itemCreateTemplate.addActionListener(actionEvent -> {
-			controller.createTemplate((HolonObject)tempCps, (JFrame)SwingUtilities.getRoot(this));
-		});
-
-        this.addMouseListener(this);
-        this.addMouseMotionListener(this);
-    }
-
-	/**
-	 * Paints all Components on the Canvas.
-	 *
-	 * @param g
-	 *            Graphics
-	 */
-	
-	private Color getStateColor(HolonObjectState state) {
-		switch(state) {
-		case NOT_SUPPLIED:
-			return new Color(230, 120, 100);
-		case NO_ENERGY:
-			return Color.white;
-		case OVER_SUPPLIED:
-			return new Color(166, 78, 229);
-		case PARTIALLY_SUPPLIED:
-			return Color.yellow;
-		case PRODUCER:
-			return Color.lightGray;
-		case SUPPLIED:
-			return new Color(13, 175, 28);
-		default:
-			return Color.BLACK;
-		}
-	}
-	private void paintCanvasObject(Graphics2D g, DecoratedHolonObject decoratedHolonObject){
-		Vector2Int pos = decoratedHolonObject.getModel().getPosition();
-		Color statecolor = getStateColor(decoratedHolonObject.getState());
-		g.setColor(statecolor);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
-		drawCanvasObject(g, decoratedHolonObject.getModel().getImage(), pos);
-	}
-	private void drawCanvasObjectString(Graphics2D g, Vector2Int posOfCanvasObject, float energy) {
-		g.setColor(Color.BLACK);
-		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (controller.getScale() / 4f) )); 
-		g.drawString((energy > 0)? "+" + Float.toString(energy): Float.toString(energy), posOfCanvasObject.getX() - controller.getScaleDiv2(), posOfCanvasObject.getY() - controller.getScaleDiv2() - 1);
-	}
-	private void paintConsumer(Graphics2D g, Consumer con){
-		paintCanvasObject(g, con);
-		paintSupplyBar(g,con.getSupplyBarPercentage(), getStateColor(con.getState()), con.getModel().getPosition());
-		drawCanvasObjectString(g, con.getModel().getPosition(), -con.getEnergyNeededFromNetwork());
-	}
-	private void paintSupplier(Graphics2D g, Supplier sup){
-		paintCanvasObject(g, sup);
-		drawCanvasObjectString(g, sup.getModel().getPosition(), sup.getEnergyToSupplyNetwork());
-	}
-	
-	private void drawCanvasObject(Graphics2D g, String Image, Vector2Int pos) {
-		g.drawImage(ImageImport.loadImage(Image, controller.getScale(), controller.getScale()) , 
-				pos.getX() - controller.getScaleDiv2(),
-				pos.getY() - controller.getScaleDiv2(),
-				controller.getScale(), controller.getScale() , null);
-	}
-	
-	private void paintCable(Graphics2D g, DecoratedCable cable, boolean isSelected)
-	{
-		Vector2Int start = cable.getModel().getA().getPosition();
-		Vector2Int end =  cable.getModel().getB().getPosition();
-		float currentEnergy = cable.getFlowEnergy();
-		float capacity = cable.getModel().getCapacity();
-		boolean unlimited = cable.getModel().isUnlimitedCapacity();
-		switch(cable.getState()) {
-		case Burned:
-			g.setColor(Color.RED);
-			g.setStroke(new BasicStroke(2));
-			break;
-		case Working:
-			g.setColor(new Color(13, 175, 28));
-			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
-			break;
-		}
-		if(isSelected){
-			g.setColor(Color.lightGray);
-		}
-		g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
-		Vector2Int middle = new Vector2Int((start.getX() + end.getX()) / 2, (start.getY() + end.getY()) / 2);
-		g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
-		g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.getX(), middle.getY());
-	}
-	private void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch)
-	{
-		drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage(): HolonSwitch.getSwitchClosedImage() , dSwitch.getModel().getPosition());
-	}
-	private void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
-		Vector2Int pos = dGroupNode.getModel().getPosition();
-		g.setColor(Color.lightGray);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
-		drawCanvasObject(g, "/Images/upper_node.png" , pos);
-		paintGroupNodeBar(g, dGroupNode, pos);
-	}
-	private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode , Vector2Int pos) {
-		// +1, -2, -1 little Adjustment for pixel perfect alignment
-		int barWidth = (int) (controller.getScale());
-		int barHeight = (int) (controller.getScale() / 5);
-		g.setColor(Color.WHITE);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
-		float[] percentages = getGroupNodeBarPercentages(dGroupNode);
-		Color[] colors = new Color[6];
-		colors[0] = getStateColor(HolonObjectState.PRODUCER);
-		colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
-		colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
-		colors[3] = getStateColor(HolonObjectState.SUPPLIED);
-		colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
-		colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
-				
-		for(int i = 5; i>=0; i--) {
-			g.setColor(colors[i]);
-			g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * percentages[i] - 1), barHeight);		
-		}
-//		g.setColor(color);
-//		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
-		g.setColor(Color.BLACK);
-		g.setStroke(new BasicStroke(1));
-		g.drawRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
-	}
-	/**
-	 * HardCoded Stuff dont try at Home ;)
-	 * @param dGroupNode
-	 * @return
-	 */
-	public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
-		int[] amountOfObjects = new int[6];
-		amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
-		amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-		amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-		amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-		amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-		amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
-		int countHolonObjects = amountOfObjects[0] + 	amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3] + amountOfObjects[4] + amountOfObjects[5];
-		float[] percentages = new float[6];
-		int count = 0;
-		for(int i = 0; i < 6; i++) {
-			count += amountOfObjects[i];
-			percentages[i] = (float)count / (float)countHolonObjects;
-		}
-		return percentages;
-	}
-	private void paintExitCable(Graphics2D g, ExitCable eCable) {
-		if(eCable.getStart() == null || eCable.getFinish() == null) {
-			System.out.println("Null wrong exitcable");
-			System.out.println(" wrongCable: " + " start:"  +eCable.getStart() + " end:"  +eCable.getFinish() + " state:" + eCable.getState());
-			return;
-		}
-		Vector2Int start = eCable.getStart().getPosition();
-		Vector2Int end = eCable.getFinish().getPosition();
-		float currentEnergy = eCable.getCable().getFlowEnergy();
-		float capacity = eCable.getCable().getModel().getCapacity();
-		boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
-		switch(eCable.getCable().getState()) {
-		case Burned:
-			g.setColor(Color.RED);
-			g.setStroke(new BasicStroke(2));
-			break;
-		case Working:
-			g.setColor(new Color(13, 175, 28));
-			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
-			break;
-		}
-		switch(eCable.getState()) {
-		case DOWN:
-		case DOWNDOWN:
-			g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
-			Vector2Int middle = new Vector2Int((start.getX() + end.getX()) / 2, (start.getY() + end.getY()) / 2);
-			g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
-			g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.getX(), middle.getY());
-			break;
-		case DOWNUP:
-		case UP:
-			Vector2Float vStart = new Vector2Float(start.getX(), start.getY());
-			Vector2Float vEnd = new Vector2Float(end.getX(), end.getY());
-			float stretchFactor = 4 * model.getScale();
-			stretchFactor =  (stretchFactor > vStart.getDistance(vEnd))? vStart.getDistance(vEnd) : stretchFactor;
-			Vector2Float vPosition = vStart.add((vEnd.subtract(vStart)).normalize().multiply(stretchFactor));
-			Vector2Int result = new Vector2Int(Math.round(vPosition.getX()),Math.round(vPosition.getY()));
-			g.drawLine(start.getX(), start.getY(), result.getX(), result.getY());
-			Vector2Int middle1 = new Vector2Int((start.getX() +result.getX()) / 2, (start.getY() + +result.getY()) / 2);
-			g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
-			g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle1.getX(), middle1.getY());
-			drawCanvasObject(g, "/Images/arrowUp.png" , result);
-			break;
-		default:
-			System.out.println("Error");
-			break;
-		}
-	}
-	private void paintSupplyBar(Graphics2D g, float percentage, Color color, Vector2Int pos) {
-		// +1, -2, -1 little Adjustment for pixel perfect alignment
-		int barWidth = (int) (controller.getScale());
-		int barHeight = (int) (controller.getScale() / 5);
-		g.setColor(Color.WHITE);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
-		g.setColor(color);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
-		g.setColor(Color.BLACK);
-		g.setStroke(new BasicStroke(1));
-		g.drawRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
-		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2)); 
-		String percentageString = (Math.round((percentage * 100))) + "%";
-		int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
-		if(percentage > 1.0f) g.setColor(Color.WHITE); //Just to see better on purple
-		g.drawString(percentageString, pos.getX() + 1 - stringWidth / 2, pos.getY() + controller.getScaleDiv2() - 1+ barHeight);
-		
-	}
-	
-	//old code
-	void drawMarker(Graphics2D g) {
-		Color transparentGrey = new Color(128, 174, 247, 40);
-		if (sx > x && sy > y) {
-			g.drawRect(x, y, sx - x, sy - y);
-			g.setColor(transparentGrey);
-			g.fillRect(x, y, sx - x, sy - y);
-		} else if (sx < x && sy < y) {
-			g.drawRect(sx, sy, x - sx, y - sy);
-			g.setColor(transparentGrey);
-			g.fillRect(sx, sy, x - sx, y - sy);
-		} else if (sx >= x) {
-			g.drawRect(x, sy, sx - x, y - sy);
-			g.setColor(transparentGrey);
-			g.fillRect(x, sy, sx - x, y - sy);
-		} else if (sy >= y) {
-			g.drawRect(sx, y, x - sx, sy - y);
-			g.setColor(transparentGrey);
-			g.fillRect(sx, y, x - sx, sy - y);
-		}
-	}
-	public void paintComponent(Graphics g) {		
-		super.paintComponent(g);
-		Graphics2D g2d = (Graphics2D) g;
-		g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
-				RenderingHints.VALUE_ANTIALIAS_ON));
-		//-->Old code
-		if (drawEdge) {
-			g2d.setColor(Color.BLACK);
-			g2d.setStroke(new BasicStroke(1));
-			g2d.drawLine(tempCps.getPosition().getX(), tempCps.getPosition().getY(), x, y);
-		}
-		//<--
-		//SelectedCable
-		HashSet<Edge> selectedEdges = new HashSet<Edge>();
-		for(AbstractCanvasObject aCps:  model.getSelectedCpsObjects()) {
-			for(Edge edge: aCps.getConnections()) {
-				selectedEdges.add(edge);
-			}
-		}
-		if(model.getSelectedEdge() != null) selectedEdges.add(model.getSelectedEdge());
-
-		
-		DecoratedGroupNode  actualGroupNode = controller.getSimManager().getActualVisualRepresentationalState().getCreatedGroupNodes().get(upperNode);
-		//VisualState Representation:
-		for(ExitCable cable : actualGroupNode.getExitCableList()) {
-			paintExitCable(g2d, cable);
-		}
-		for(DecoratedCable cable : actualGroupNode.getInternCableList()) {
-			paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
-		}
-	
-		
-		for(DecoratedGroupNode dGroupNode : actualGroupNode.getGroupNodeList()) {
-			paintGroupNode(g2d, dGroupNode);
-		}
-		for(Consumer con: actualGroupNode.getConsumerList()) {
-			paintConsumer(g2d, con);					
-		}
-		for(Supplier sup: actualGroupNode.getSupplierList()) {
-			paintSupplier(g2d, sup);				
-		}
-		for(Passiv pas: actualGroupNode.getPassivList()) {
-			paintCanvasObject(g2d, pas);
-		}
-		for(DecoratedSwitch dSwitch : actualGroupNode.getSwitchList()) {
-				paintSwitch(g2d, dSwitch);
-		}
-		for(Node node : actualGroupNode.getNodeList()) {
-			drawCanvasObject(g2d, "/Images/node.png" , node.getPosition());
-		}
-		
-		//-->oldCode 
-		if (doMark) {
-			g2d.setColor(Color.BLACK);
-			g2d.setStroke(new BasicStroke(0));
-			drawMarker(g2d);
-		}
-		//Test Selection
-		//Objects:
-		g2d.setColor(Color.BLUE);
-		g2d.setStroke(new BasicStroke(1));
-		Color transparentGrey = new Color(128, 174, 247, 40);
-		for(AbstractCanvasObject aCps:  model.getSelectedCpsObjects()) {
-			if(aCps instanceof Node) {
-				Vector2Int pos = aCps.getPosition();
-				g2d.setColor(transparentGrey);
-				g2d.fillOval(pos.getX() - (int) (controller.getScaleDiv2()), pos.getY() - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
-				g2d.setColor(Color.LIGHT_GRAY);
-				g2d.setStroke(new BasicStroke(2));
-				g2d.drawOval(pos.getX() - (int) (controller.getScaleDiv2()), pos.getY() - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
-			}
-			else {
-				Vector2Int pos = aCps.getPosition();
-				g2d.setColor(transparentGrey);
-				g2d.fillRect(pos.getX() - (int) (controller.getScaleDiv2()* 1.5f), pos.getY() - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));
-				g2d.setColor(Color.LIGHT_GRAY);
-				g2d.setStroke(new BasicStroke(2));
-				g2d.drawRect(pos.getX() - (int) (controller.getScaleDiv2()* 1.5f), pos.getY() - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));				
-			}
-
-		}
-		//maybeReplace:
-		if(mayBeReplaced != null){
-			g2d.setColor(Color.RED);
-			Vector2Int pos = mayBeReplaced.getPosition();
-			g.drawImage(ImageImport.loadImage("/Images/replace.png") , 
-					pos.getX() + controller.getScaleDiv2(),
-					pos.getY() - controller.getScale(),
-					controller.getScaleDiv2(), controller.getScaleDiv2(), null);
-		}
-		//<-- OldCode
-	}
-   
-
-    @Override
-    public void mouseClicked(MouseEvent e) {
-    	if(!disable){
-        triggerUpdateController();
-        stopEditing();
-    	}
-    }
-
-    @Override
-    public void mouseEntered(MouseEvent e) {
-    }
-
-    @Override
-    public void mouseExited(MouseEvent e) {
-    }
-
-    @Override
-    public void mousePressed(MouseEvent e) {
-    	if(!disable){
-    	stopEditing();
-        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 (AbstractCanvasObject cps : upperNode.getNodes()) {
-                cx = cps.getPosition().getX() - model.getScaleDiv2();
-                cy = cps.getPosition().getY() - model.getScaleDiv2();
-                if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
-                    tempCps = cps;
-
-
-                    dragging = true;
-                    if (e.isControlDown() && tempCps != null) {
-                        if (model.getSelectedCpsObjects().contains(tempCps)) {
-                            controller.deleteSelectedObject(tempCps);
-                        } else {
-                            controller.addSelectedObject(tempCps);
-                            if(tempCps instanceof GroupNode)
-    							controller.getObjectsInDepth();
-                        }
-                    }
-
-                    // 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 (Edge ed : upperNode.getConnections()) {
-                AbstractCanvasObject 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 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) {
-    	if(!disable){
-        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 { 
-            	/**
-            	 * Save State before performing NodePlacement, replacement e.g.
-            	 */
-                controller.autoSave();
-            } catch (IOException ex) {
-                ex.printStackTrace();
-            }
-            
-            /**
-             * check if tempCps could replace an Object on the UpperNodeanvas
-             */
-            if(model.getSelectedCpsObjects().size() == 1 && checkForReplacement(upperNode.getNodes(), tempCps, tempCps.getPosition().getX(), tempCps.getPosition().getY())){
-            	/**
-            	 * if UpperNode would be replaced, close its tabs
-            	 */
-            	if(mayBeReplaced instanceof GroupNode)
-            		closeUpperNodeTab(mayBeReplaced.getId());
-            	/**
-            	 * replace on canvas
-            	 */
-            	controller.replaceObjUpperNode(mayBeReplaced, tempCps, upperNode);
-            	mayBeReplaced=null;
-            }
-        }
-
-        if (!e.isControlDown() && !dragged && tempCps != null && MouseEvent.BUTTON3 != e.getButton()) {
-            model.getSelectedCpsObjects().clear();
-            controller.addSelectedObject(tempCps);
-            if(tempCps instanceof GroupNode)
-				controller.getObjectsInDepth();
-        }
-
-        dragged = false;
-
-        // Rightclick List
-        setRightClickMenu(e);
-
-        markObjects();
-
-        if (doubleClick() && tempCps != null && tempCps instanceof HolonSwitch) {
-            ((HolonSwitch) tempCps).switchState();
-        }
-
-        controller.calculateStateAndVisualForTimeStep(model.getCurIteration());
-        triggerUpdateController();
-        repaint();
-    	}
-    }
-
-    @Override
-    public void mouseDragged(MouseEvent e) {
-    	if(!disable){
-        // 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().getX();
-                    yDist = y - tempCps.getPosition().getY();
-
-                    tempCps.setPosition(x, y); // Drag Position
-
-                    // TipText Position and name
-                    toolTip = true;
-                    toolTipText = tempCps.getName() + ", " + tempCps.getId();
-                    toolTipPos.setX(tempCps.getPosition().getX() - model.getScaleDiv2());
-                    toolTipPos.setY(tempCps.getPosition().getY() - model.getScaleDiv2());
-
-                    // All Selected Objects
-                    for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-                        if (cps != tempCps) {
-                            x = (int) (cps.getPosition().getX() + xDist);
-                            y = (int) (cps.getPosition().getY() + 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);
-                        }
-                    }
-                }
-                /**
-            	 * check if something would be replaced
-            	 */
-                if(model.getSelectedCpsObjects().size()==1)
-                	checkForReplacement(upperNode.getNodes(), tempCps, x, y);
-
-               repaint();
-            } catch (Exception eex) {
-
-            }
-        	
-        }
-
-        // Mark Objects
-        if (doMark) {
-            tempSelected.clear();
-            for (AbstractCanvasObject 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().getX() + model.getScaleDiv2() && y1 <= cps.getPosition().getY() + model.getScaleDiv2()
-                        && x2 >= cps.getPosition().getX() && y2 >= cps.getPosition().getY()) {
-                    tempSelected.add(cps);
-
-                }
-            }
-            int count = 0;
-            for (Edge ed : upperNode.getConnections()) {
-                AbstractCanvasObject 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 (AbstractCanvasObject cps : upperNode.getNodes()) {
-
-            cx = cps.getPosition().getX() - controller.getScaleDiv2();
-            cy = cps.getPosition().getY() - controller.getScaleDiv2();
-
-            on = setToolTipInfoAndPosition(on, cps);
-        }
-        int count = 0;
-        for (Edge ed : upperNode.getConnections()) {
-
-            AbstractCanvasObject 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.setX(cx - 25);
-                toolTipPos.setY(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
-        Edge e = null;
-        for (AbstractCanvasObject cps : upperNode.getNodes()) {
-
-            cx = cps.getPosition().getX() - controller.getScaleDiv2();
-            cy = cps.getPosition().getY() - controller.getScaleDiv2();
-
-            if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
-                    && cps != tempCps) {
-                found = true;
-                node = false;
-                onEdge = false;
-                for (Edge p : tempCps.getConnections()) {
-                    if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
-                        newEdge = false;
-                        e = p;
-                    }
-                }
-                if (!newEdge) {
-                    if (outsideCon) {
-                    } else {
-                        controller.removeEdgesOnCanvas(e);
-                    }
-                    // Node ohne Edge?
-                    if (e.getA().getClass() == Node.class && e.getA().getConnections().isEmpty()) {
-                        tempCps = e.getA();
-                        deleteNode = true;
-                    }
-                    if (e.getB().getClass() == Node.class && e.getB().getConnections().isEmpty()) {
-                        deleteNode = true;
-                    }
-                } else {
-                	if(!(cps instanceof GroupNode || tempCps instanceof GroupNode)) {
-						e = new Edge(cps, tempCps, model.getMaxCapacity());
-						controller.addEdgeOnCanvas(e);
-					}else if (cps instanceof GroupNode && !(tempCps instanceof GroupNode)){
-						GroupNode thisUpperNode = (GroupNode)cps;
-						Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps)).filter(aCpsHandle -> !(aCpsHandle.object instanceof GroupNode)).toArray();
-						if(possibilities.length != 0) {
-							ACpsHandle selected = (ACpsHandle) JOptionPane.showInputDialog(this, "Select a inside Object:", "Connection To?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
-							if(selected != null) {
-								e = new Edge(selected.object, tempCps, model.getMaxCapacity());
-								controller.addEdgeOnCanvas(e);
-							}
-						}else {
-							Node n = new Node("Node");
-
-							n.setPosition(x, y);
-							controller.addObjUpperNode(n, thisUpperNode);
-							e = new Edge(n, tempCps, model.getMaxCapacity());
-							controller.addEdgeOnCanvas(e);
-						}
-						
-					}
-                }
-            }
-        }
-        if (!found && !outsideCon) {
-            int count = 0;
-            for (Edge ed : upperNode.getConnections()) {
-                AbstractCanvasObject 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 (Edge p : tempCps.getConnections()) {
-                        if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
-                            newEdge = false;
-                            e = p;
-                        }
-                    }
-                    if (!newEdge) {
-
-                        // Node ohne Edge?
-                        if (e.getA().getClass() == Node.class && e.getA().getConnections().isEmpty()) {
-                            tempCps = e.getA();
-                            deleteNode = true;
-                        }
-                        if (e.getB().getClass() == Node.class && e.getB().getConnections().isEmpty()) {
-                            deleteNode = true;
-                        }
-                    } else {
-                        Edge edge = new Edge(cps, tempCps, model.getMaxCapacity());
-                        if (outsideCon) {
-                        } else {
-                            controller.addEdgeOnCanvas(edge);
-                        }
-                    }
-                }
-                count++;
-            }
-        }
-
-        // Edge auf eine Edge gezogen?
-        if (onEdge && !checkForReplacement(x, y)) {
-            Edge p = mousePositionOnEdge(x, y);
-            if (p != null) {
-                Edge e1;
-                Edge e2;
-
-                node = false;
-
-                Node n = new Node("Node");
-
-                n.setPosition(x, y);
-                controller.addObjUpperNode(n, upperNode);
-
-                AbstractCanvasObject r, k;
-                r = p.getA();
-                k = p.getB();
-
-                e = new Edge(n, tempCps, model.getMaxCapacity());
-
-                e1 = new Edge(n, r, model.getMaxCapacity());
-
-                e2 = new Edge(n, k, model.getMaxCapacity());
-
-                controller.addEdgeOnCanvas(e1);
-                controller.addEdgeOnCanvas(e2);
-            }
-        }else{
-        	mayBeReplaced = null;
-        }
-
-        // ins leere Gedragged
-        if (node && x > upperNode.getLeftBorder() && !checkForReplacement(x, y)) {
-            Node n = new Node("Node");
-
-            n.setPosition(x, y);
-            controller.addObjUpperNode(n, upperNode);
-
-            e = new Edge(n, tempCps, model.getMaxCapacity());
-
-        }else{
-        	mayBeReplaced = null;
-        }
-
-        // 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 Edge mousePositionOnEdge(int x, int y) {
-        x += controller.getScaleDiv2();
-        y += controller.getScaleDiv2();
-        int lx, ly, hx, hy;
-
-//TODO: is this right
-//        for (CpsEdge p : upperNode.getNodeEdges()) {
-//            Line2D l = new Line2D.Float(p.getA().getPosition().getX(), p.getA().getPosition().getY(), p.getB().getPosition().getX(),
-//                    p.getB().getPosition().getY());
-//
-//            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 (Edge e : upperNode.getConnections()) {
-            AbstractCanvasObject cps;
-            if (e.getA().equals(this.upperNode)) {
-                cps = e.getB();
-            } else {
-                cps = e.getA();
-            }
-            for (Edge p : cps.getConnections()) {
-                AbstractCanvasObject 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().getX(),
-                            obj.getPosition().getY());
-                    if ((upperNode.getLeftBorder() >> 1) > obj.getPosition().getX()) {
-                        hx = (upperNode.getLeftBorder() >> 1) - 25 + model.getScaleDiv2() + 7;
-                        lx = obj.getPosition().getX() + model.getScaleDiv2() - 7;
-                    } else {
-                        lx = (upperNode.getLeftBorder() >> 1) - 25 + model.getScaleDiv2() - 7;
-                        hx = obj.getPosition().getX() + model.getScaleDiv2() + 7;
-                    }
-                    if ((int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) > obj.getPosition().getY()) {
-                        hy = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + model.getScaleDiv2() + 7;
-                        ly = obj.getPosition().getY() + model.getScaleDiv2() - 7;
-                    } else {
-                        ly = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count) + model.getScaleDiv2() - 7;
-                        hy = obj.getPosition().getY() + 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;
-    }
-
-
-
-    /**
-     * copies a set of given informations
-     *
-     * @param informations
-     */
-    protected void setShowedInformation(boolean[] informations) {
-        showedInformation = informations;
-    }
-
-
-    /**
-     * 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;
-    }
-    
-    @Override
-	public boolean checkForReplacement(int x, int y) {
-		return checkForReplacement(upperNode.getNodes(), null, x, y);
-	}
-    
-
-	@Override
-	public void tryToAlignObjects(){
-		/**
-		 * Align all Objects
-		 */
-		for(AbstractCanvasObject cps: upperNode.getNodes())
-			align(cps,3*model.getScaleDiv2());
-		
-		/**
-		 * AutoSave new Positons
-		 */
-		try{	
-			controller.autoSave();
-		} catch (IOException ex) {
-			System.err.println("AutoSave error by aligning");
-			ex.printStackTrace();
-		}
-	}
-
-	@Override
-	public void closeUpperNodeTab(int upperNodeId) {
-        JTabbedPane tabbedPane = (JTabbedPane) getParent().getParent().getParent();
-        for (int i = 4; i < tabbedPane.getTabCount(); i++) {
-            if (((GroupNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i)).getViewport()
-                    .getComponent(0)).upperNode.getId() == upperNodeId) {
-                tabbedPane.remove(i);
-                break;
-            }
-        }
-	}
-
-}

+ 0 - 51
src/ui/view/Main.java

@@ -1,51 +0,0 @@
-package ui.view;
-
-import ui.controller.Control;
-import ui.model.Model;
-
-import javax.swing.*;
-
-import java.awt.*;
-
-/**
- * The main Class in this Program. The GUI is created in this Class.
- * 
- * @author Gruppe14
- * 
- */
-public class Main {
-
-	/**
-	 * main method of this program.
-	 * 
-	 * @param args
-	 *            standard
-	 */
-	public static void main(String[] args) {
-		if (!System.getProperty("os.name").startsWith("Linux")) {
-			loadNotLinuxLookAndFeel();	
-		}
-		
-        EventQueue.invokeLater(() -> {
-            try {
-                Model model = new Model();
-                Control control = new Control(model);
-                GUI view = new GUI(control);
-                IndexTranslator.model = model;
-                view.getFrmCyberPhysical().setVisible(true);
-
-            } catch (Exception e) {
-                e.printStackTrace();
-            }
-        });
-    }
-
-	private static void loadNotLinuxLookAndFeel() {
-		try {
-		UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
-		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
-		e.printStackTrace();
-		}
-	}
-
-}

+ 0 - 1126
src/ui/view/MyCanvas.java

@@ -1,1126 +0,0 @@
-package ui.view;
-
-import java.awt.BasicStroke;
-import java.awt.Color;
-import java.awt.Font;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.RenderingHints;
-import java.awt.datatransfer.UnsupportedFlavorException;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
-import java.awt.geom.Line2D;
-import java.awt.image.BufferedImage;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-
-import javax.swing.ImageIcon;
-import javax.swing.JFrame;
-import javax.swing.JLabel;
-import javax.swing.JOptionPane;
-import javax.swing.JScrollPane;
-import javax.swing.JTabbedPane;
-import javax.swing.SwingUtilities;
-
-import com.google.gson.JsonParseException;
-
-import classes.AbstractCanvasObject;
-import classes.Edge;
-import classes.GroupNode;
-import classes.HolonObject;
-import classes.HolonSwitch;
-import classes.Node;
-import ui.controller.Control;
-import ui.controller.UpdateController;
-import ui.model.Consumer;
-import ui.model.DecoratedCable;
-import ui.model.DecoratedGroupNode;
-import ui.model.DecoratedHolonObject;
-import ui.model.DecoratedHolonObject.HolonObjectState;
-import ui.model.DecoratedSwitch;
-import ui.model.ExitCable;
-import ui.model.DecoratedSwitch.SwitchState;
-import ui.model.Model;
-import ui.model.Passiv;
-import ui.model.Supplier;
-import ui.model.VisualRepresentationalState;
-import utility.ImageImport;
-import utility.Vector2Int;
-
-/**
- * This Class is the Canvas. All Objects will be visualized here
- *
- * @author Gruppe14
- */
-public class MyCanvas extends AbstractCanvas implements MouseListener,
-		MouseMotionListener {
-
-	private static final long serialVersionUID = 1L;
-	public boolean disabled = false;
-	/**
-	 * Constructor.
-	 *
-	 * @param mod
-	 *            the Model
-	 * @param control
-	 *            the Controller
-	 * @param unitGraph
-	 */
-	public MyCanvas(Model mod, Control control, UnitGraph unitGraph) {
-		toolTip = false;
-		this.controller = control;
-		this.model = mod;
-		
-		scalediv20 = model.getScale() / 20;
-		
-		showConnectionInformation = true;
-		showedInformation[1] = true;
-		showedInformation[3] = false;
-		showedInformation[4] = true;
-		control.setMaxCapacity(10000);
-		popmenu.add(itemCut);
-		popmenu.add(itemCopy);
-		popmenu.add(itemPaste);
-		popmenu.add(itemDelete);
-		popmenu.add(itemAlign);
-		popmenu.addSeparator();
-		popmenu.add(itemGroup);
-		popmenu.add(itemUngroup);
-		popmenu.add(itemCreateTemplate);
-
-		updCon = new UpdateController(mod, control);
-
-		itemDelete.setEnabled(false);
-		itemCut.setEnabled(false);
-		itemCopy.setEnabled(false);
-		itemPaste.setEnabled(true);
-		itemAlign.setEnabled(false);
-		itemGroup.setEnabled(false);
-		itemUngroup.setEnabled(false);
-
-		itemCut.setText("Cut");
-		
-		itemGroup.addActionListener(actionEvent -> {
-			// calculate uppernode pos (taken from the controller)
-				unPos = new Vector2Int(0, 0);
-				animCps = new ArrayList<>();
-				for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-					animCps.add(cps); // add to animation Cps ArrayList
-					unPos = unPos.add(cps.getPosition());
-				}
-				unPos = unPos.divide(animCps.size());
-
-				// save old Position
-				savePos = new ArrayList<>();
-				for (int i = 0; i < animCps.size(); i++) {
-					savePos.add(animCps.get(i).getPosition().clone());
-				}
-
-				animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
-					if (animDuration - animDelay > 0 && animCps.size() > 1) {
-						for (AbstractCanvasObject animCpObject : animCps) {
-							Vector2Int pos = animCpObject.getPosition();
-	                    	Vector2Int difference = pos.subtract(unPos);
-	                    	Vector2Int result = pos.subtract(difference.divide(animSteps));
-	                    	pos.set(result);
-						}
-						repaint();
-						animDuration -= animDelay;
-						animSteps--;
-					} else {
-						animDuration = ANIMTIME;
-						animSteps = animDuration / animDelay;
-						animT.stop();
-						for (int i = 0; i < animCps.size(); i++) {
-							animCps.get(i).getPosition().set(savePos.get(i));
-						}
-						controller.addUpperNode("GroupNode", null, animCps);
-						controller.calculateStateAndVisualForCurrentTimeStep();
-						triggerUpdateController();
-						model.getSelectedCpsObjects().clear();
-						repaint();
-					}
-				});
-				animT.start();
-			});
-
-		itemUngroup
-				.addActionListener(actionEvent -> {
-					// save old Position
-					int upperNodeId = tempCps.getId();
-					
-					closeUpperNodeTab(upperNodeId);
-
-					savePos = new ArrayList<>();
-					animCps = ((GroupNode) tempCps).getNodes();
-					controller.ungroupGroupNode((GroupNode) tempCps, null);
-
-					for (int i = 0; i < animCps.size(); i++) {
-						savePos.add(animCps.get(i).getPosition().clone());
-					}
-					for (AbstractCanvasObject cps : animCps) {
-						int x = tempCps.getPosition().getX();
-						int y = tempCps.getPosition().getY();
-
-						cps.setPosition(new Vector2Int(x, y));
-					}
-
-					animT = new javax.swing.Timer(
-							animDelay,
-							actionEvent1 -> {
-								model.getSelectedCpsObjects().clear();
-								if (animDuration - animDelay >= 0) {
-									for (int i = 0; i < animCps.size(); i++) {
-										Vector2Int pos =  animCps.get(i).getPosition();
-				                    	Vector2Int difference = pos.subtract(savePos.get(i));
-				                    	Vector2Int result = pos.subtract(difference.divide(animSteps));
-				                    	pos.set(result);
-									}
-									repaint();
-									animDuration -= animDelay;
-									animSteps--;
-								} else {
-									animDuration = ANIMTIME;
-									animSteps = animDuration / animDelay;
-									animT.stop();
-									for (int i = 0; i < animCps.size(); i++) {
-										animCps.get(i).getPosition().set(savePos
-												.get(i));
-									}
-									controller.calculateStateAndVisualForCurrentTimeStep();
-									triggerUpdateController();
-									repaint();
-								}
-							});
-					animT.start();
-				});
-
-		// adds the selected object(s) to the statistic panel
-
-		itemDelete.addActionListener(actionEvent -> {
-			// Remove the selected Object objects
-				//Edge Deleting
-				if (tempCps == null && edgeHighlight != null) {
-					controller.removeEdgesOnCanvas(edgeHighlight);
-					//Look for a CPSNode with no Connections and delete them
-					if(edgeHighlight.getA().getClass() == Node.class && edgeHighlight.getA().getConnections().size() == 0){ 
-						controller.delCanvasObject(edgeHighlight.getA(), false);	
-					}
-					if(edgeHighlight.getB().getClass() == Node.class && edgeHighlight.getB().getConnections().size() == 0){ //Look on the other end of the cable
-						controller.delCanvasObject(edgeHighlight.getB(), false);
-					}
-					edgeHighlight = null;
-				}
-				boolean save = false;
-				for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
-					AbstractCanvasObject cps = model.getSelectedCpsObjects()
-							.get(j);
-					if (j == model.getSelectedCpsObjects().size() - 1)
-						save = true;
-					controller.delCanvasObject(cps, save);
-					// Remove UpperNodeTab if UpperNode deleted
-				if (cps instanceof GroupNode) {
-					JTabbedPane tabbedPane = (JTabbedPane)getParent().getParent()
-							.getParent().getParent();
-					// Look if the uppernode is open in a Tab
-					for (int i = 4; i < tabbedPane.getTabCount(); i++) {
-						if (tabbedPane.getComponentAt(i) != null
-								&& ((GroupNodeCanvas) ((JScrollPane) tabbedPane
-										.getComponentAt(i)).getViewport()
-										.getComponent(0)).upperNode.getId() == cps
-										.getId()) {
-							((ButtonTabComponent) tabbedPane
-									.getTabComponentAt(i)).removeTabs();
-							break;
-						}
-					}
-				}
-				toolTip = false;
-			}
-			model.getSelectedCpsObjects().clear();
-			tempCps = null;
-			repaint();
-		});
-
-		itemCut.addActionListener(actionEvent -> {
-			controller.cut(null);
-			itemPaste.setEnabled(true);
-			repaint();
-		});
-
-		itemCopy.addActionListener(actionEvent -> {
-			if(tempCps instanceof GroupNode)
-				controller.getObjectsInDepth();
-			controller.copy(null);
-			itemPaste.setEnabled(true);
-			repaint();
-		});
-
-		itemAlign.addActionListener(actionEvent ->
-		{
-			for(AbstractCanvasObject cps: model.getSelectedCpsObjects())
-				align(cps, model.getScaleDiv2());
-			repaint();
-		});
-		itemPaste
-				.addActionListener(actionEvent -> {
-					try {
-						controller.paste(null, mousePosition);
-
-					} 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();
-				});
-		
-		/*
-		 * create Template
-		 */
-		itemCreateTemplate.addActionListener(actionEvent -> {
-			controller.createTemplate((HolonObject)tempCps,(JFrame)SwingUtilities.getRoot(this));
-		});
-
-		this.addMouseListener(this);
-		this.addMouseMotionListener(this);
-	}
-
-	/**
-	 * Paints all Components on the Canvas.
-	 *
-	 * @param g
-	 *            Graphics
-	 */
-	
-	private Color getStateColor(HolonObjectState state) {
-		switch(state) {
-		case NOT_SUPPLIED:
-			return new Color(230, 120, 100);
-		case NO_ENERGY:
-			return Color.white;
-		case OVER_SUPPLIED:
-			return new Color(166, 78, 229);
-		case PARTIALLY_SUPPLIED:
-			return Color.yellow;
-		case PRODUCER:
-			return Color.lightGray;
-		case SUPPLIED:
-			return new Color(13, 175, 28);
-		default:
-			return Color.BLACK;
-		}
-	}
-	private void paintCanvasObject(Graphics2D g, DecoratedHolonObject decoratedHolonObject){
-		Vector2Int pos = decoratedHolonObject.getModel().getPosition();
-		Color statecolor = getStateColor(decoratedHolonObject.getState());
-		g.setColor(statecolor);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
-		drawCanvasObject(g, decoratedHolonObject.getModel().getImage(), pos);
-	}
-	private void drawCanvasObjectString(Graphics2D g, Vector2Int posOfCanvasObject, float energy) {
-		g.setColor(Color.BLACK);
-		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (controller.getScale() / 4f) )); 
-		g.drawString((energy > 0)? "+" + Float.toString(energy): Float.toString(energy), posOfCanvasObject.getX() - controller.getScaleDiv2(), posOfCanvasObject.getY() - controller.getScaleDiv2() - 1);
-	}
-	private void paintConsumer(Graphics2D g, Consumer con){
-		paintCanvasObject(g, con);
-		paintSupplyBar(g,con.getSupplyBarPercentage(), getStateColor(con.getState()), con.getModel().getPosition());
-		drawCanvasObjectString(g, con.getModel().getPosition(), -con.getEnergyNeededFromNetwork());
-	}
-	private void paintSupplier(Graphics2D g, Supplier sup){
-		paintCanvasObject(g, sup);
-		drawCanvasObjectString(g, sup.getModel().getPosition(), sup.getEnergyToSupplyNetwork());
-	}
-	
-	private void drawCanvasObject(Graphics2D g, String Image, Vector2Int pos) {
-		g.drawImage(ImageImport.loadImage(Image, controller.getScale(), controller.getScale()) , 
-				pos.getX() - controller.getScaleDiv2(),
-				pos.getY() - controller.getScaleDiv2(),
-				controller.getScale(), controller.getScale() , null);
-	}
-	
-	private void paintCable(Graphics2D g, DecoratedCable cable, boolean isSelected)
-	{
-		Vector2Int start = cable.getModel().getA().getPosition();
-		Vector2Int end =  cable.getModel().getB().getPosition();
-		float currentEnergy = cable.getFlowEnergy();
-		float capacity = cable.getModel().getCapacity();
-		boolean unlimited = cable.getModel().isUnlimitedCapacity();
-		switch(cable.getState()) {
-		case Burned:
-			g.setColor(Color.RED);
-			g.setStroke(new BasicStroke(2));
-			break;
-		case Working:
-			g.setColor(new Color(13, 175, 28));
-			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
-			break;
-		}
-		if(isSelected){
-			g.setColor(Color.lightGray);
-		}
-		g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
-		if(showConnectionInformation) {			
-			Vector2Int middle = new Vector2Int((start.getX() + end.getX()) / 2, (start.getY() + end.getY()) / 2);
-			g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
-			g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.getX(), middle.getY());
-		}
-	}
-	private void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch)
-	{
-		drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage(): HolonSwitch.getSwitchClosedImage() , dSwitch.getModel().getPosition());
-	}
-	
-	private void paintExitCable(Graphics2D g, ExitCable eCable) {
-		Vector2Int start = eCable.getStart().getPosition();
-		Vector2Int end = eCable.getFinish().getPosition();
-		float currentEnergy = eCable.getCable().getFlowEnergy();
-		float capacity = eCable.getCable().getModel().getCapacity();
-		boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
-		switch(eCable.getCable().getState()) {
-		case Burned:
-			g.setColor(Color.RED);
-			g.setStroke(new BasicStroke(2));
-			break;
-		case Working:
-			g.setColor(new Color(13, 175, 28));
-			g.setStroke(new BasicStroke(unlimited?2f:(currentEnergy / capacity * 2f) + 1));
-			break;
-		}
-		g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
-		Vector2Int middle = new Vector2Int((start.getX() + end.getX()) / 2, (start.getY() + end.getY()) / 2);
-		g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
-		g.drawString(currentEnergy + "/" + (unlimited?"\u221E":capacity) , middle.getX(), middle.getY());
-	}
-	private void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
-		Vector2Int pos = dGroupNode.getModel().getPosition();
-		g.setColor(Color.lightGray);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(), controller.getScale(), controller.getScale());
-		drawCanvasObject(g, "/Images/upper_node.png" , pos);
-		paintGroupNodeBar(g, dGroupNode, pos);
-	}
-	private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode , Vector2Int pos) {
-		// +1, -2, -1 little Adjustment for pixel perfect alignment
-		int barWidth = (int) (controller.getScale());
-		int barHeight = (int) (controller.getScale() / 5);
-		g.setColor(Color.WHITE);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
-		float[] percentages = getGroupNodeBarPercentages(dGroupNode);
-		Color[] colors = new Color[6];
-		colors[0] = getStateColor(HolonObjectState.PRODUCER);
-		colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
-		colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
-		colors[3] = getStateColor(HolonObjectState.SUPPLIED);
-		colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
-		colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
-				
-		for(int i = 5; i>=0; i--) {
-			g.setColor(colors[i]);
-			g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * percentages[i] - 1), barHeight);		
-		}
-//		g.setColor(color);
-//		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
-		g.setColor(Color.BLACK);
-		g.setStroke(new BasicStroke(1));
-		g.drawRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
-	}
-	/**
-	 * HardCoded Stuff dont try at Home ;)
-	 * @param dGroupNode
-	 * @return
-	 */
-	public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
-		int[] amountOfObjects = new int[6];
-		amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
-		amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
-		amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
-		amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
-		amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
-		amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
-		int countHolonObjects = amountOfObjects[0] + 	amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3] + amountOfObjects[4] + amountOfObjects[5];
-		float[] percentages = new float[6];
-		int count = 0;
-		for(int i = 0; i < 6; i++) {
-			count += amountOfObjects[i];
-			percentages[i] = (float)count / (float)countHolonObjects;
-		}
-		return percentages;
-	}
-	private void paintSupplyBar(Graphics2D g, float percentage, Color color, Vector2Int pos) {
-		// +1, -2, -1 little Adjustment for pixel perfect alignment
-		int barWidth = (int) (controller.getScale());
-		int barHeight = (int) (controller.getScale() / 5);
-		g.setColor(Color.WHITE);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) barWidth, barHeight);
-		g.setColor(color);
-		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
-		g.setColor(Color.BLACK);
-		g.setStroke(new BasicStroke(1));
-		g.drawRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, barWidth - 1 , barHeight);
-		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2)); 
-		String percentageString = (Math.round((percentage * 100))) + "%";
-		int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
-		if(percentage > 1.0f) g.setColor(Color.WHITE); //Just to see better on purple
-		g.drawString(percentageString, pos.getX() + 1 - stringWidth / 2, pos.getY() + controller.getScaleDiv2() - 1+ barHeight);
-		
-	}
-	
-	//old code
-	void drawMarker(Graphics2D g) {
-		Color transparentGrey = new Color(128, 174, 247, 40);
-		if (sx > x && sy > y) {
-			g.drawRect(x, y, sx - x, sy - y);
-			g.setColor(transparentGrey);
-			g.fillRect(x, y, sx - x, sy - y);
-		} else if (sx < x && sy < y) {
-			g.drawRect(sx, sy, x - sx, y - sy);
-			g.setColor(transparentGrey);
-			g.fillRect(sx, sy, x - sx, y - sy);
-		} else if (sx >= x) {
-			g.drawRect(x, sy, sx - x, y - sy);
-			g.setColor(transparentGrey);
-			g.fillRect(x, sy, sx - x, y - sy);
-		} else if (sy >= y) {
-			g.drawRect(sx, y, x - sx, sy - y);
-			g.setColor(transparentGrey);
-			g.fillRect(sx, y, x - sx, sy - y);
-		}
-	}
-	public void paintComponent(Graphics g) {		
-		super.paintComponent(g);
-		Graphics2D g2d = (Graphics2D) g;
-		g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING,
-				RenderingHints.VALUE_ANTIALIAS_ON));
-		//-->Old code
-		if (drawEdge) {
-			g2d.setColor(Color.BLACK);
-			g2d.setStroke(new BasicStroke(1));
-			g2d.drawLine(tempCps.getPosition().getX(), tempCps.getPosition().getY(), x, y);
-		}
-		//<--
-		//SelectedCable
-		HashSet<Edge> selectedEdges = new HashSet<Edge>();
-		for(AbstractCanvasObject aCps:  model.getSelectedCpsObjects()) {
-			for(Edge edge: aCps.getConnections()) {
-				selectedEdges.add(edge);
-			}
-		}
-		if(model.getSelectedEdge() != null) selectedEdges.add(model.getSelectedEdge());
-		//timstep:
-		g.setFont(new Font("TimesNewRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10) )); 
-		g2d.setColor(Color.BLACK);
-		
-		VisualRepresentationalState  visualState = controller.getSimManager().getActualVisualRepresentationalState();
-		//VisualState Representation:
-		if(visualState == null) System.out.println("AHHH"); 
-		for(ExitCable cable : visualState.getExitCableList()) {
-			paintExitCable(g2d, cable);
-		}
-		for(DecoratedCable cable : visualState.getCableList()) {
-			paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
-		}
-		for(DecoratedGroupNode dGroupNode : visualState.getGroupNodeList()) {
-			paintGroupNode(g2d, dGroupNode);
-		}
-		for(Consumer con: visualState.getConsumerList()) {
-			paintConsumer(g2d, con);					
-		}
-		for(Supplier sup: visualState.getSupplierList()) {
-			paintSupplier(g2d, sup);				
-		}
-		for(Passiv pas: visualState.getPassivList()) {
-			paintCanvasObject(g2d, pas);
-		}
-		for(DecoratedSwitch dSwitch : visualState.getSwitchList()) {
-				paintSwitch(g2d, dSwitch);
-		}
-		for(Node node : visualState.getNodeList()) {
-			drawCanvasObject(g2d, "/Images/node.png" , node.getPosition());
-		}
-		
-		//-->oldCode 
-		if (doMark) {
-			g2d.setColor(Color.BLACK);
-			g2d.setStroke(new BasicStroke(0));
-			drawMarker(g2d);
-		}
-		//Test Selection
-		//Objects:
-		g2d.setColor(Color.BLUE);
-		g2d.setStroke(new BasicStroke(1));
-		Color transparentGrey = new Color(128, 174, 247, 40);
-		for(AbstractCanvasObject aCps:  model.getSelectedCpsObjects()) {
-			if(aCps instanceof Node) {
-				Vector2Int pos = aCps.getPosition();
-				g2d.setColor(transparentGrey);
-				g2d.fillOval(pos.getX() - (int) (controller.getScaleDiv2()), pos.getY() - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
-				g2d.setColor(Color.LIGHT_GRAY);
-				g2d.setStroke(new BasicStroke(2));
-				g2d.drawOval(pos.getX() - (int) (controller.getScaleDiv2()), pos.getY() - (int) (controller.getScaleDiv2()),  controller.getScale(),  controller.getScale());
-			}
-			else {
-				Vector2Int pos = aCps.getPosition();
-				g2d.setColor(transparentGrey);
-				g2d.fillRect(pos.getX() - (int) (controller.getScaleDiv2()* 1.5f), pos.getY() - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));
-				g2d.setColor(Color.LIGHT_GRAY);
-				g2d.setStroke(new BasicStroke(2));
-				g2d.drawRect(pos.getX() - (int) (controller.getScaleDiv2()* 1.5f), pos.getY() - (int) (controller.getScaleDiv2()* 1.5f), (int) (controller.getScale()* 1.5f) , (int) (controller.getScale()* 1.5f));				
-			}
-
-		}
-		//maybeReplace:
-		if(mayBeReplaced != null){
-			g2d.setColor(Color.RED);
-			Vector2Int pos = mayBeReplaced.getPosition();
-			g2d.drawImage(ImageImport.loadImage("/Images/replace.png") , 
-					pos.getX() + controller.getScaleDiv2(),
-					pos.getY() - controller.getScale(),
-					controller.getScaleDiv2(), controller.getScaleDiv2(), null);
-		}
-		//<-- OldCode
-	}
-
-	@Override
-	public void mouseClicked(MouseEvent e) {
-		if(!disabled){
-			if (e.getButton() == MouseEvent.BUTTON1) {
-			DefaulTable propertyTable = model.getPropertyTable();
-			if (propertyTable.getRowCount() > 0) {
-				for (int i = propertyTable.getRowCount() - 1; i > -1; i--) {
-					propertyTable.removeRow(i);
-				}
-			}
-
-			triggerUpdateController();
-			}
-			stopEditing();
-		}
-	}
-
-	@Override
-	public void mouseEntered(MouseEvent e) {
-	}
-
-	@Override
-	public void mouseExited(MouseEvent e) {
-	}
-
-	@Override
-	public void mousePressed(MouseEvent e) {
-		if(!disabled){
-		stopEditing();
-		tempCps = null;
-		edgeHighlight = null;
-		controller.setSelecteEdge(null);
-		// Object Selection
-		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-			cx = cps.getPosition().getX() - controller.getScaleDiv2();
-			cy = cps.getPosition().getY() - controller.getScaleDiv2();
-			if (x - controller.getScale() <= cx
-					&& y - controller.getScale() <= cy && x >= cx && y >= cy) {
-				tempCps = cps;
-
-
-				dragging = true;
-
-				if (e.isControlDown() && tempCps != null) {
-					if (model.getSelectedCpsObjects().contains(tempCps)) {
-						controller.deleteSelectedObject(tempCps);
-							//TODO: RemoveDepth
-					} else {
-						controller.addSelectedObject(tempCps);
-						if(tempCps instanceof GroupNode)
-							controller.getObjectsInDepth();
-					}
-
-				}
-
-				// 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;
-				}
-			}
-		}
-
-		// Edge Selection
-		if (tempCps == null) {
-			edgeHighlight = mousePositionOnEdge(x, y);
-			controller.setSelecteEdge(edgeHighlight);
-			controller.setSelectedObjectID(0);
-			if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
-				model.getSelectedCpsObjects().clear();
-			}
-		}
-
-		if (edgeHighlight == null && tempCps == null) {
-			sx = e.getX();
-			sy = e.getY();
-			doMark = true;
-		}
-
-		repaint();
-		}
-	}
-
-	@Override
-	public void mouseReleased(MouseEvent e) {
-		if(!disabled){
-		x = e.getX();
-		y = e.getY();
-
-		dragging = false;
-
-		if (drawEdge) {
-			drawEdge = false;
-			drawDeleteEdge();
-		}
-
-		if (dragged) {
-			try {
-				/**
-				 * Save before further Dragged interactions happen
-				 */
-				controller.autoSave();
-				
-			} catch (IOException ex) {
-				System.err.println("AutoSave error by dragging");
-				ex.printStackTrace();
-			}
-			
-			/**
-			 * check if a unique tempCps could replace an Object on the canvas
-			 */
-			if(model.getSelectedCpsObjects().size()==1 
-					&& checkForReplacement(model.getObjectsOnCanvas(), tempCps, tempCps.getPosition().getX(), tempCps.getPosition().getY())){
-				/**
-            	 * if UpperNode would be replaced, close its tabs
-            	 */
-            	if(mayBeReplaced instanceof GroupNode)
-            		closeUpperNodeTab(mayBeReplaced.getId());
-				/**
-				 * replace on canvas (will save)
-				 */
-				controller.replaceCanvasObject(mayBeReplaced, tempCps);
-				mayBeReplaced=null;
-			}
-		}
-
-		if (!e.isControlDown() && !dragged && tempCps != null
-				&& MouseEvent.BUTTON3 != e.getButton()) {
-			model.getSelectedCpsObjects().clear();
-			controller.addSelectedObject(tempCps);
-			model.setSelectedCpsObject(tempCps);
-			if(tempCps instanceof GroupNode)
-				controller.getObjectsInDepth();
-		}
-
-		dragged = false;
-
-		// Rightclick List
-		setRightClickMenu(e);
-
-		markObjects();
-
-		if (doubleClick() && tempCps instanceof HolonSwitch 
-				&& MouseEvent.BUTTON3 != e.getButton()&& tempCps != null) {
-			((HolonSwitch) tempCps).switchState();
-
-		}
-		controller.calculateStateAndVisualForTimeStep(model.getCurIteration());
-
-		triggerUpdateController();
-
-		repaint();
-		}
-	}
-
-	@Override
-	public void mouseDragged(MouseEvent e) {
-		if(!disabled){
-		// 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 {
-				dragged = true;
-				float xDist, yDist; // Distance
-
-				x = e.getX();
-				y = e.getY();
-
-				// Make sure its in bounds
-				int scaleDiv2 = controller.getScaleDiv2();
-				if (e.getX() < scaleDiv2)
-					x = scaleDiv2;
-				else if (e.getX() > this.getWidth() - scaleDiv2)
-					x = this.getWidth() - scaleDiv2;
-				if (e.getY() < scaleDiv2)
-					y = scaleDiv2;
-				else if (e.getY() > this.getHeight()
-						- scaleDiv2)
-					y = this.getHeight() - scaleDiv2;
-
-				// Distance
-				xDist = x - tempCps.getPosition().getX();
-				yDist = y - tempCps.getPosition().getY();
-
-				tempCps.setPosition(x, y); // Drag Position
-				// ToolTipText Position and name
-				toolTip = true;
-				toolTipText = tempCps.getName() + ", " + tempCps.getId();
-				toolTipPos.setX(tempCps.getPosition().getX()
-						- scaleDiv2);
-				toolTipPos.setY(tempCps.getPosition().getY()
-						+ scaleDiv2);
-
-				// All Selected Objects
-				for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
-					if (cps != tempCps) {
-						x = (int) (cps.getPosition().getX() + xDist);
-						y = (int) (cps.getPosition().getY() + yDist);
-
-						// Make sure its in bounds
-						if (x <= scaleDiv2)
-							x = scaleDiv2;
-						else if (x > this.getWidth()
-								- scaleDiv2)
-							x = this.getWidth() - scaleDiv2;
-						if (y <= scaleDiv2)
-							y = scaleDiv2;
-						else if (y > this.getHeight()
-								- scaleDiv2)
-							y = this.getHeight() - scaleDiv2;
-
-						cps.setPosition(x, y);
-					}
-				}
-				
-				/**
-				 * check if something might be replaced
-				 */
-				if(model.getSelectedCpsObjects().size()==1)
-					checkForReplacement(model.getObjectsOnCanvas(), tempCps, x, y);
-				
-				repaint();
-			} catch (Exception eex) {
-			}
-		}
-
-		// Mark Objects
-		if (doMark) {
-			tempSelected.clear();
-			for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-				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().getX() + model.getScaleDiv2()
-						&& y1 <= cps.getPosition().getY() + model.getScaleDiv2()
-						&& x2 >= cps.getPosition().getX()
-						&& y2 >= cps.getPosition().getY()) {
-					tempSelected.add(cps);
-
-				}
-			}
-		}
-
-		repaint();
-		}
-	}
-
-	@Override
-	public void mouseMoved(MouseEvent e) {	
-		if(!disabled){
-		x = e.getX();
-		y = e.getY();
-
-		// Everything for the tooltip :)
-		boolean on = false;
-		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-			cx = cps.getPosition().getX() - controller.getScaleDiv2();
-			cy = cps.getPosition().getY() - controller.getScaleDiv2();
-
-			on = setToolTipInfoAndPosition(on, cps);
-		}
-		if(on||(!on && toolTip))
-		repaint();
-		toolTip = on;
-		}
-	}
-
-
-	/**
-	 * Draws or Deletes an Edge.
-	 */
-	void drawDeleteEdge() {
-		if (getMousePosition() != null) {
-			boolean node = true;
-			boolean newEdge = true;
-			boolean onEdge = true;
-			boolean deleteNode = false;
-			Edge e = null;
-
-			for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-				cx = cps.getPosition().getX() - controller.getScaleDiv2();
-				cy = cps.getPosition().getY() - controller.getScaleDiv2();
-				if (x - controller.getScale() <= cx
-						&& y - controller.getScale() <= cy && x >= cx
-						&& y >= cy && cps != tempCps) {
-					node = false;
-					onEdge = false;
-					for (Edge p : tempCps.getConnections()) {
-						if ((p.getA() == tempCps && p.getB() == cps)
-								|| (p.getB() == tempCps && p.getA() == cps)) {
-							newEdge = false;
-							e = p;
-						}
-					}
-					if (!newEdge) {
-						controller.removeEdgesOnCanvas(e);
-						// Node ohne Edge?
-						if (e.getA().getClass() == Node.class
-								&& e.getA().getConnections().isEmpty()) {
-							tempCps = e.getA();
-							deleteNode = true;
-						}
-						if (e.getB().getClass() == Node.class
-								&& e.getB().getConnections().isEmpty()) {
-							deleteNode = true;
-						}
-					} else {
-						if(!(cps instanceof GroupNode || tempCps instanceof GroupNode)) {
-							e = new Edge(cps, tempCps, model.getMaxCapacity());
-							controller.addEdgeOnCanvas(e);
-						}else if (cps instanceof GroupNode && !(tempCps instanceof GroupNode)){
-							GroupNode thisUpperNode = (GroupNode)cps;
-							Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps)).filter(aCpsHandle -> !(aCpsHandle.object instanceof GroupNode)).toArray();
-							if(possibilities.length != 0) {
-								ACpsHandle selected = (ACpsHandle) JOptionPane.showInputDialog(this, "Select a inside Object:", "Connection To?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , possibilities, "");
-								if(selected != null) {
-									e = new Edge(selected.object, tempCps, model.getMaxCapacity());
-									controller.addEdgeOnCanvas(e);
-								}
-							}else {
-								Node n = new Node("Node");
-
-								n.setPosition(x, y);
-								controller.addObjUpperNode(n, thisUpperNode);
-								e = new Edge(n, tempCps, model.getMaxCapacity());
-								controller.addEdgeOnCanvas(e);
-							}
-							
-						}
-						
-					}
-				}
-			}
-			// Edge auf eine Edge gezogen?
-			if (onEdge && !checkForReplacement(x, y)) {
-				Edge p = mousePositionOnEdge(x, y);
-				if (p != null) {
-					Edge e1;
-					Edge e2;
-
-					node = false;
-
-					Node n = new Node("Node");
-
-					n.setPosition(x, y);
-					controller.addObjectCanvas(n);
-
-					AbstractCanvasObject r, k;
-					r = p.getA();
-					k = p.getB();
-
-					e = new Edge(n, tempCps, model.getMaxCapacity());
-
-					e1 = new Edge(n, r, model.getMaxCapacity());
-
-					e2 = new Edge(n, k, model.getMaxCapacity());
-
-					controller.removeEdgesOnCanvas(p);
-					controller.addEdgeOnCanvas(e);
-					controller.addEdgeOnCanvas(e1);
-					controller.addEdgeOnCanvas(e2);
-				}
-			}else{
-				mayBeReplaced = null;
-			}
-
-			// ins leere Gedragged
-			if (node && !checkForReplacement(x, y)) {
-				Node n = new Node("Node");
-
-				n.setPosition(x, y);
-				
-					controller.addObjectCanvas(n);
-
-				e = new Edge(n, tempCps, model.getMaxCapacity());
-
-				controller.addEdgeOnCanvas(e);
-			}else{
-				mayBeReplaced = null;
-			}
-
-			// 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 Edge mousePositionOnEdge(int x, int y) {
-		x += controller.getScaleDiv2();
-		y += controller.getScaleDiv2();
-		for (Edge p : model.getEdgesOnCanvas()) {
-			Line2D l = new Line2D.Float(p.getA().getPosition().getX(), p.getA()
-					.getPosition().getY(), p.getB().getPosition().getX(), p.getB()
-					.getPosition().getY());
-
-			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 && y < hy) {
-				return p;
-			}
-		}
-		return null;
-	}
-
-	void updateLanguages() {
-		itemCut.setText("Cut");
-		itemCopy.setText("Copy");
-		itemPaste.setText("Paste");
-		itemDelete.setText("Delete");
-		itemGroup.setText("Group");
-		itemUngroup.setText("Ungroup");
-	}
-
-	/**
-	 * Set if Information should be shown.
-	 *
-	 * @param connection
-	 *            boolean for conecction
-	 * @param object
-	 *            boolean for objects
-	 * @param nodeOfnode
-	 */
-	void setShowedInformation(boolean connection, boolean object,
-			boolean border, boolean nodeOfnode) {
-		showConnectionInformation = connection;
-		showedInformation[1] = object;
-		showedInformation[3] = border;
-		showedInformation[4] = nodeOfnode;
-	}
-
-	/**
-	 * Returns if Information should be shown.
-	 *
-	 * @return Array of boolean [0] = connection, [1] = objects
-	 */
-	boolean[] getShowedInformation() {
-		return showedInformation;
-	}
-
-	/**
-	 * set toolTip
-	 *
-	 * @param bool
-	 */
-	void setToolTip(boolean bool) {
-		this.toolTip = bool;
-	}
-
-	/**
-	 * Set the Mouse
-	 *
-	 * @param x
-	 * @param y
-	 */
-	void setXY(int x, int y) {
-		this.x = x;
-		this.y = y;
-	}
-
-	@Override
-	public boolean checkForReplacement(int x, int y) {
-		
-		return checkForReplacement(model.getObjectsOnCanvas(), null, x, y);
-	}
-	
-	@Override
-	public void tryToAlignObjects(){
-		/**
-		 * Align all Objects
-		 */
-		for(AbstractCanvasObject cps: model.getObjectsOnCanvas())
-			align(cps,3*model.getScaleDiv2());
-		
-		/**
-		 * AutoSave new Positons
-		 */
-		try{	
-			controller.autoSave();
-		} catch (IOException ex) {
-			System.err.println("AutoSave error by aligning");
-			ex.printStackTrace();
-		}
-	}
-	
-	
-	@Override
-	public void closeUpperNodeTab(int upperNodeId) {
-		JTabbedPane tabbedPaneInner = (JTabbedPane) getParent()
-				.getParent().getParent().getParent();
-		for (int i = 1; i < tabbedPaneInner.getTabCount(); i++) {
-			if (((GroupNodeCanvas) ((JScrollPane) tabbedPaneInner
-					.getComponentAt(i)).getViewport().getComponent(
-							0)).upperNode.getId() == upperNodeId) {
-				tabbedPaneInner.remove(i);
-				break;
-			}
-		}
-	}
-	
-	
-	   
-}

+ 0 - 38
src/ui/view/PropertyTable.java

@@ -1,38 +0,0 @@
-package ui.view;
-
-import javax.swing.table.DefaultTableModel;
-
-/**
- * Property Table.
- * 
- * @author Gruppe14
- */
-public class PropertyTable extends DefaultTableModel {
-
-	private final int maxColumns = 7;
-	
-	@Override
-	public Class<?> getColumnClass(int columnIndex) {
-		//System.out.println("getColumnClass(" + "index:" + columnIndex+ ", ColumnCount:" + getColumnCount() + ")");
-		if (getColumnCount() == maxColumns) {
-			switch (columnIndex) {
-			case 4:
-			case 6:
-				return Boolean.class;
-			}
-		} else if (getColumnCount() == maxColumns - 1) {
-			switch (columnIndex) {
-			case 3:
-			case 5:
-				return Boolean.class;
-			}
-		}
-		return String.class;
-	}
-	
-	@Override
-	public boolean isCellEditable(int row, int column) {
-		return getColumnCount() == maxColumns && column > 1
-				|| getColumnCount() == maxColumns -1  && column > 0;
-	}
-}

+ 0 - 792
src/ui/view/UnitGraph.java

@@ -1,792 +0,0 @@
-package ui.view;
-
-import java.awt.BasicStroke;
-import java.awt.Color;
-import java.awt.Cursor;
-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 java.awt.geom.Path2D;
-import java.awt.geom.Point2D;
-import java.util.LinkedList;
-import java.util.ListIterator;
-
-import javax.swing.JPanel;
-
-import classes.UnitGraphPoint;
-import interfaces.GraphEditable;
-import interfaces.GraphEditable.Graphtype;
-import interfaces.LocalMode;
-import ui.controller.Control;
-import ui.model.Model;
-import utility.Vector2Int;
-
-/**
- * This Class represents a Graph where the User can model the behavior of
- * elements and switches over time.
- *
- * @author Tom Troppmann
- */
-public class UnitGraph extends JPanel implements MouseListener, MouseMotionListener, ComponentListener {
-
-    private static final long serialVersionUID = 1L;
-	
-	
-	// Normal Settings
-	private int border = 4;
-	private int clickThreshholdSquared = 25;
-	
-	// Display Settings
-	/**
-	 * The size of a dot in the graph.
-	 * It should be at least 1.
-	 * */
-	int dotSize = 8;
-	/** The Color of a dot in the graph. */
-	Color dotColor = Color.blue;
-	Color editDotColor = new Color(255, 119, 0);
-	
-	//Intern Variables
-	//TODO: JavaDoc
-	private LinkedList<UnitGraphPoint> actualGraphPoints = new LinkedList<UnitGraphPoint>();
-	private Graphtype actualGraphType;
-	private GraphEditable actualElement;
-	Vector2Int editPosition;
-	boolean editMode = false;
-	private enum pointType {Normal, StartPoint, EndPoint};
-	pointType editPoint = pointType.Normal;
-	
-	//Maybe Needed
-	private Model model;
-	
-	
-	private int widthWithBorder, heightWithBorder;
-	
-	
-	
-	
-	
-	
-    /**
-     * Constructor.
-     *
-     * @param model   the Model
-     * @param control the Controller
-     */
-    public UnitGraph(final Model model, Control control) {
-        setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
-        this.model = model;
-        this.setBackground(Color.WHITE);
-
-        this.addMouseListener(this);
-        this.addMouseMotionListener(this);
-        this.addComponentListener(this);
-    }
-    /**
-     * When the UnitGraph should represent a new GraphEditable Element.
-     * Its Updates the Graph and give access to the Element.
-     * @param element
-     */
-    public void initNewElement(GraphEditable element)
-    {
-    	overrideUnitGraph(element.getStateGraph());
-    	actualGraphType = element.getGraphType();
-    	actualElement = element;
-    	repaint();
-    }
-    
-    
-    
-    /**
-     * Paints the Graph, the Grid, the actual Line fro the currentIteration
-     * @param g Graphics
-     */
-    public void paintComponent(Graphics g) {
-        super.paintComponent(g);
-        Graphics2D g2D = (Graphics2D) g;
-        drawGrid(g2D);
-        g2D.setColor(Color.BLACK);
-        g2D.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
-        g2D.setStroke(new BasicStroke(2));
-        drawUnitGraph(g2D);
-        g2D.setColor(dotColor);
-        if(editMode)
-        {
-        	drawUnitGraphPointsReleased(g2D);
-        }else
-        {
-        	 drawUnitGraphPoints(g2D);
-        }
-        g2D.setColor(dotColor);
-        g2D.setStroke(new BasicStroke(1));
-        drawCurrentIterartionLine(g2D);
-    }
-
-    // Draw Methods only to let the User see the changes. Nothing its saved here or changed.
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Methods draws the UnitGraph whether its a boolGraph or a doubleGraph.
-     * @param g to draw.
-     */
-    private void drawUnitGraph(Graphics2D g) {
-    	switch(actualGraphType) {
-    	case boolGraph:
-    		if(editMode)
-    			drawBoolGraphInEditMode(g);
-    		else
-    			drawBoolGraph(g);
-    		break;
-    	case doubleGraph:
-    		if(editMode)
-    			drawDoubleGraphInEditMode(g);
-    		else
-    			drawDoubleGraph(g);
-    		break;
-    	default:
-    		throw new UnsupportedOperationException();
-    	}
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Methods draws the UnitGraphPoints of the UnitGraph.
-     * @param g to draw.
-     */
-    private void drawUnitGraphPoints(Graphics2D g) {
-    	g.setColor(dotColor);
-    	for(UnitGraphPoint p : actualGraphPoints){
-    		drawDot(g, p.displayedPosition);
-    	}
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Methods draws the UnitGraphPoints of the UnitGraph when its in EditMode.
-     * @param g to draw.
-     */
-    private void drawUnitGraphPointsReleased(Graphics2D g) {
-    	drawUnitGraphPoints(g);
-    	g.setColor(editDotColor);
-    	drawDot(g, editPosition);
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Methods draws the Grid on the Canvas.
-     * @param g2D to draw.
-     */
-	private void drawGrid(Graphics2D g2D) {
-        g2D.setStroke(new BasicStroke(1));
-        g2D.setColor(Color.lightGray);
-        int amountOfLines = 10;
-        int width = widthWithBorder + 2 * border;
-        int height = heightWithBorder;
-        for(int i = 0; i<=amountOfLines; i++)
-        {
-        	int linehieght = (int) (((double)i/ (double) amountOfLines) * (double) height) + border;
-        	g2D.drawLine(0, linehieght, width, linehieght);
-        }
-	}
-    
-	 /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws the CurrentIterationLine.
-     * @param g2D to draw.
-     */
-    private void drawCurrentIterartionLine(Graphics2D g)
-    {
-    	int cur = model.getCurIteration();
-    	int max = model.getIterations();
-    	double where;
-    	if(!this.isUsingLocalPeriod()) {
-    		where = ((double) cur)/((double) max);
-    	}
-    	else
-    	{
-    		int lPeriod = this.getLocalPeriod();
-    		where = ((double) cur%lPeriod)/((double) lPeriod);
-    	}
-    	Vector2Int oben = new Vector2Int(border + (int)(where * widthWithBorder), 0);
-    	Vector2Int unten = new Vector2Int(border + (int)(where * widthWithBorder), 2 * border + heightWithBorder);
-    	drawLine(g,oben,unten);
-    	
-    }
-    
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws a line between two Positions on the Canvas.
-     * @param g2D to draw.
-     * @param start the Position of one end of the line to draw. 
-     * @param end the other Ends Position of the Line to draw.
-     */
-    private void drawLine(Graphics2D g, Vector2Int start, Vector2Int end)
-    {
-    	Path2D.Double path = new Path2D.Double();
-    	path.moveTo(start.getX(), start.getY());
-    	path.lineTo(end.getX(), end.getY());
-    	g.draw(path);
-    }
-    
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * Initialize a Cubic BezierCurve.
-     * @param start The Position to start the Curve.
-     */
-    private Path2D.Double initBezier(Vector2Int start) {
-    	//Good Source for basic understanding for Bezier Curves
-        //http://www.theappguruz.com/blog/bezier-curve-in-games
-    	Path2D.Double path = new Path2D.Double();
-    	path.moveTo(start.getX(), start.getY());
-		return path;
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * Calculate the Path of a the Cubic BezierCurve with the special controlPoints to make the wanted behavior.
-     * @param path the path of the Bezier.
-     * @param actaul the actual Position of the Path.
-     * @param target the end Position of the Curve.
-     */
-    private void curveTo(Path2D.Double path, Vector2Int actual, Vector2Int target) {
-         double mitte = (actual.getX() + target.getX())* 0.5;
-         path.curveTo(mitte, actual.getY(), mitte, target.getY(), target.getX(), target.getY());
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * Draws a Dot at a Position.
-     * @param g to draw.
-     * @param p the position of the Dot.
-     */
-    private void drawDot(Graphics2D g, Vector2Int p)
-    {    	
-    	g.fillOval(p.getX() -dotSize/2, p.getY()-dotSize/2, dotSize, dotSize);
-    }
-    
-    
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws the UnitGraph as BoolGraph.
-     * @param g2D to draw.
-     */
-    private void drawBoolGraph(Graphics2D g) {
-    	if(actualGraphPoints.size() <= 1) return;
-    	LinkedList<Vector2Int> cornerPoints =  new LinkedList<Vector2Int>();
-     	ListIterator<UnitGraphPoint> iter = actualGraphPoints.listIterator();
-     	Vector2Int actual = actualGraphPoints.getFirst().displayedPosition;
-     	Path2D.Double path = new Path2D.Double();
-     	path.moveTo(actual.getX(), actual.getY());
-     	while (iter.hasNext())
-    	{
-    		Vector2Int target = iter.next().displayedPosition;
-    		//BooleanConnection
-    		path.lineTo(target.getX(), actual.getY()); //line to corner
-    		cornerPoints.add(new Vector2Int(target.getX(), actual.getY())); //save corner
-    		path.lineTo(target.getX(), target.getY()); //line to next Point
-    		
-    		actual = target;
-    	}
-     	g.draw(path);
-     	//Draw the Points on the Corner that dont exist in Data but should be visual
-     	g.setColor(dotColor);
-     	for(Vector2Int p: cornerPoints)
-     	{
-     		drawDot(g, p);
-     	}
-     	
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws the UnitGraph as BoolGraph in EditMode.
-     * @param g2D to draw.
-     */
-    private void drawBoolGraphInEditMode(Graphics2D g) {
-    	LinkedList<Vector2Int> before = new LinkedList<Vector2Int>();
-     	LinkedList<Vector2Int> after = new LinkedList<Vector2Int>();
-     	for(UnitGraphPoint p: actualGraphPoints)
-     	{
-     		if(p.displayedPosition.getX() < editPosition.getX())
-     			before.add(p.displayedPosition);
-     		else
-     			after.add(p.displayedPosition);
-     	}    	
-     	g.setColor(Color.BLACK);
-     	drawBoolGraphFromList(g, before);
-     	g.setColor(Color.BLACK);
-     	drawBoolGraphFromList(g, after);
-     	//EditGraph
-     	LinkedList<Vector2Int> middle = new LinkedList<Vector2Int>();
-     	if(!before.isEmpty()) middle.add(before.getLast());
-     	middle.add(editPosition);
-    	if(!after.isEmpty()) middle.add(after.getFirst());
-    	
-    	g.setColor(editDotColor);
-    	drawBoolGraphFromList(g, middle);
-    	drawSnappingHint(g);
-    }
-    
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws a red Hint to signal the User the snapping of the hovered Point under the Cursor in EditMode.
-     * @param g2D to draw.
-     */
-    private void drawSnappingHint(Graphics2D g)
-    {
-    	//ColorHint
-    	g.setColor(Color.RED);
-    	//Threshhold Line
-    	final float dash1[] = {10.0f};
-        final BasicStroke dashed =new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1, 0.0f);
-        g.setStroke(dashed);
-        
-        
-        int halfheight =  border + heightWithBorder / 2;
-        g.drawLine(0, halfheight , widthWithBorder + 2 * border, halfheight);
-        //Threshhold Text
-        g.drawString("Snapping Threshold", 10, halfheight - 2);
-    }
-    
-    
-    
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws a partial Graph from a Position List as BoolGraph.
-     * @param g2D to draw.
-     * @param list the PositionList to draw a BoolGraph
-     */
-	private void drawBoolGraphFromList(Graphics2D g, LinkedList<Vector2Int> list) {
-		if(list.size() <= 1) return;
-     	ListIterator<Vector2Int> iter = list.listIterator();
-      	LinkedList<Vector2Int> cornerPoints =  new LinkedList<Vector2Int>();
-     	Vector2Int actual = list.getFirst();
-     	Path2D.Double path = new Path2D.Double();
-     	path.moveTo(actual.getX(), actual.getY());
-     	while (iter.hasNext())
-    	{
-    		Vector2Int target = iter.next();
-    		//BooleanConnection
-    		path.lineTo(target.getX(), actual.getY()); //line to corner
-    		cornerPoints.add(new Vector2Int(target.getX(), actual.getY())); //save corner
-    		path.lineTo(target.getX(), target.getY()); //line to next Point
-    		actual = target;
-    	}
-     	g.draw(path);
-    	g.setColor(dotColor);
-     	for(Vector2Int p: cornerPoints)
-     	{
-     		drawDot(g, p);
-     	}
-	}
-    
-	  /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws the UnitGraph as DoubleGraph.
-     * @param g2D to draw.
-     */
-    private void drawDoubleGraph(Graphics2D g) {
-    	if(actualGraphPoints.isEmpty()) throw new IndexOutOfBoundsException("A Graph Without Points is not supportet jet");
-    	ListIterator<UnitGraphPoint> iter = actualGraphPoints.listIterator();
-    	Vector2Int actual = iter.next().displayedPosition;
-    	Path2D.Double path = this.initBezier(actual);
-    	while (iter.hasNext())
-    	{
-    		Vector2Int target = iter.next().displayedPosition;
-    		this.curveTo(path, actual, target);
-    		actual = target;
-    	}
-    	g.draw(path);
-    	
-    }
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws the UnitGraph as DoubleGraph in EditMode.
-     * @param g2D to draw.
-     */
-    private void drawDoubleGraphInEditMode(Graphics2D g) {
-     	LinkedList<Vector2Int> before = new LinkedList<Vector2Int>();
-     	LinkedList<Vector2Int> after = new LinkedList<Vector2Int>();
-     	for(UnitGraphPoint p: actualGraphPoints)
-     	{
-     		if(p.displayedPosition.getX() < editPosition.getX())
-     			before.add(p.displayedPosition);
-     		else
-     			after.add(p.displayedPosition);
-     	}    	
-     	drawUnitGraphFromList(g, before);
-     	drawUnitGraphFromList(g, after);
-     	//EditGraph
-     	LinkedList<Vector2Int> middle = new LinkedList<Vector2Int>();
-     	if(!before.isEmpty()) middle.add(before.getLast());
-     	middle.add(editPosition);
-    	if(!after.isEmpty()) middle.add(after.getFirst());
-    	
-    	g.setColor(editDotColor);
-    	drawUnitGraphFromList(g, middle);
-    }
-    
-    /**
-     * Helper Method to draw the UnitGraphPanel. {@link UnitGraph#paintComponent(Graphics)}
-     * <p>
-     * This Method draws a partial Graph from a Position List as DoubleGraph.
-     * @param g2D to draw.
-     * @param list the PositionList to draw a DoubleGraph
-     */
-	private void drawUnitGraphFromList(Graphics2D g, LinkedList<Vector2Int> list) {
-		if(list.size() <= 1) return;
-     	ListIterator<Vector2Int> iter = list.listIterator();
-     	Vector2Int actual = list.getFirst();
-     	Path2D.Double path = this.initBezier(actual);
-     	while (iter.hasNext())
-    	{
-    		Vector2Int target = iter.next();
-    		curveTo(path, actual, target);
-    		actual = target;
-    	}
-     	g.draw(path);
-	}
-  
-    //Under the hood functions to calculate and function the 
-    /**
-     * A unitgraphpoint have a x and y position to store the data of a graph point.
-     * Also it have a displayposition to store the Position of the GraphPoints on the Canvas. 
-     * e.g. when the canvas has 500 width and 200 height a GraphPoint with the X=0.5 and Y=1.0 should have a displayposition of (250,3) when border is 3.
-     */
-    private void updateRepresentativePositions()
-    {
-    	for(UnitGraphPoint p : actualGraphPoints) {
-    		p.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
-    	}
-    }
-    /**
-     * Takes a List of GraphPoints and convert it to the actual UnitGraphPoints with displayposition in the {@link #actualGraphPoints}
-     * @param stateCurve the list of GraphPoint
-     */
-    private void overrideUnitGraph(LinkedList<Point2D.Double> stateCurve) {
-    	actualGraphPoints.clear();
-    	for(Point2D.Double p: stateCurve){
-    		actualGraphPoints.add(new UnitGraphPoint(p));
-    	}
-    	updateRepresentativePositions();
-    }
-    
-    /**
-     * When the PanelSize Change the width and height to calculate the drawings have to be adjusted.
-     */
-    private void calculateWidthHeight()
-    {
-    	widthWithBorder = this.getWidth() - 2 * border;
-    	heightWithBorder = this.getHeight() - 2 * border;
-    }
-    
-    /**
-     * Save the actualGraphPoint List to the GraphEditable Element.
-     */
-    private void saveGraph() {
-    	LinkedList<Point2D.Double> actual = actualElement.getStateGraph();
-    	actual.clear();
-    	for(UnitGraphPoint p: actualGraphPoints)
-    	{
-    		actual.add(p.getPoint());
-    	}
-    	actualElement.sampleGraph();
-    }
-    /**
-     * Remove a UnitGraphPoint from the UnitGraphPoint list ({@link #actualGraphPoints} when its near a given Position.
-     * @param mPosition
-     */
-    private void removePointNearPosition(Vector2Int mPosition) {
-    	ListIterator<UnitGraphPoint> iter = actualGraphPoints.listIterator();
-    	while (iter.hasNext())
-    	{
-    		if(near(mPosition,iter.next().displayedPosition))
-    		{
-    			iter.remove();
-    			break;
-    		}
-    	}
-    }
-    
-    
-    /**
-     * Determine if the Point is a StartPoint , EndPoint or a NormalPoint a.k.a. in between Points.
-     * @param mPosition The Position to check.
-     */
-    private void  detectStartEndPoint(Vector2Int mPosition)
-    {
-    	UnitGraphPoint first = actualGraphPoints.getFirst();
-    	UnitGraphPoint last = actualGraphPoints.getLast();
-    	if(near(mPosition, first.displayedPosition)) editPoint = pointType.StartPoint;
-    	else if(near(mPosition, last.displayedPosition))  editPoint = pointType.EndPoint;
-    	else editPoint = pointType.Normal;
-    }
-
-    /**
-     * Determine if a Point is near the Cursor (depends on Mode what near means). To detect if it should grab the Point or create a new Point. 
-     * @param actual
-     * @param target
-     * @return
-     */
-	private boolean near(Vector2Int actual, Vector2Int target) {
-		switch(actualGraphType)
-		{
-		case boolGraph: //Distance only with X 
-			int xDis = target.getX() - actual.getX();
-			return xDis * xDis  < clickThreshholdSquared;
-		case doubleGraph:
-			return actual.getSquaredDistance(target) < clickThreshholdSquared;
-		default:
-			return false;
-		}	
-	}
-    
-	/**
-	 * When the Mouse Drag a Point it updates each time the position.
-	 * @param newPosition
-	 */
-    private void updateEditPointPosition(Vector2Int newPosition) {
-    	//make it in the bounds of the UnitGraph no Point out of the Border
-    	Vector2Int currentPosition = setInBounds(newPosition);
-    	if(editPoint != pointType.Normal) attachToBorder(currentPosition);
-    	if(actualGraphType == Graphtype.boolGraph) snapBoolean(currentPosition);
-    	this.editPosition = currentPosition;
-    }
-    
-    
-    /**
-     * No Point on the UnitGraph should exit the UnitGraph.
-     * @param p the Position
-	 * @return the updated Position.
-     */
-	private Vector2Int setInBounds(Vector2Int p) {
-		p.clampX(border, border + widthWithBorder);
-		p.clampY(border, border + heightWithBorder);
-		return p;
-	}
-    
-	
-	
-	/**
-	 * For Switches the Point have to be Snap to the Top or the Bottem.
-	 * @param p the Position
-	 * @return the updated Position.
-	 */
-	private Vector2Int snapBoolean(Vector2Int p)
-	{
-		if (p.getY() < border + heightWithBorder / 2) {
-			p.setY(border);
-		} else {
-			p.setY(border + heightWithBorder);
-		}
-		return p;
-	}
-	
-	
-	/**
-	 * The First Point has to be at 0(LeftSide) and Last Point has to be at 1(RightSide).  
-	 * @param p the Position
-	 * @return the updated Position.
-	 */
-	private Vector2Int attachToBorder(Vector2Int p)
-	{
-		switch(editPoint)
-		{
-		case StartPoint:
-			p.setX(border);
-			break;
-		case EndPoint:
-			p.setX(border + widthWithBorder);
-			break;
-		default:
-			break;
-		}
-		return p;
-	}
-	/**
-	 * Insert a Position in the UnitGraphList at the right order.
-	 * Its sorted based on the xValues.
-	 * @param pos The new UnitGraphPoints Position
-	 */
-    private void insertNewGraphPoint(Vector2Int pos)
-    {
-    	setInBounds(pos);
-    	ListIterator<UnitGraphPoint> iter2 = actualGraphPoints.listIterator();
-    	while (iter2.hasNext())
-    	{
-    		Vector2Int tempPosition = iter2.next().displayedPosition;
-    		if(pos.getX() <= tempPosition.getX())
-    		{
-    			//previous to go back a position to make the new point before the the Position with greater X
-    			iter2.previous();
-    			iter2.add(generateUnitGraphPoint(pos));
-    			break;
-    		}
-    	}
-    	if(!iter2.hasNext()) //if behind last point
-    	{
-    		iter2.add(generateUnitGraphPoint(pos));
-    	}
-    }
-    /**
-     * Generate a UnitGraphPoint from a normal Position in the UnitGraph.
-     * @param pos the normal pos with xValues from 0..Width and yValues from 0..Height
-     * @return a UnitGraphPoint
-     */
-	private UnitGraphPoint generateUnitGraphPoint(Vector2Int pos) {
-		UnitGraphPoint temp = new UnitGraphPoint((double) (pos.getX() - border) / (double) widthWithBorder,
-				1 - (double) (pos.getY() - border) / (double) heightWithBorder, true);
-		temp.displayedPosition = pos;
-		return temp;
-	}
-
-    /**
-     * Update the Point Position 
-     */
-	@Override
-    public void mouseDragged(MouseEvent e) {
-    	updateEditPointPosition(new Vector2Int(e.getPoint().x, e.getPoint().y));
-    	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) {
-    }
-
-    /**
-     * The First Step.
-     * When LeftMouseButton its checks if a point is to grab under the cursor or create a new Point. Then enter EditMode.
-     * When RightMouseButton its delete a point if its under the Curser.
-     */
-    @Override
-    public void mousePressed(MouseEvent e) {
-		Vector2Int mPosition = new Vector2Int(e.getPoint().x, e.getPoint().y);
-		if (e.getButton() == MouseEvent.BUTTON3) {
-			// RightMouseButtonEvent
-			detectStartEndPoint(mPosition);
-			if (editPoint == pointType.Normal) {
-				removePointNearPosition(mPosition);
-				repaint();
-			}
-			editMode = false;
-
-		} else if (e.getButton() == MouseEvent.BUTTON1) {
-			// LeftMouseButtonEvent
-			detectStartEndPoint(mPosition);
-			removePointNearPosition(mPosition);
-			updateEditPointPosition(mPosition);
-			editMode = true;
-			repaint();
-		}
-	}
-
-    /**
-     * The last step to save the Changes.
-     * Its insert the Hovering Point and exit EditMode.
-     */
-    @Override
-    public void mouseReleased(MouseEvent e) {
-    	if(editMode)
-    	{
-    		this.insertNewGraphPoint(editPosition);
-    		editMode = false;
-    		repaint();
-    	}
-    	saveGraph();
-    }
-
-    /**
-     * When the Component is Resized.
-     *
-     * @param e ComponentEvent
-     */
-    public void componentResized(ComponentEvent e) {
-    	calculateWidthHeight();
-    	updateRepresentativePositions();
-        repaint();
-    }
-
-    @Override
-    public void componentHidden(ComponentEvent e) {
-    }
-
-    @Override
-    public void componentMoved(ComponentEvent e) {
-
-    }
-
-    @Override
-    public void componentShown(ComponentEvent e) {
-    }
-
-    /**
-     * Resets the graph to normal.
-     */
-    public void reset() {
-       	if(this.actualElement != null) {
-       		actualElement.reset();
-       		overrideUnitGraph(actualElement.getStateGraph());
-       		repaint();
-       	}
-       	
-    }
-
-
-    
-    //LocalMode access methods...
-    //To access a element from the GUI for the LocalMode
-	public void setUseLocalPeriod(boolean state) {
-		if(this.actualElement != null) {
-			((LocalMode) actualElement).setUseLocalPeriod(state);
-       	}
-	}
-
-	public void setLocalPeriod(int localLength) {
-		if(this.actualElement != null) {
-			((LocalMode) actualElement).setLocalPeriod(localLength);
-       	}
-	}
-	
-	public int getLocalPeriod() {
-		if(this.actualElement != null) {
-			return ((LocalMode) actualElement).getLocalPeriod();
-       	}
-		return -1;
-	}
-	
-	public boolean isUsingLocalPeriod() {
-		if(this.actualElement != null) {
-			return ((LocalMode) actualElement).isUsingLocalPeriod();
-       	}
-		return false;
-	}
-
-	
-    
-
-}

+ 80 - 120
src/ui/view/AbstractCanvas.java → src/ui/view/canvas/AbstractCanvas.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.canvas;
 
 import java.awt.BasicStroke;
 import java.awt.Color;
@@ -8,14 +8,14 @@ import java.awt.Image;
 import java.awt.Point;
 import java.awt.event.MouseEvent;
 import java.util.ArrayList;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Set;
 import java.util.TimerTask;
 
-import javax.swing.CellEditor;
 import javax.swing.JMenuItem;
 import javax.swing.JPanel;
 import javax.swing.JPopupMenu;
-import javax.swing.JTable;
 import javax.swing.Timer;
 
 import classes.AbstractCanvasObject;
@@ -25,7 +25,6 @@ import classes.HolonElement;
 import classes.HolonObject;
 import classes.Node;
 import ui.controller.Control;
-import ui.controller.UpdateController;
 import ui.model.Model;
 import utility.Vector2Int;
 
@@ -43,16 +42,16 @@ public abstract class AbstractCanvas extends JPanel {
 	 * Version
 	 */
 	private static final long serialVersionUID = 1L;
-	
+
 	final JMenuItem itemCut = new JMenuItem("Cut");
 	final JMenuItem itemCopy = new JMenuItem("Copy");
-	final JMenuItem itemPaste = new JMenuItem("Paste");
+	public final JMenuItem itemPaste = new JMenuItem("Paste");
 	final JMenuItem itemDelete = new JMenuItem("Delete");
 	final JMenuItem itemGroup = new JMenuItem("Group");
 	final JMenuItem itemUngroup = new JMenuItem("Ungroup");
 	final JMenuItem itemAlign = new JMenuItem("Align selected");
 	final JMenuItem itemCreateTemplate = new JMenuItem("Create Template");
-	
+
 	final int ANIMTIME = 500; // animation Time
 	private final int animFPS = 60;
 	final int animDelay = 1000 / animFPS; // animation Delay
@@ -61,15 +60,14 @@ public abstract class AbstractCanvas extends JPanel {
 	protected int x = 0;
 	protected int y = 0;
 	// Selection
-	AbstractCanvasObject tempCps = null;
-	UpdateController updCon;
-	
-	//Replacement
+	public AbstractCanvasObject tempCps = null;
+
+	// Replacement
 	/**
 	 * the CpsObject that might be replaced by drag&drop
 	 */
-	protected AbstractCanvasObject mayBeReplaced = null;
-	
+	public AbstractCanvasObject mayBeReplaced = null;
+
 	// PopUpMenu
 	JPopupMenu popmenu = new JPopupMenu();
 	// Tooltip
@@ -77,14 +75,13 @@ public abstract class AbstractCanvas extends JPanel {
 	Vector2Int toolTipPos = new Vector2Int(); // Tooltip Position
 	String toolTipText = "";
 	List<HolonElement> dataSelected = new ArrayList<>();
-	ArrayList<AbstractCanvasObject> tempSelected = new ArrayList<>();
-	boolean[] showedInformation = new boolean[5];
+	protected Set<AbstractCanvasObject> tempSelected = new HashSet<>();
 	boolean showConnectionInformation;
 	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
-	Edge edgeHighlight = null;
+	public Edge edgeHighlight = null;
 	Point mousePosition = new Point(); // Mouse Position when
 	ArrayList<Vector2Int> savePos;
 	// edge Object Start Point
@@ -105,16 +102,14 @@ public abstract class AbstractCanvas extends JPanel {
 
 	// ------------------------------------------ METHODS
 	// ------------------------------------------
-	
-
-	
-	
 
-	class ACpsHandle{
+	class ACpsHandle {
 		public AbstractCanvasObject object;
-		ACpsHandle(AbstractCanvasObject object){
+
+		ACpsHandle(AbstractCanvasObject object) {
 			this.object = object;
 		}
+
 		public String toString() {
 			return object.toString();
 		}
@@ -131,6 +126,7 @@ public abstract class AbstractCanvas extends JPanel {
 			g2.drawRect(sx, y, x - sx, sy - y);
 		}
 	}
+
 	/**
 	 * @deprecated
 	 * @param g
@@ -161,8 +157,6 @@ public abstract class AbstractCanvas extends JPanel {
 		}
 	}
 
-
-
 	void setRightClickMenu(MouseEvent e) {
 		if (e.getButton() == MouseEvent.BUTTON3) {
 			itemPaste.setEnabled(true);
@@ -181,7 +175,7 @@ public abstract class AbstractCanvas extends JPanel {
 					itemUngroup.setEnabled(true);
 				else
 					itemUngroup.setEnabled(false);
-				if (model.getSelectedCpsObjects().size() == 0) {
+				if (model.getSelectedObjects().size() == 0) {
 					controller.addSelectedObject(tempCps);
 				}
 				if (tempCps instanceof HolonObject) {
@@ -212,17 +206,15 @@ public abstract class AbstractCanvas extends JPanel {
 	void markObjects() {
 		if (doMark) {
 			doMark = false;
-			for (AbstractCanvasObject cps : tempSelected) {
-				if (!model.getSelectedCpsObjects().contains(cps)) {
-					controller.addSelectedObject(cps);
-				}
+			if (!tempSelected.isEmpty()) {
+				controller.toggleSelectedObjects(tempSelected);
+				controller.getObjectsInDepth();
+				tempSelected.clear();
 			}
-			controller.getObjectsInDepth();
-			tempSelected.clear();
+			
 		}
 	}
 
-
 	int[] determineMousePositionOnEdge(Edge p) {
 		int lx, ly, hx, hy;
 
@@ -279,99 +271,94 @@ public abstract class AbstractCanvas extends JPanel {
 
 	abstract void drawDeleteEdge();
 
-	void triggerUpdateController() {
-		updCon.paintProperties(tempCps);
-		updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
-		updCon.refreshTableProperties(model.getPropertyTable());
-	}
-	
-	
 	/**
-	 * Checks if {@code draggedCps} or a new cpsObject at Position (x,y) could replace exactly one object
-	 * in {@code objects}.
-	 * Saves the object that would be replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
-	 * @param objects list of objects that could be replaced
+	 * Checks if {@code draggedCps} or a new cpsObject at Position (x,y) could
+	 * replace exactly one object in {@code objects}. Saves the object that would be
+	 * replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
+	 * 
+	 * @param objects    list of objects that could be replaced
 	 * @param draggedCps Object that might replace
-	 * @param x Position of the objects that might replace
-	 * @param y Position of the objects that might replace
-	 * @return true if exactly one Object could be replaced 
+	 * @param x          Position of the objects that might replace
+	 * @param y          Position of the objects that might replace
+	 * @return true if exactly one Object could be replaced
 	 */
-	protected boolean checkForReplacement(ArrayList<AbstractCanvasObject> objects, AbstractCanvasObject draggedCps, int x, int y){
-		
+	protected boolean checkForReplacement(ArrayList<AbstractCanvasObject> objects, AbstractCanvasObject draggedCps,
+			int x, int y) {
+
 		/** distance treshold for replacement */
-		int treshhold = controller.getScale()/2;
-						
+		int treshhold = controller.getScale() / 2;
+
 		/** number of Objects that might be replaced (should be 1) */
 		int replaceCounter = 0;
-		
+
 		/** last object that could be replaced */
 		AbstractCanvasObject toBeReplaced = null;
-		
+
 		/** Position of object that might be replaced */
 		Vector2Int p;
-		
+
 		/** for each cps on Canvas */
-		if(draggedCps == null || !(draggedCps instanceof Node) && !(draggedCps instanceof Node)){
-			for (AbstractCanvasObject cps : objects){
+		if (draggedCps == null || !(draggedCps instanceof Node) && !(draggedCps instanceof Node)) {
+			for (AbstractCanvasObject cps : objects) {
 				/** same object -> ignore */
-				if(cps == draggedCps)continue;
-						
+				if (cps == draggedCps)
+					continue;
+
 				/** set Position of object that might be replaced */
 				p = cps.getPosition();
-				
+
 				/** if near enough */
-				if(Math.abs(x-p.getX())<treshhold && Math.abs(y-p.getY())<treshhold){
+				if (Math.abs(x - p.getX()) < treshhold && Math.abs(y - p.getY()) < treshhold) {
 					replaceCounter++;
 					toBeReplaced = cps;
-					
+
 					/**
-					 * if too many Objects could be replaced:
-					 * stop searching, because it would not be clear which one should
-					 * be replaced
+					 * if too many Objects could be replaced: stop searching, because it would not
+					 * be clear which one should be replaced
 					 */
-					if(replaceCounter>1)break;
+					if (replaceCounter > 1)
+						break;
 				}
 			}
 		}
 		/**
 		 * return true if exactly one obect would be replaced
 		 */
-		if( replaceCounter == 1 && toBeReplaced != null){
+		if (replaceCounter == 1 && toBeReplaced != null) {
 			mayBeReplaced = toBeReplaced;
 			return true;
-		}else{
+		} else {
 			mayBeReplaced = null;
 			return false;
 		}
 	}
-	
+
 	/**
-	 * Checks if an inserted new Object could replace exactly one object on the canvas.
-	 * Saves the object that would be replaced in {@link AbstractCanvas}.{@code MayBeReplaced}
+	 * Checks if an inserted new Object could replace exactly one object on the
+	 * canvas. Saves the object that would be replaced in
+	 * {@link AbstractCanvas}.{@code MayBeReplaced}
+	 * 
 	 * @param x Position of the objects that might replace
 	 * @param y Position of the objects that might replace
-	 * @return true if exactly one Object could be replaced 
+	 * @return true if exactly one Object could be replaced
 	 */
 	public abstract boolean checkForReplacement(int x, int y);
-	
-		
+
 	/**
 	 * highlights the object that mayBeReplaced
+	 * 
 	 * @param g2
 	 */
 	protected void highlightMayBeReplaced(Graphics2D g2) {
-		if(mayBeReplaced != null){
+		if (mayBeReplaced != null) {
 			g2.setColor(Color.RED);
-			g2.fillRect(
-					(int) (mayBeReplaced.getPosition().getX()
-							- controller.getScaleDiv2() - (scalediv20 + 3)),
-					(int) (mayBeReplaced.getPosition().getY()
-							- controller.getScaleDiv2() - (scalediv20 + 3)),
+			g2.fillRect((int) (mayBeReplaced.getPosition().getX() - controller.getScaleDiv2() - (scalediv20 + 3)),
+					(int) (mayBeReplaced.getPosition().getY() - controller.getScaleDiv2() - (scalediv20 + 3)),
 					(int) (controller.getScale() + ((scalediv20 + 3) * 2)),
 					(int) (controller.getScale() + ((scalediv20 + 3) * 2)));
 		}
 	}
-	
+
 	/**
 	 * Align alle Objects on the Canvas to a Grid with objects every 10 pixels
 	 */
@@ -379,62 +366,35 @@ public abstract class AbstractCanvas extends JPanel {
 
 	/**
 	 * Aligns the Object the a grid
-	 * @param cps Object that should be aligned
-	 * @param distance distance between the AlignmentGrid Lines. (objects every 'distance' pixels
+	 * 
+	 * @param cps      Object that should be aligned
+	 * @param distance distance between the AlignmentGrid Lines. (objects every
+	 *                 'distance' pixels
 	 */
 	protected void align(AbstractCanvasObject cps, int distance) {
 		/** Position of the AbstractCpsObject which should be aligned */
 		Vector2Int p = cps.getPosition();
-		
-		//calculate how many pixels the cps should be decreased to align
+
+		// calculate how many pixels the cps should be decreased to align
 		/** x offset relative to a grid with lines every distance pixels */
 		int x_off = cps.getPosition().getX() % distance;
-		
+
 		/** y offset relative to a grid with lines every distance pixels */
 		int y_off = cps.getPosition().getY() % distance;
-		
-		//align to the other Line, if it is nearer
-		if(x_off > distance/2)
+
+		// align to the other Line, if it is nearer
+		if (x_off > distance / 2)
 			x_off -= distance;
-		if(y_off > distance/2)
+		if (y_off > distance / 2)
 			y_off -= distance;
-		
+
 		/** set new Position */
-		cps.setPosition(p.getX()-x_off, p.getY()-y_off);
-	}
-	
-	/**
-	 * Stops Editing in HolonElementTable and PropertyTable
-	 */
-	protected void stopEditing() {
-		/**
-		 * Stop Editing, if mouse exits the Table
-		 */
-		JTable holElem = model.getTableHolonElement();
-		CellEditor cellEditor = holElem.getCellEditor();
-		if (cellEditor != null) {
-		    if (cellEditor.getCellEditorValue() != null) {
-		    	/** TODO: Maybe try to save current Data */
-		        cellEditor.stopCellEditing();
-		    } else {
-		        cellEditor.cancelCellEditing();
-		    }
-		}
-		
-		JTable propertys = model.getTableProperties();
-		cellEditor = propertys.getCellEditor();
-		if (cellEditor != null) {
-		    if (cellEditor.getCellEditorValue() != null) {
-		    	/** TODO: Maybe try to save current Data */
-		        cellEditor.stopCellEditing();
-		    } else {
-		        cellEditor.cancelCellEditing();
-		    }
-		}
+		cps.setPosition(p.getX() - x_off, p.getY() - y_off);
 	}
 
 	/**
 	 * Closes a tab of the UpperNode with ID upperNodeID
+	 * 
 	 * @param upperNodeId
 	 */
 	public abstract void closeUpperNodeTab(int upperNodeId);

+ 1054 - 0
src/ui/view/canvas/Canvas.java

@@ -0,0 +1,1054 @@
+package ui.view.canvas;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Font;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseListener;
+import java.awt.event.MouseMotionListener;
+import java.awt.geom.Line2D;
+import java.awt.image.BufferedImage;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+
+import javax.swing.ImageIcon;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JScrollPane;
+import javax.swing.JTabbedPane;
+import javax.swing.SwingUtilities;
+
+import com.google.gson.JsonParseException;
+
+import classes.AbstractCanvasObject;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.Node;
+import ui.controller.Control;
+import ui.model.Consumer;
+import ui.model.DecoratedCable;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedHolonObject;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.DecoratedSwitch;
+import ui.model.ExitCable;
+import ui.model.DecoratedSwitch.SwitchState;
+import ui.view.inspector.UnitGraph;
+import ui.model.Model;
+import ui.model.Passiv;
+import ui.model.Supplier;
+import ui.model.VisualRepresentationalState;
+import utility.ImageImport;
+import utility.Vector2Int;
+
+/**
+ * This Class is the Canvas. All Objects will be visualized here
+ *
+ * @author Gruppe14
+ */
+public class Canvas extends AbstractCanvas implements MouseListener, MouseMotionListener {
+
+	private static final long serialVersionUID = 1L;
+	public boolean disabled = false;
+	private boolean showSupplyBar = false;
+
+	GroupNode groupNode = null;
+
+	Color[] colors = new Color[6];
+
+	/**
+	 * Constructor.
+	 *
+	 * @param mod       the Model
+	 * @param control   the Controller
+	 * @param unitGraph
+	 */
+	public Canvas(Model mod, Control control, UnitGraph unitGraph) {
+		toolTip = false;
+		this.controller = control;
+		this.model = mod;
+		colors[0] = getStateColor(HolonObjectState.PRODUCER);
+		colors[1] = getStateColor(HolonObjectState.NOT_SUPPLIED);
+		colors[2] = getStateColor(HolonObjectState.PARTIALLY_SUPPLIED);
+		colors[3] = getStateColor(HolonObjectState.SUPPLIED);
+		colors[4] = getStateColor(HolonObjectState.OVER_SUPPLIED);
+		colors[5] = getStateColor(HolonObjectState.NO_ENERGY);
+
+		scalediv20 = model.getScale() / 20;
+
+		showConnectionInformation = true;
+		control.setMaxCapacity(10000);
+		popmenu.add(itemCut);
+		popmenu.add(itemCopy);
+		popmenu.add(itemPaste);
+		popmenu.add(itemDelete);
+		popmenu.add(itemAlign);
+		popmenu.addSeparator();
+		popmenu.add(itemGroup);
+		popmenu.add(itemUngroup);
+		popmenu.add(itemCreateTemplate);
+
+		itemDelete.setEnabled(false);
+		itemCut.setEnabled(false);
+		itemCopy.setEnabled(false);
+		itemPaste.setEnabled(true);
+		itemAlign.setEnabled(false);
+		itemGroup.setEnabled(false);
+		itemUngroup.setEnabled(false);
+
+		itemCut.setText("Cut");
+
+		itemGroup.addActionListener(actionEvent -> {
+			// calculate uppernode pos (taken from the controller)
+			unPos = new Vector2Int(0, 0);
+			animCps = new ArrayList<>();
+			for (AbstractCanvasObject cps : model.getSelectedObjects()) {
+				animCps.add(cps); // add to animation Cps ArrayList
+				unPos = unPos.add(cps.getPosition());
+			}
+			unPos = unPos.divide(animCps.size());
+
+			// save old Position
+			savePos = new ArrayList<>();
+			for (int i = 0; i < animCps.size(); i++) {
+				savePos.add(animCps.get(i).getPosition().clone());
+			}
+
+			animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
+				if (animDuration - animDelay > 0 && animCps.size() > 1) {
+					for (AbstractCanvasObject animCpObject : animCps) {
+						Vector2Int pos = animCpObject.getPosition();
+						Vector2Int difference = pos.subtract(unPos);
+						Vector2Int result = pos.subtract(difference.divide(animSteps));
+						pos.set(result);
+					}
+					repaint();
+					animDuration -= animDelay;
+					animSteps--;
+				} else {
+					animDuration = ANIMTIME;
+					animSteps = animDuration / animDelay;
+					animT.stop();
+					for (int i = 0; i < animCps.size(); i++) {
+						animCps.get(i).getPosition().set(savePos.get(i));
+					}
+					controller.addUpperNode("GroupNode", groupNode, animCps);
+					controller.calculateStateAndVisualForCurrentTimeStep();
+					controller.clearSelection();
+					repaint();
+				}
+			});
+			animT.start();
+		});
+
+		itemUngroup.addActionListener(actionEvent -> {
+			// save old Position
+			int upperNodeId = tempCps.getId();
+
+			closeUpperNodeTab(upperNodeId);
+
+			savePos = new ArrayList<>();
+			animCps = ((GroupNode) tempCps).getNodes();
+			controller.ungroupGroupNode((GroupNode) tempCps, groupNode);
+
+			for (int i = 0; i < animCps.size(); i++) {
+				savePos.add(animCps.get(i).getPosition().clone());
+			}
+			for (AbstractCanvasObject cps : animCps) {
+				int x = tempCps.getPosition().getX();
+				int y = tempCps.getPosition().getY();
+
+				cps.setPosition(new Vector2Int(x, y));
+			}
+
+			animT = new javax.swing.Timer(animDelay, actionEvent1 -> {
+				controller.clearSelection();
+				if (animDuration - animDelay >= 0) {
+					for (int i = 0; i < animCps.size(); i++) {
+						Vector2Int pos = animCps.get(i).getPosition();
+						Vector2Int difference = pos.subtract(savePos.get(i));
+						Vector2Int result = pos.subtract(difference.divide(animSteps));
+						pos.set(result);
+					}
+					repaint();
+					animDuration -= animDelay;
+					animSteps--;
+				} else {
+					animDuration = ANIMTIME;
+					animSteps = animDuration / animDelay;
+					animT.stop();
+					for (int i = 0; i < animCps.size(); i++) {
+						animCps.get(i).getPosition().set(savePos.get(i));
+					}
+					controller.calculateStateAndVisualForCurrentTimeStep();
+					repaint();
+				}
+			});
+			animT.start();
+		});
+
+		// adds the selected object(s) to the statistic panel
+
+		itemDelete.addActionListener(actionEvent -> {
+			// Remove the selected Object objects
+			// Edge Deleting
+			if (tempCps == null && edgeHighlight != null) {
+				controller.removeEdgesOnCanvas(edgeHighlight);
+				// Look for a CPSNode with no Connections and delete them
+				if (edgeHighlight.getA() instanceof Node
+						&& edgeHighlight.getA().getConnections().size() == 0) {
+					controller.delCanvasObject(edgeHighlight.getA(), false);
+				}
+				if (edgeHighlight.getB() instanceof Node
+						&& edgeHighlight.getB().getConnections().size() == 0) { // Look on the other end of the cable
+					controller.delCanvasObject(edgeHighlight.getB(), false);
+				}
+				edgeHighlight = null;
+			}
+			for (AbstractCanvasObject cps : model.getSelectedObjects()) {
+				controller.delCanvasObject(cps, false);
+				toolTip = false;
+			}
+			controller.tryAutoSave();
+			controller.clearSelection();
+			tempCps = null;
+			repaint();
+		});
+
+		itemCut.addActionListener(actionEvent -> {
+			controller.cut(null);
+			itemPaste.setEnabled(true);
+			repaint();
+		});
+
+		itemCopy.addActionListener(actionEvent -> {
+			if (tempCps instanceof GroupNode)
+				controller.getObjectsInDepth();
+			controller.copy(null);
+			itemPaste.setEnabled(true);
+			repaint();
+		});
+
+		itemAlign.addActionListener(actionEvent -> {
+			for (AbstractCanvasObject cps : model.getSelectedObjects())
+				align(cps, model.getScaleDiv2());
+			repaint();
+		});
+		itemPaste.addActionListener(actionEvent -> {
+			try {
+				controller.paste(null, mousePosition);
+
+			} 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();
+		});
+
+		/*
+		 * create Template
+		 */
+		itemCreateTemplate.addActionListener(actionEvent -> {
+			controller.createTemplate((HolonObject) tempCps, (JFrame) SwingUtilities.getRoot(this));
+		});
+
+		this.addMouseListener(this);
+		this.addMouseMotionListener(this);
+	}
+
+	/**
+	 * Paints all Components on the Canvas.
+	 *
+	 * @param g Graphics
+	 */
+
+	protected Color getStateColor(HolonObjectState state) {
+		switch (state) {
+		case NOT_SUPPLIED:
+			return new Color(230, 120, 100);
+		case NO_ENERGY:
+			return Color.white;
+		case OVER_SUPPLIED:
+			return new Color(166, 78, 229);
+		case PARTIALLY_SUPPLIED:
+			return Color.yellow;
+		case PRODUCER:
+			return Color.lightGray;
+		case SUPPLIED:
+			return new Color(13, 175, 28);
+		default:
+			return Color.BLACK;
+		}
+	}
+
+	protected void paintCanvasObject(Graphics2D g, DecoratedHolonObject decoratedHolonObject) {
+		Vector2Int pos = decoratedHolonObject.getModel().getPosition();
+		Color statecolor = getStateColor(decoratedHolonObject.getState());
+		g.setColor(statecolor);
+		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(),
+				controller.getScale(), controller.getScale());
+		drawCanvasObject(g, decoratedHolonObject.getModel().getImage(), pos);
+	}
+
+	protected void drawCanvasObjectString(Graphics2D g, Vector2Int posOfCanvasObject, float energy) {
+		g.setColor(Color.BLACK);
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (controller.getScale() / 4f)));
+		g.drawString((energy > 0) ? "+" + Float.toString(energy) : Float.toString(energy),
+				posOfCanvasObject.getX() - controller.getScaleDiv2(),
+				posOfCanvasObject.getY() - controller.getScaleDiv2() - 1);
+	}
+
+	protected void paintConsumer(Graphics2D g, Consumer con) {
+		paintCanvasObject(g, con);
+		drawCanvasObjectString(g, con.getModel().getPosition(), -con.getEnergyNeededFromNetwork());
+		if (showSupplyBar) {
+			paintSupplyBar(g, con.getSupplyBarPercentage(), getStateColor(con.getState()),
+					con.getModel().getPosition());
+		}
+	}
+
+	protected void paintSupplier(Graphics2D g, Supplier sup) {
+		paintCanvasObject(g, sup);
+		drawCanvasObjectString(g, sup.getModel().getPosition(), sup.getEnergyToSupplyNetwork());
+	}
+
+	protected void drawCanvasObject(Graphics2D g, String Image, Vector2Int pos) {
+		g.drawImage(ImageImport.loadImage(Image, controller.getScale(), controller.getScale()),
+				pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(), controller.getScale(),
+				controller.getScale(), null);
+	}
+
+	protected void paintCable(Graphics2D g, DecoratedCable cable, boolean isSelected) {
+		Vector2Int start = cable.getModel().getA().getPosition();
+		Vector2Int end = cable.getModel().getB().getPosition();
+		float currentEnergy = cable.getFlowEnergy();
+		float capacity = cable.getModel().getCapacity();
+		boolean unlimited = cable.getModel().isUnlimitedCapacity();
+		switch (cable.getState()) {
+		case Burned:
+			g.setColor(Color.RED);
+			g.setStroke(new BasicStroke(2));
+			break;
+		case Working:
+			g.setColor(new Color(13, 175, 28));
+			g.setStroke(new BasicStroke(unlimited ? 2f : (currentEnergy / capacity * 2f) + 1));
+			break;
+		}
+		if (isSelected) {
+			g.setColor(Color.lightGray);
+		}
+		g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
+		if (showConnectionInformation) {
+			Vector2Int middle = new Vector2Int((start.getX() + end.getX()) / 2, (start.getY() + end.getY()) / 2);
+			g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10)));
+			g.drawString(currentEnergy + "/" + (unlimited ? "\u221E" : capacity), middle.getX(), middle.getY());
+		}
+	}
+
+	protected void paintSwitch(Graphics2D g, DecoratedSwitch dSwitch) {
+		drawCanvasObject(g, dSwitch.getState() == SwitchState.Open ? HolonSwitch.getSwitchOpenImage()
+				: HolonSwitch.getSwitchClosedImage(), dSwitch.getModel().getPosition());
+	}
+
+	protected void paintExitCable(Graphics2D g, ExitCable eCable) {
+		Vector2Int start = eCable.getStart().getPosition();
+		Vector2Int end = eCable.getFinish().getPosition();
+		float currentEnergy = eCable.getCable().getFlowEnergy();
+		float capacity = eCable.getCable().getModel().getCapacity();
+		boolean unlimited = eCable.getCable().getModel().isUnlimitedCapacity();
+		switch (eCable.getCable().getState()) {
+		case Burned:
+			g.setColor(Color.RED);
+			g.setStroke(new BasicStroke(2));
+			break;
+		case Working:
+			g.setColor(new Color(13, 175, 28));
+			g.setStroke(new BasicStroke(unlimited ? 2f : (currentEnergy / capacity * 2f) + 1));
+			break;
+		}
+		g.drawLine(start.getX(), start.getY(), end.getX(), end.getY());
+		Vector2Int middle = new Vector2Int((start.getX() + end.getX()) / 2, (start.getY() + end.getY()) / 2);
+		g.setFont(new Font("TimesRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10)));
+		g.drawString(currentEnergy + "/" + (unlimited ? "\u221E" : capacity), middle.getX(), middle.getY());
+	}
+
+	protected void paintGroupNode(Graphics2D g, DecoratedGroupNode dGroupNode) {
+		Vector2Int pos = dGroupNode.getModel().getPosition();
+		g.setColor(Color.lightGray);
+		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() - controller.getScaleDiv2(),
+				controller.getScale(), controller.getScale());
+		drawCanvasObject(g, "/Images/upper_node.png", pos);
+		paintGroupNodeBar(g, dGroupNode, pos);
+	}
+
+	private void paintGroupNodeBar(Graphics2D g, DecoratedGroupNode dGroupNode, Vector2Int pos) {
+		// +1, -2, -1 little Adjustment for pixel perfect alignment
+		int barWidth = (int) (controller.getScale());
+		int barHeight = (int) (controller.getScale() / 5);
+		g.setColor(Color.WHITE);
+		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) barWidth,
+				barHeight);
+		float[] percentages = getGroupNodeBarPercentages(dGroupNode);
+
+		for (int i = 5; i >= 0; i--) {
+			g.setColor(colors[i]);
+			g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1,
+					(int) (barWidth * percentages[i] - 1), barHeight);
+		}
+//		g.setColor(color);
+//		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
+		g.setColor(Color.BLACK);
+		g.setStroke(new BasicStroke(1));
+		g.drawRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, barWidth - 1,
+				barHeight);
+	}
+
+	/**
+	 * HardCoded Stuff dont try at Home ;)
+	 * 
+	 * @param dGroupNode
+	 * @return
+	 */
+	public float[] getGroupNodeBarPercentages(DecoratedGroupNode dGroupNode) {
+		int[] amountOfObjects = new int[6];
+		amountOfObjects[0] = dGroupNode.getAmountOfSupplier();
+		amountOfObjects[1] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+		amountOfObjects[2] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+		amountOfObjects[3] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+		amountOfObjects[4] = dGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+		amountOfObjects[5] = dGroupNode.getAmountOfPassiv();
+		int countHolonObjects = amountOfObjects[0] + amountOfObjects[1] + amountOfObjects[2] + amountOfObjects[3]
+				+ amountOfObjects[4] + amountOfObjects[5];
+		float[] percentages = new float[6];
+		int count = 0;
+		for (int i = 0; i < 6; i++) {
+			count += amountOfObjects[i];
+			percentages[i] = (float) count / (float) countHolonObjects;
+		}
+		return percentages;
+	}
+
+	private void paintSupplyBar(Graphics2D g, float percentage, Color color, Vector2Int pos) {
+		// +1, -2, -1 little Adjustment for pixel perfect alignment
+		int barWidth = (int) (controller.getScale());
+		int barHeight = (int) (controller.getScale() / 5);
+		g.setColor(Color.WHITE);
+		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, (int) barWidth,
+				barHeight);
+		g.setColor(color);
+		g.fillRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1,
+				(int) (barWidth * (percentage < 1 ? percentage : 1.0f) - 1), barHeight);
+		g.setColor(Color.BLACK);
+		g.setStroke(new BasicStroke(1));
+		g.drawRect(pos.getX() - controller.getScaleDiv2(), pos.getY() + controller.getScaleDiv2() - 1, barWidth - 1,
+				barHeight);
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, (int) (barHeight * 1.5) - 2));
+		String percentageString = (Math.round((percentage * 100))) + "%";
+		int stringWidth = (int) g.getFontMetrics().getStringBounds(percentageString, g).getWidth();
+		if (percentage > 1.0f)
+			g.setColor(Color.WHITE); // Just to see better on purple
+		g.drawString(percentageString, pos.getX() + 1 - stringWidth / 2,
+				pos.getY() + controller.getScaleDiv2() - 1 + barHeight);
+
+	}
+
+	// old code
+	void drawMarker(Graphics2D g) {
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		if (sx > x && sy > y) {
+			g.drawRect(x, y, sx - x, sy - y);
+			g.setColor(transparentGrey);
+			g.fillRect(x, y, sx - x, sy - y);
+		} else if (sx < x && sy < y) {
+			g.drawRect(sx, sy, x - sx, y - sy);
+			g.setColor(transparentGrey);
+			g.fillRect(sx, sy, x - sx, y - sy);
+		} else if (sx >= x) {
+			g.drawRect(x, sy, sx - x, y - sy);
+			g.setColor(transparentGrey);
+			g.fillRect(x, sy, sx - x, y - sy);
+		} else if (sy >= y) {
+			g.drawRect(sx, y, x - sx, sy - y);
+			g.setColor(transparentGrey);
+			g.fillRect(sx, y, x - sx, sy - y);
+		}
+	}
+
+	public void paintComponent(Graphics g) {
+		super.paintComponent(g);
+		Graphics2D g2d = (Graphics2D) g;
+		g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
+		// -->Old code
+		if (drawEdge) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(1));
+			g2d.drawLine(tempCps.getPosition().getX(), tempCps.getPosition().getY(), x, y);
+		}
+		// <--
+		// SelectedCable
+		HashSet<Edge> selectedEdges = new HashSet<Edge>();
+		for (AbstractCanvasObject aCps : model.getSelectedObjects()) {
+			for (Edge edge : aCps.getConnections()) {
+				selectedEdges.add(edge);
+			}
+		}
+		if (model.getSelectedEdge() != null)
+			selectedEdges.add(model.getSelectedEdge());
+		// timstep:
+		g.setFont(new Font("TimesNewRoman", Font.PLAIN, Math.max((int) (controller.getScale() / 3.5f), 10)));
+		g2d.setColor(Color.BLACK);
+
+		VisualRepresentationalState visualState = controller.getSimManager().getActualVisualRepresentationalState();
+		// VisualState Representation:
+		if (visualState == null) {
+			System.out.println("AHHH");
+			return;
+		}
+		for (ExitCable cable : visualState.getExitCableList()) {
+			paintExitCable(g2d, cable);
+		}
+		for (DecoratedCable cable : visualState.getCableList()) {
+			paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
+		}
+		for (DecoratedGroupNode dGroupNode : visualState.getGroupNodeList()) {
+			paintGroupNode(g2d, dGroupNode);
+		}
+		for (Consumer con : visualState.getConsumerList()) {
+			paintConsumer(g2d, con);
+		}
+		for (Supplier sup : visualState.getSupplierList()) {
+			paintSupplier(g2d, sup);
+		}
+		for (Passiv pas : visualState.getPassivList()) {
+			paintCanvasObject(g2d, pas);
+		}
+		for (DecoratedSwitch dSwitch : visualState.getSwitchList()) {
+			paintSwitch(g2d, dSwitch);
+		}
+		for (Node node : visualState.getNodeList()) {
+			drawCanvasObject(g2d, "/Images/node.png", node.getPosition());
+		}
+
+		// -->oldCode
+		if (doMark) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(0));
+			drawMarker(g2d);
+		}
+		// Test Selection
+		// Objects:
+		g2d.setColor(Color.BLUE);
+		g2d.setStroke(new BasicStroke(1));
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		for (AbstractCanvasObject aCps : model.getSelectedObjects()) {
+			if (aCps instanceof Node) {
+				Vector2Int pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillOval(pos.getX() - (int) (controller.getScaleDiv2()),
+						pos.getY() - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawOval(pos.getX() - (int) (controller.getScaleDiv2()),
+						pos.getY() - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
+			} else {
+				Vector2Int pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillRect(pos.getX() - (int) (controller.getScaleDiv2() * 1.5f),
+						pos.getY() - (int) (controller.getScaleDiv2() * 1.5f), (int) (controller.getScale() * 1.5f),
+						(int) (controller.getScale() * 1.5f));
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawRect(pos.getX() - (int) (controller.getScaleDiv2() * 1.5f),
+						pos.getY() - (int) (controller.getScaleDiv2() * 1.5f), (int) (controller.getScale() * 1.5f),
+						(int) (controller.getScale() * 1.5f));
+			}
+
+		}
+		// maybeReplace:
+		if (mayBeReplaced != null) {
+			g2d.setColor(Color.RED);
+			Vector2Int pos = mayBeReplaced.getPosition();
+			g2d.drawImage(ImageImport.loadImage("/Images/replace.png"), pos.getX() + controller.getScaleDiv2(),
+					pos.getY() - controller.getScale(), controller.getScaleDiv2(), controller.getScaleDiv2(), null);
+		}
+		// <-- OldCode
+	}
+
+	@Override
+	public void mouseClicked(MouseEvent e) {
+	}
+
+	@Override
+	public void mouseEntered(MouseEvent e) {
+	}
+
+	@Override
+	public void mouseExited(MouseEvent e) {
+	}
+
+	@Override
+	public void mousePressed(MouseEvent e) {
+		this.grabFocus();
+		if (!disabled) {
+			tempCps = null;
+			edgeHighlight = null;
+			controller.setSelecteEdge(null);
+			// Object Selection
+			for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
+				cx = cps.getPosition().getX() - controller.getScaleDiv2();
+				cy = cps.getPosition().getY() - controller.getScaleDiv2();
+				if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
+					tempCps = cps;
+
+					dragging = true;
+
+					if (e.isControlDown() && tempCps != null) {
+						System.out.println("Add Remove Selection CANVAS");
+						if (model.getSelectedObjects().contains(tempCps)) {
+							controller.removeObjectFromSelection(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;
+					}
+				}
+			}
+
+			// Edge Selection
+			if (tempCps == null) {
+				edgeHighlight = mousePositionOnEdge(x, y);
+				controller.setSelecteEdge(edgeHighlight);
+				controller.setSelectedObjectID(0);
+				if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
+					controller.clearSelection();
+				}
+			}
+
+			if (edgeHighlight == null && tempCps == null) {
+				sx = e.getX();
+				sy = e.getY();
+				doMark = true;
+			}
+
+			repaint();
+		}
+	}
+
+	@Override
+	public void mouseReleased(MouseEvent e) {
+		if (!disabled) {
+			x = e.getX();
+			y = e.getY();
+
+			dragging = false;
+
+			if (drawEdge) {
+				drawEdge = false;
+				drawDeleteEdge();
+			}
+
+			if (dragged) {
+				try {
+					/**
+					 * Save before further Dragged interactions happen
+					 */
+					controller.autoSave();
+
+				} catch (IOException ex) {
+					System.err.println("AutoSave error by dragging");
+					ex.printStackTrace();
+				}
+
+				/**
+				 * check if a unique tempCps could replace an Object on the canvas
+				 */
+				if (model.getSelectedObjects().size() == 1 && checkForReplacement(model.getObjectsOnCanvas(),
+						tempCps, tempCps.getPosition().getX(), tempCps.getPosition().getY())) {
+					/**
+					 * if UpperNode would be replaced, close its tabs
+					 */
+					if (mayBeReplaced instanceof GroupNode)
+						closeUpperNodeTab(mayBeReplaced.getId());
+					/**
+					 * replace on canvas (will save)
+					 */
+					controller.replaceCanvasObject(mayBeReplaced, tempCps);
+					mayBeReplaced = null;
+				}
+			}
+
+			if (!e.isControlDown() && !dragged && tempCps != null && MouseEvent.BUTTON3 != e.getButton()) {
+				controller.clearSelection();
+				controller.addSelectedObject(tempCps);
+				if (tempCps instanceof GroupNode)
+					controller.getObjectsInDepth();
+			}
+
+			dragged = false;
+
+			// Rightclick List
+			setRightClickMenu(e);
+
+			markObjects();
+
+			boolean doubleclick = doubleClick();
+			if (doubleclick && tempCps instanceof HolonSwitch && MouseEvent.BUTTON3 != e.getButton()
+					&& tempCps != null) {
+				((HolonSwitch) tempCps).switchState();
+			}
+			if (doubleclick && tempCps != null && tempCps instanceof GroupNode) {
+				controller.getGui().openNewUpperNodeTab((GroupNode) tempCps);
+			}
+			controller.calculateStateAndVisualForTimeStep(model.getCurrentIteration());
+
+			repaint();
+		}
+	}
+
+	@Override
+	public void mouseDragged(MouseEvent e) {
+		if (!disabled) {
+			// If Edge is drawn
+			x = e.getX();
+			y = e.getY();
+
+			if (!model.getSelectedObjects().contains(tempCps) && !doMark) {
+				controller.clearSelection();
+				if (tempCps != null) {
+					controller.addSelectedObject(tempCps);
+				}
+			}
+			if (dragging) {
+				try {
+					dragged = true;
+					float xDist, yDist; // Distance
+
+					x = e.getX();
+					y = e.getY();
+
+					// Make sure its in bounds
+					int scaleDiv2 = controller.getScaleDiv2();
+					if (e.getX() < scaleDiv2)
+						x = scaleDiv2;
+					else if (e.getX() > this.getWidth() - scaleDiv2)
+						x = this.getWidth() - scaleDiv2;
+					if (e.getY() < scaleDiv2)
+						y = scaleDiv2;
+					else if (e.getY() > this.getHeight() - scaleDiv2)
+						y = this.getHeight() - scaleDiv2;
+
+					// Distance
+					xDist = x - tempCps.getPosition().getX();
+					yDist = y - tempCps.getPosition().getY();
+
+					tempCps.setPosition(x, y); // Drag Position
+					// ToolTipText Position and name
+					toolTip = true;
+					toolTipText = tempCps.getName() + ", " + tempCps.getId();
+					toolTipPos.setX(tempCps.getPosition().getX() - scaleDiv2);
+					toolTipPos.setY(tempCps.getPosition().getY() + scaleDiv2);
+
+					// All Selected Objects
+					for (AbstractCanvasObject cps : model.getSelectedObjects()) {
+						if (cps != tempCps) {
+							x = (int) (cps.getPosition().getX() + xDist);
+							y = (int) (cps.getPosition().getY() + yDist);
+
+							// Make sure its in bounds
+							if (x <= scaleDiv2)
+								x = scaleDiv2;
+							else if (x > this.getWidth() - scaleDiv2)
+								x = this.getWidth() - scaleDiv2;
+							if (y <= scaleDiv2)
+								y = scaleDiv2;
+							else if (y > this.getHeight() - scaleDiv2)
+								y = this.getHeight() - scaleDiv2;
+
+							cps.setPosition(x, y);
+						}
+					}
+
+					/**
+					 * check if something might be replaced
+					 */
+					if (model.getSelectedObjects().size() == 1)
+						checkForReplacement(model.getObjectsOnCanvas(), tempCps, x, y);
+
+					repaint();
+				} catch (Exception eex) {
+				}
+			}
+
+			// Mark Objects
+			if (doMark) {
+				tempSelected.clear();
+				for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
+					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().getX() + model.getScaleDiv2()
+							&& y1 <= cps.getPosition().getY() + model.getScaleDiv2() && x2 >= cps.getPosition().getX()
+							&& y2 >= cps.getPosition().getY()) {
+						tempSelected.add(cps);
+
+					}
+				}
+			}
+
+			repaint();
+		}
+	}
+
+	@Override
+	public void mouseMoved(MouseEvent e) {
+		if (!disabled) {
+			x = e.getX();
+			y = e.getY();
+
+			// Everything for the tooltip :)
+			boolean on = false;
+			for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
+				cx = cps.getPosition().getX() - controller.getScaleDiv2();
+				cy = cps.getPosition().getY() - controller.getScaleDiv2();
+
+				on = setToolTipInfoAndPosition(on, cps);
+			}
+			if (on || (!on && toolTip))
+				repaint();
+			toolTip = on;
+		}
+	}
+
+	/**
+	 * Draws or Deletes an Edge.
+	 */
+	void drawDeleteEdge() {
+		if (getMousePosition() != null) {
+			boolean node = true;
+			boolean newEdge = true;
+			boolean onEdge = true;
+			boolean deleteNode = false;
+			Edge e = null;
+
+			for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
+				cx = cps.getPosition().getX() - controller.getScaleDiv2();
+				cy = cps.getPosition().getY() - controller.getScaleDiv2();
+				if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy
+						&& cps != tempCps) {
+					node = false;
+					onEdge = false;
+					for (Edge p : tempCps.getConnections()) {
+						if ((p.getA() == tempCps && p.getB() == cps) || (p.getB() == tempCps && p.getA() == cps)) {
+							newEdge = false;
+							e = p;
+						}
+					}
+					if (!newEdge) {
+						controller.removeEdgesOnCanvas(e);
+						// Node ohne Edge?
+						if (e.getA().getClass() == Node.class && e.getA().getConnections().isEmpty()) {
+							tempCps = e.getA();
+							deleteNode = true;
+						}
+						if (e.getB().getClass() == Node.class && e.getB().getConnections().isEmpty()) {
+							deleteNode = true;
+						}
+					} else {
+						if (!(cps instanceof GroupNode || tempCps instanceof GroupNode)) {
+							e = new Edge(cps, tempCps, model.getMaxCapacity());
+							controller.addEdgeOnCanvas(e);
+						} else if (cps instanceof GroupNode && !(tempCps instanceof GroupNode)) {
+							GroupNode thisUpperNode = (GroupNode) cps;
+							Object[] possibilities = thisUpperNode.getNodes().stream().map(aCps -> new ACpsHandle(aCps))
+									.filter(aCpsHandle -> !(aCpsHandle.object instanceof GroupNode)).toArray();
+							if (possibilities.length != 0) {
+								ACpsHandle selected = (ACpsHandle) JOptionPane.showInputDialog(this,
+										"Select a inside Object:", "Connection To?", JOptionPane.OK_OPTION,
+										new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)),
+										possibilities, "");
+								if (selected != null) {
+									e = new Edge(selected.object, tempCps, model.getMaxCapacity());
+									controller.addEdgeOnCanvas(e);
+								}
+							} else {
+								Node n = new Node("Node");
+
+								n.setPosition(x, y);
+								controller.addObjUpperNode(n, thisUpperNode);
+								e = new Edge(n, tempCps, model.getMaxCapacity());
+								controller.addEdgeOnCanvas(e);
+							}
+
+						}
+
+					}
+				}
+			}
+			// Edge auf eine Edge gezogen?
+			if (onEdge && !checkForReplacement(x, y)) {
+				Edge p = mousePositionOnEdge(x, y);
+				if (p != null) {
+					Edge e1;
+					Edge e2;
+
+					node = false;
+
+					Node n = new Node("Node");
+
+					n.setPosition(x, y);
+					controller.addObjectCanvas(n);
+
+					AbstractCanvasObject r, k;
+					r = p.getA();
+					k = p.getB();
+
+					e = new Edge(n, tempCps, model.getMaxCapacity());
+
+					e1 = new Edge(n, r, model.getMaxCapacity());
+
+					e2 = new Edge(n, k, model.getMaxCapacity());
+
+					controller.removeEdgesOnCanvas(p);
+					controller.addEdgeOnCanvas(e);
+					controller.addEdgeOnCanvas(e1);
+					controller.addEdgeOnCanvas(e2);
+				}
+			} else {
+				mayBeReplaced = null;
+			}
+
+			// ins leere Gedragged
+			if (node && !checkForReplacement(x, y)) {
+				Node n = new Node("Node");
+
+				n.setPosition(x, y);
+
+				controller.addObjectCanvas(n);
+
+				e = new Edge(n, tempCps, model.getMaxCapacity());
+
+				controller.addEdgeOnCanvas(e);
+			} else {
+				mayBeReplaced = null;
+			}
+
+			// 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
+	 */
+	protected Edge mousePositionOnEdge(int x, int y) {
+		x += controller.getScaleDiv2();
+		y += controller.getScaleDiv2();
+		for (Edge p : model.getEdgesOnCanvas()) {
+			Line2D l = new Line2D.Float(p.getA().getPosition().getX(), p.getA().getPosition().getY(),
+					p.getB().getPosition().getX(), p.getB().getPosition().getY());
+
+			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
+					&& y < hy) {
+				return p;
+			}
+		}
+		return null;
+	}
+
+	/**
+	 * set toolTip
+	 *
+	 * @param bool
+	 */
+	public void setToolTip(boolean bool) {
+		this.toolTip = bool;
+	}
+
+	/**
+	 * Set the Mouse
+	 *
+	 * @param x
+	 * @param y
+	 */
+	public void setXY(int x, int y) {
+		this.x = x;
+		this.y = y;
+	}
+
+	@Override
+	public boolean checkForReplacement(int x, int y) {
+
+		return checkForReplacement(model.getObjectsOnCanvas(), null, x, y);
+	}
+
+	@Override
+	public void tryToAlignObjects() {
+		/**
+		 * Align all Objects
+		 */
+		for (AbstractCanvasObject cps : model.getObjectsOnCanvas())
+			align(cps, 3 * model.getScaleDiv2());
+
+		/**
+		 * AutoSave new Positons
+		 */
+		try {
+			controller.autoSave();
+		} catch (IOException ex) {
+			System.err.println("AutoSave error by aligning");
+			ex.printStackTrace();
+		}
+	}
+
+	@Override
+	public void closeUpperNodeTab(int upperNodeId) {
+		JTabbedPane tabbedPaneInner = (JTabbedPane) getParent().getParent().getParent().getParent();
+		for (int i = 1; i < tabbedPaneInner.getTabCount(); i++) {
+			if (((GroupNodeCanvas) ((JScrollPane) tabbedPaneInner.getComponentAt(i)).getViewport().getComponent(0))
+					.getGroupNode().getId() == upperNodeId) {
+				tabbedPaneInner.remove(i);
+				break;
+			}
+		}
+	}
+
+}

+ 489 - 0
src/ui/view/canvas/GroupNodeCanvas.java

@@ -0,0 +1,489 @@
+package ui.view.canvas;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.RenderingHints;
+import java.awt.event.MouseEvent;
+import java.io.IOException;
+import java.util.HashSet;
+
+import classes.AbstractCanvasObject;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.Node;
+import ui.controller.Control;
+import ui.model.Consumer;
+import ui.model.DecoratedCable;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedSwitch;
+import ui.model.ExitCable;
+import ui.model.Model;
+import ui.model.Passiv;
+import ui.model.Supplier;
+import ui.view.inspector.UnitGraph;
+import utility.ImageImport;
+import utility.Vector2Int;
+
+
+//TODO delete GroupNodeCanvas completely and only have canvas Class
+public class GroupNodeCanvas extends Canvas {
+	private String parentPath;
+	private Component parentComponent;
+
+	public GroupNodeCanvas(Model mod, Control control, UnitGraph unitGraph, GroupNode groupNode, String parentPath,
+			Component parentComponent) {
+		super(mod, control, unitGraph);
+		this.groupNode = groupNode;
+		this.parentPath = parentPath;
+		this.parentComponent = parentComponent;
+	}
+
+	public void setGroupNode(GroupNode upperNode) {
+		this.groupNode = upperNode;
+	}
+
+	public GroupNode getGroupNode() {
+		return groupNode;
+	}
+
+	public String getParentPath() {
+		return parentPath;
+	}
+
+	public Component getParentComponent() {
+		return parentComponent;
+	}
+
+	public void paintComponent(Graphics g) {
+		// super.paintComponent(g);
+		Graphics2D g2d = (Graphics2D) g;
+		g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
+		g2d.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
+		// -->Old code
+		if (drawEdge) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(1));
+			g2d.drawLine(tempCps.getPosition().getX(), tempCps.getPosition().getY(), x, y);
+		}
+		// <--
+		// SelectedCable
+		HashSet<Edge> selectedEdges = new HashSet<Edge>();
+		for (AbstractCanvasObject aCps : model.getSelectedObjects()) {
+			for (Edge edge : aCps.getConnections()) {
+				selectedEdges.add(edge);
+			}
+		}
+		if (model.getSelectedEdge() != null)
+			selectedEdges.add(model.getSelectedEdge());
+
+		DecoratedGroupNode actualGroupNode = controller.getSimManager().getActualVisualRepresentationalState()
+				.getCreatedGroupNodes().get(groupNode);
+		// VisualState Representation:
+		for (ExitCable cable : actualGroupNode.getExitCableList()) {
+			paintExitCable(g2d, cable);
+		}
+		for (DecoratedCable cable : actualGroupNode.getInternCableList()) {
+			paintCable(g2d, cable, selectedEdges.contains(cable.getModel()));
+		}
+
+		for (DecoratedGroupNode dGroupNode : actualGroupNode.getGroupNodeList()) {
+			paintGroupNode(g2d, dGroupNode);
+		}
+		for (Consumer con : actualGroupNode.getConsumerList()) {
+			paintConsumer(g2d, con);
+		}
+		for (Supplier sup : actualGroupNode.getSupplierList()) {
+			paintSupplier(g2d, sup);
+		}
+		for (Passiv pas : actualGroupNode.getPassivList()) {
+			paintCanvasObject(g2d, pas);
+		}
+		for (DecoratedSwitch dSwitch : actualGroupNode.getSwitchList()) {
+			paintSwitch(g2d, dSwitch);
+		}
+		for (Node node : actualGroupNode.getNodeList()) {
+			drawCanvasObject(g2d, "/Images/node.png", node.getPosition());
+		}
+
+		// -->oldCode
+		if (doMark) {
+			g2d.setColor(Color.BLACK);
+			g2d.setStroke(new BasicStroke(0));
+			drawMarker(g2d);
+		}
+		// Test Selection
+		// Objects:
+		g2d.setColor(Color.BLUE);
+		g2d.setStroke(new BasicStroke(1));
+		Color transparentGrey = new Color(128, 174, 247, 40);
+		for (AbstractCanvasObject aCps : model.getSelectedObjects()) {
+			if (aCps instanceof Node) {
+				Vector2Int pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillOval(pos.getX() - (int) (controller.getScaleDiv2()),
+						pos.getY() - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawOval(pos.getX() - (int) (controller.getScaleDiv2()),
+						pos.getY() - (int) (controller.getScaleDiv2()), controller.getScale(), controller.getScale());
+			} else {
+				Vector2Int pos = aCps.getPosition();
+				g2d.setColor(transparentGrey);
+				g2d.fillRect(pos.getX() - (int) (controller.getScaleDiv2() * 1.5f),
+						pos.getY() - (int) (controller.getScaleDiv2() * 1.5f), (int) (controller.getScale() * 1.5f),
+						(int) (controller.getScale() * 1.5f));
+				g2d.setColor(Color.LIGHT_GRAY);
+				g2d.setStroke(new BasicStroke(2));
+				g2d.drawRect(pos.getX() - (int) (controller.getScaleDiv2() * 1.5f),
+						pos.getY() - (int) (controller.getScaleDiv2() * 1.5f), (int) (controller.getScale() * 1.5f),
+						(int) (controller.getScale() * 1.5f));
+			}
+
+		}
+		// maybeReplace:
+		if (mayBeReplaced != null) {
+			g2d.setColor(Color.RED);
+			Vector2Int pos = mayBeReplaced.getPosition();
+			g.drawImage(ImageImport.loadImage("/Images/replace.png"), pos.getX() + controller.getScaleDiv2(),
+					pos.getY() - controller.getScale(), controller.getScaleDiv2(), controller.getScaleDiv2(), null);
+		}
+		// <-- OldCode
+	}
+
+	@Override
+	public void mousePressed(MouseEvent e) {
+		this.grabFocus();
+		if (!disabled) {
+			tempCps = null;
+			dataSelected = null;
+			edgeHighlight = null;
+			controller.setSelecteEdge(null);
+			controller.setSelectedObjectID(-1);
+			// Object Selection
+
+			if (e.getX() > 0) {
+				for (AbstractCanvasObject cps : groupNode.getNodes()) {
+					cx = cps.getPosition().getX() - model.getScaleDiv2();
+					cy = cps.getPosition().getY() - model.getScaleDiv2();
+					if (x - controller.getScale() <= cx && y - controller.getScale() <= cy && x >= cx && y >= cy) {
+						tempCps = cps;
+
+						dragging = true;
+						if (e.isControlDown() && tempCps != null) {
+							System.out.println("Add Remove Selection GROUPNODECANVAS");
+							if (model.getSelectedObjects().contains(tempCps)) {
+								controller.removeObjectFromSelection(tempCps);
+							} else {
+								controller.addSelectedObject(tempCps);
+								if (tempCps instanceof GroupNode)
+									controller.getObjectsInDepth();
+							}
+						}
+
+						// 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 (Edge ed : groupNode.getConnections()) {
+					AbstractCanvasObject cps;
+					if (ed.getA().equals(this.groupNode)) {
+						cps = ed.getB();
+					} else {
+						cps = ed.getA();
+					}
+					if (x - controller.getScale() <= (model.getScaleDiv2())
+							&& y - controller.getScale() <= (scalediv20 + 5
+									+ (model.getScale() + scalediv20 + 10) * count)
+							&& x >= model.getScaleDiv2()
+							&& y >= (scalediv20 + 5 + (model.getScale() + scalediv20 + 10) * count)) {
+						tempCps = cps;
+						// If drawing an Edge (CTRL down)
+						if (tempCps.getClass() == HolonObject.class) {
+							HolonObject tempObj = ((HolonObject) tempCps);
+							dataSelected = tempObj.getElements();
+						}
+						if (e.isShiftDown()) {
+							drawEdge = true;
+						}
+					}
+					count++;
+				}
+			}
+			// 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) {
+						controller.clearSelection();
+					}
+				}
+
+				if (edgeHighlight == null && tempCps == null) {
+					sx = e.getX();
+					sy = e.getY();
+					doMark = true;
+				}
+				repaint();
+			}
+		}
+	}
+
+	@Override
+	public void mouseReleased(MouseEvent e) {
+		if (!disabled) {
+			x = e.getX();
+			y = e.getY();
+			dragging = false;
+
+			if (drawEdge) {
+				drawEdge = false;
+				drawDeleteEdge();
+			}
+
+			if (dragged) {
+				try {
+					/**
+					 * Save State before performing NodePlacement, replacement e.g.
+					 */
+					controller.autoSave();
+				} catch (IOException ex) {
+					ex.printStackTrace();
+				}
+
+				/**
+				 * check if tempCps could replace an Object on the UpperNodeanvas
+				 */
+				if (model.getSelectedObjects().size() == 1 && checkForReplacement(groupNode.getNodes(), tempCps,
+						tempCps.getPosition().getX(), tempCps.getPosition().getY())) {
+					/**
+					 * if UpperNode would be replaced, close its tabs
+					 */
+					if (mayBeReplaced instanceof GroupNode)
+						closeUpperNodeTab(mayBeReplaced.getId());
+					/**
+					 * replace on canvas
+					 */
+					controller.replaceObjUpperNode(mayBeReplaced, tempCps, groupNode);
+					mayBeReplaced = null;
+				}
+			}
+
+			if (!e.isControlDown() && !dragged && tempCps != null && MouseEvent.BUTTON3 != e.getButton()) {
+				controller.clearSelection();
+				controller.addSelectedObject(tempCps);
+				if (tempCps instanceof GroupNode)
+					controller.getObjectsInDepth();
+			}
+
+			dragged = false;
+
+			// Rightclick List
+			setRightClickMenu(e);
+
+			markObjects();
+			boolean doubleclick = doubleClick();  
+			if (doubleclick && tempCps != null && tempCps instanceof HolonSwitch) {
+				((HolonSwitch) tempCps).switchState();
+			}
+			if (doubleclick && tempCps != null && tempCps instanceof GroupNode) {
+				controller.getGui().openNewUpperNodeTab((GroupNode)tempCps);
+			}
+			controller.calculateStateAndVisualForTimeStep(model.getCurrentIteration());
+			repaint();
+		}
+	}
+
+	@Override
+	public void mouseDragged(MouseEvent e) {
+		if (!disabled) {
+			// If Edge is drawn
+			x = e.getX();
+			y = e.getY();
+			if (!model.getSelectedObjects().contains(tempCps) && !doMark) {
+				controller.clearSelection();
+				if (tempCps != null) {
+					controller.addSelectedObject(tempCps);
+				}
+			}
+			if (dragging) {
+				try {
+					// tempCps in the upperNode? else its a connected Object from
+					// outside
+					if (groupNode.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() +  + 5)
+							x = controller.getScaleDiv2() +  + 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().getX();
+						yDist = y - tempCps.getPosition().getY();
+
+						tempCps.setPosition(x, y); // Drag Position
+
+						// TipText Position and name
+						toolTip = true;
+						toolTipText = tempCps.getName() + ", " + tempCps.getId();
+						toolTipPos.setX(tempCps.getPosition().getX() - model.getScaleDiv2());
+						toolTipPos.setY(tempCps.getPosition().getY() - model.getScaleDiv2());
+
+						// All Selected Objects
+						for (AbstractCanvasObject cps : model.getSelectedObjects()) {
+							if (cps != tempCps) {
+								x = (int) (cps.getPosition().getX() + xDist);
+								y = (int) (cps.getPosition().getY() + yDist);
+
+								// Make sure its in bounds
+								if (x <  + 5 + controller.getScaleDiv2())
+									x = controller.getScaleDiv2() +  + 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);
+							}
+						}
+					}
+					/**
+					 * check if something would be replaced
+					 */
+					if (model.getSelectedObjects().size() == 1)
+						checkForReplacement(groupNode.getNodes(), tempCps, x, y);
+
+					repaint();
+				} catch (Exception eex) {
+
+				}
+
+			}
+
+			// Mark Objects
+			if (doMark) {
+				tempSelected.clear();
+				for (AbstractCanvasObject cps : groupNode.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().getX() + model.getScaleDiv2()
+							&& y1 <= cps.getPosition().getY() + model.getScaleDiv2() && x2 >= cps.getPosition().getX()
+							&& y2 >= cps.getPosition().getY()) {
+						tempSelected.add(cps);
+
+					}
+				}
+				int count = 0;
+				for (Edge ed : groupNode.getConnections()) {
+					AbstractCanvasObject cps;
+					if (ed.getA().equals(groupNode)) {
+						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 <= 0
+							&& y1 <= (int) (5 + (model.getScale() + scalediv20 + 10) * count) + model.getScaleDiv2()
+							&& x2 >=  0
+							&& 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 (AbstractCanvasObject cps : groupNode.getNodes()) {
+
+				cx = cps.getPosition().getX() - controller.getScaleDiv2();
+				cy = cps.getPosition().getY() - controller.getScaleDiv2();
+
+				on = setToolTipInfoAndPosition(on, cps);
+			}
+			int count = 0;
+			for (Edge ed : groupNode.getConnections()) {
+
+				AbstractCanvasObject cps;
+				if (ed.getA().equals(this.groupNode)) {
+					cps = ed.getB();
+				} else {
+					cps = ed.getA();
+				}
+
+				cx = 0 ;
+				cy = (int) (scalediv20 + 5 + (50 + scalediv20 + 10) * count);
+				if (x - 50 <= cx && y - 50 <= cy && x >= cx && y >= cy) {
+
+					on = true;
+					toolTipPos.setX(cx - 25);
+					toolTipPos.setY(cy + 50);
+					toolTipText = cps.getName() + ", " + cps.getId();
+
+				}
+				count++;
+			}
+
+			toolTip = on;
+			repaint();
+		}
+	}
+}

+ 2 - 7
src/ui/view/ButtonTabComponent.java → src/ui/view/component/ButtonTabComponent.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.component;
 
 /*
  * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
@@ -42,16 +42,14 @@ import java.awt.event.*;
  */
 public class ButtonTabComponent extends JPanel {
 	private final JTabbedPane pane;
-	private final JTabbedPane pane2;
 
-	public ButtonTabComponent(final JTabbedPane pane, final JTabbedPane pane2) {
+	public ButtonTabComponent(final JTabbedPane pane) {
 		// unset default FlowLayout' gaps
 		super(new FlowLayout(FlowLayout.LEFT, 0, 0));
 		if (pane == null) {
 			throw new NullPointerException("TabbedPane is null");
 		}
 		this.pane = pane;
-		this.pane2 = pane2;
 		setOpaque(false);
 
 		// make JLabel read titles from JTabbedPane
@@ -149,9 +147,6 @@ public class ButtonTabComponent extends JPanel {
 		int i = pane.indexOfTabComponent(ButtonTabComponent.this);
 		if (i != -1) {
 			pane.remove(i);
-			if (pane2.getTabCount() > 0) {
-				pane2.remove(i);
-			}
 		}
 	}
 }

+ 1 - 1
src/ui/view/Console.java → src/ui/view/component/Console.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.component;
 
 import java.awt.BorderLayout;
 

+ 95 - 0
src/ui/view/component/TrippleCheckBox.java

@@ -0,0 +1,95 @@
+package ui.view.component;
+
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Graphics;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+import javax.swing.Icon;
+import javax.swing.JCheckBox;
+import javax.swing.UIManager;
+
+public class TrippleCheckBox extends JCheckBox implements Icon, ActionListener {
+
+	public enum State {
+		unselected, mid_state_selection, selected
+	};
+
+	State state;
+	final static Icon icon = UIManager.getIcon("CheckBox.icon");
+
+	public TrippleCheckBox() {
+		this("", State.unselected);
+	}
+
+	public TrippleCheckBox(String text) {
+		this(text, State.unselected);
+	}
+
+	public TrippleCheckBox(String text, State selection) {
+		super(text, selection == State.selected);
+		setSelectionState(selection);
+		addActionListener(this);
+		setIcon(this);
+	}
+
+	@Override
+	public boolean isSelected() {
+		return (getSelectionState() == State.selected);
+	}
+
+	public State getSelectionState() {
+		return state;
+	}
+
+	public void setSelectionState(State selection) {
+		state = selection;
+		setSelected(state == State.selected);
+		repaint();
+	}
+
+
+	@Override
+	public void paintIcon(Component c, Graphics g, int x, int y) {
+		icon.paintIcon(c, g, x, y);
+		if (getSelectionState() != State.mid_state_selection)
+			return;
+
+		int w = getIconWidth();
+		int h = getIconHeight();
+		g.setColor(Color.white);
+		g.fillRect(x + 1, y + 1, w - 2, h - 2);
+		g.setColor(c.isEnabled() ? new Color(51, 51, 51) : new Color(122, 138, 153));
+		g.fillRect(x + 4, y + 4, w - 8, h - 8);
+
+		if (!c.isEnabled())
+			return;
+		g.setColor(new Color(81, 81, 81));
+		g.drawRect(x + 4, y + 4, w - 9, h - 9);
+	}
+
+	@Override
+	public int getIconWidth() {
+		return icon.getIconWidth();
+	}
+
+	@Override
+	public int getIconHeight() {
+		return icon.getIconHeight();
+	}
+
+	public void actionPerformed(ActionEvent e) {
+		switch (getSelectionState()) {
+		case unselected:
+			setSelectionState(State.selected);
+			break;
+		case mid_state_selection:
+			setSelectionState(State.unselected);
+			break;
+		case selected:
+			setSelectionState(State.unselected);
+			break;
+		}
+	}
+}

+ 1 - 1
src/ui/view/AboutUsPopUp.java → src/ui/view/dialog/AboutUsPopUp.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.dialog;
 
 import javax.swing.*;
 

+ 19 - 26
src/ui/view/AddElementPopUp.java → src/ui/view/dialog/AddElementPopUp.java

@@ -1,16 +1,24 @@
-package ui.view;
+package ui.view.dialog;
 
-import classes.AbstractCanvasObject;
-import classes.HolonElement;
-import classes.HolonObject;
-import utility.ImageImport;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.event.KeyEvent;
+import java.awt.event.KeyListener;
 
-import javax.swing.*;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
 import javax.swing.border.EmptyBorder;
 
-import java.awt.*;
-import java.awt.event.KeyEvent;
-import java.awt.event.KeyListener;
+import classes.HolonElement;
+import classes.HolonObject;
+import utility.ImageImport;
 
 /**
  * popup for adding an Holon Element to a holon Object.
@@ -39,8 +47,6 @@ public class AddElementPopUp extends JDialog {
 	private JTextField providedEnergy;
 	/** Element is active if checked */
 	JCheckBox checkBoxActive;
-	/** Textfield to enter the amount of this Element */
-	private JTextField amount;
 
 	/**
 	 * Create the AddElementPopup Dialog
@@ -98,17 +104,7 @@ public class AddElementPopUp extends JDialog {
 		checkBoxActive.setSelected(true);
 		checkBoxActive.setBounds(250, 50, 115, 20);
 		contentPanel.add(checkBoxActive);
-		
-		/* Add Amount Textfield and Checkbox */
-		JLabel lblAmount = new JLabel("Amount:");
-		lblAmount.setBounds(10, 130, 100, 14);
-		contentPanel.add(lblAmount);
 
-		amount = new JTextField();
-		amount.setBounds(130, 130, 110, 20);
-		contentPanel.add(amount);
-		amount.setColumns(10);
-		amount.setText("1");
 
 		/* Add Buttons and Actions */
 		JPanel buttonPane = new JPanel();
@@ -153,8 +149,7 @@ public class AddElementPopUp extends JDialog {
 	public void setElement(HolonElement holonElement) {
 		hl = holonElement;
 		elementName.setText(hl.getEleName());
-		amount.setText(""+hl.getAmount());
-		providedEnergy.setText(""+hl.getEnergyPerElement());
+		providedEnergy.setText(""+hl.getEnergy());
 		checkBoxActive.setSelected(hl.isActive());
 		
 	}
@@ -173,12 +168,10 @@ public class AddElementPopUp extends JDialog {
 		if (elementName.getText().length() != 0 && !repeated) {
 			try {
 				float energy = Float.parseFloat(providedEnergy.getText());
-				int elementAmount = Integer.parseInt(amount.getText());
 				if(hl == null){
-					hl = new HolonElement(this.tempCps, elementName.getText(), elementAmount, energy);
+					hl = new HolonElement(this.tempCps, elementName.getText(), energy);
 				} else {
 					hl.setEleName(elementName.getText());
-					hl.setAmount(elementAmount);
 					hl.setEnergyPerElement(energy);
 					hl.setActive(checkBoxActive.isSelected());
 				}

+ 22 - 37
src/ui/view/AddObjectPopUp.java → src/ui/view/dialog/AddObjectPopUp.java

@@ -1,9 +1,8 @@
-package ui.view;
+package ui.view.dialog;
 
 import java.awt.BorderLayout;
 import java.awt.Color;
 import java.awt.FlowLayout;
-import java.awt.Image;
 import java.awt.event.KeyEvent;
 import java.awt.event.KeyListener;
 import java.awt.event.MouseAdapter;
@@ -53,7 +52,7 @@ public class AddObjectPopUp extends JDialog {
 	private DefaultListModel<String> listModel;
 	private JList<String> list;
 	private String imagePath;
-	//	private HolonObject theObject;
+	// private HolonObject theObject;
 	private Control controller;
 	private File selectedFile = null;
 	private String filePath = " ";
@@ -63,25 +62,21 @@ public class AddObjectPopUp extends JDialog {
 	private boolean editState;
 	private boolean imageChanged = false;
 
-
 	/**
 	 * Create the dialog.
 	 * 
-	 * @param edit
-	 *            true if edit
-	 * @param obj
-	 *            the object
-	 * @param cat
-	 *            the categorie
+	 * @param edit true if edit
+	 * @param obj  the object
+	 * @param cat  the categorie
 	 */
-    AddObjectPopUp(boolean edit, AbstractCanvasObject obj, String cat, JFrame parentFrame) {
+	public AddObjectPopUp(boolean edit, AbstractCanvasObject obj, String cat, JFrame parentFrame) {
 
-        toEdit = obj;
+		toEdit = obj;
 		editState = edit;
-		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png",30,30));
+		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png", 30, 30));
 		setBounds(100, 100, 450, 342);
-        setLocationRelativeTo(parentFrame);
-        getContentPane().setLayout(new BorderLayout());
+		setLocationRelativeTo(parentFrame);
+		getContentPane().setLayout(new BorderLayout());
 		JPanel contentPanel = new JPanel();
 		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
 		getContentPane().add(contentPanel, BorderLayout.CENTER);
@@ -155,19 +150,19 @@ public class AddObjectPopUp extends JDialog {
 				lblImagePreview.setIcon(new ImageIcon(ImageImport.loadImage(obj.getImage(), 50, 50)));
 			}
 			sourcePath.setBounds(148, 77, 271, 20);
-			if(edit) {
+			if (edit) {
 				this.filePath = obj.getImage();
 				sourcePath.setText(filePath);
 			}
 			contentPanel.add(sourcePath);
-			
+
 			sourcePath.setColumns(10);
 		}
 		{
 			JButton btnAddDefaultElement = new JButton("Add Element");
 			btnAddDefaultElement.addActionListener(actionEvent -> {
-                addElement = new AddElementPopUp(parentFrame);
-                addElement.setActualHolonObject((HolonObject)toEdit);
+				addElement = new AddElementPopUp(parentFrame);
+				addElement.setActualHolonObject((HolonObject) toEdit);
 				addElement.setVisible(true);
 				HolonElement hl = addElement.getElement();
 				hl.setSaving(new Pair<>(givenCategory, objectName.getText()));
@@ -190,9 +185,9 @@ public class AddObjectPopUp extends JDialog {
 				listModel = new DefaultListModel<String>();
 
 				/*
-				 * HolonElement hel = new HolonElement("Test", 100, 5); String
-				 * name = hel.getEleName(); for (int i = 0; i < 11; i++) {
-				 * hel.setEleName(name + i); addElement(hel); }
+				 * HolonElement hel = new HolonElement("Test", 100, 5); String name =
+				 * hel.getEleName(); for (int i = 0; i < 11; i++) { hel.setEleName(name + i);
+				 * addElement(hel); }
 				 */
 				list = new JList<String>(listModel);
 				scrollPane.setViewportView(list);
@@ -231,10 +226,6 @@ public class AddObjectPopUp extends JDialog {
 								if (imageChanged)
 									copieFile();
 								imageChanged = false;
-								// theObject = new
-								// HolonObject(objectName.getText());
-								// theObject.setElements(hElements);
-								// theObject.setImage(imagePath);// TODO Auto-generated catch block
 								try {
 									if (editState) {
 										controller.delObjectCategory(givenCategory, toEdit.getName());
@@ -280,16 +271,14 @@ public class AddObjectPopUp extends JDialog {
 		}
 	}
 
-
 	/**
 	 * adds a Holon Element.
 	 *
-	 * @param hl
-	 *            the HolonElement
+	 * @param hl the HolonElement
 	 */
 	private void addElement(HolonElement hl) {
 		hElements.add(hl);
-		listModel.addElement(hl.getAmount() + "x: " + hl.getEleName() + " " + hl.getEnergyPerElement() + "U");
+		listModel.addElement("x: " + hl.getEleName() + " " + hl.getEnergy() + "U");
 	}
 
 	/**
@@ -304,9 +293,7 @@ public class AddObjectPopUp extends JDialog {
 			selectedFile = fileChooser.getSelectedFile();
 			filePath = selectedFile.getAbsolutePath();
 			sourcePath.setText(filePath);
-			ImageIcon icon = new ImageIcon(//TODO: ugly
-					
-					new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
+			ImageIcon icon = new ImageIcon(ImageImport.loadImage(filePath, 50, 50));
 			lblImagePreview.setIcon(icon);
 			imageChanged = true;
 		} else {
@@ -367,8 +354,7 @@ public class AddObjectPopUp extends JDialog {
 	/**
 	 * Sets the Controller.
 	 * 
-	 * @param controller
-	 *            the controller
+	 * @param controller the controller
 	 */
 	public void setController(Control controller) {
 		this.controller = controller;
@@ -377,8 +363,7 @@ public class AddObjectPopUp extends JDialog {
 	/**
 	 * Set the Category.
 	 * 
-	 * @param cat
-	 *            the Category
+	 * @param cat the Category
 	 */
 	public void setCategory(String cat) {
 		givenCategory = cat;

+ 8 - 3
src/ui/view/BackgroundPopUp.java → src/ui/view/dialog/BackgroundPopUp.java

@@ -1,13 +1,18 @@
-package ui.view;
+package ui.view.dialog;
 
 import classes.GroupNode;
 import ui.controller.Control;
 import ui.model.Model;
+import ui.view.canvas.Canvas;
 import utility.ImageImport;
 
 import javax.swing.*;
 import javax.swing.filechooser.FileNameExtensionFilter;
-import java.awt.*;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.GridLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.awt.event.ComponentAdapter;
@@ -48,7 +53,7 @@ public class BackgroundPopUp extends JDialog {
     private boolean imageBtnClearedPressed = false;
     private int mode = 0;
 
-    public BackgroundPopUp(Model model, Control controller, MyCanvas canvas, GroupNode uNode, JFrame parentFrame) {
+    public BackgroundPopUp(Model model, Control controller, Canvas canvas, GroupNode uNode, JFrame parentFrame) {
         super((java.awt.Frame) null, true);
 		getContentPane().setBackground(Color.WHITE);
 		this.setTitle("Set View Background");

+ 25 - 19
src/ui/view/CanvasResizePopUp.java → src/ui/view/dialog/CanvasResizePopUp.java

@@ -1,8 +1,11 @@
-package ui.view;
+package ui.view.dialog;
 
 import ui.controller.Control;
 import ui.model.Model;
+import ui.view.canvas.Canvas;
+import ui.view.canvas.GroupNodeCanvas;
 import utility.ImageImport;
+import utility.Vector2Int;
 
 import javax.swing.*;
 import java.awt.*;
@@ -13,10 +16,9 @@ public class CanvasResizePopUp extends JDialog {
     private final JButton btnOk = new JButton("OK");
 	private final JButton btnCancel = new JButton("Cancel");
 	JTabbedPane tabbedPane;
-	JTabbedPane tabbedPane2;
 	Model model;
 	Control controller;
-	MyCanvas canvas;
+	Canvas canvas;
     private JPanel mainPanel = new JPanel();
     private JTextField tFieldWidht = new JTextField();
     private JTextField tFieldHeight = new JTextField();
@@ -24,11 +26,9 @@ public class CanvasResizePopUp extends JDialog {
     private JLabel lblHeight = new JLabel("Height:");
     private JPanel buttonPanel = new JPanel();
 
-	public CanvasResizePopUp(Model model, Control controller, MyCanvas canvas, JTabbedPane tabbedPane,
-                             JTabbedPane tabbedPane2, JFrame parentFrame) {
+	public CanvasResizePopUp(Model model, Control controller, Canvas canvas, JTabbedPane tabbedPane, JFrame parentFrame) {
         super((java.awt.Frame) null, true);
 		this.tabbedPane = tabbedPane;
-		this.tabbedPane2 = tabbedPane2;
 		this.model = model;
 		this.controller = controller;
 		this.canvas = canvas;
@@ -43,9 +43,9 @@ public class CanvasResizePopUp extends JDialog {
 		tFieldWidht.setText("" + model.getCanvasX());
 		tFieldHeight.setText("" + model.getCanvasY());
 		mainPanel.add(lblWidth);
-		mainPanel.add(tFieldHeight);
-		mainPanel.add(lblHeight);
 		mainPanel.add(tFieldWidht);
+		mainPanel.add(lblHeight);
+		mainPanel.add(tFieldHeight);
 		mainPanel.setBackground(Color.WHITE);
 
 		// Button Panel
@@ -54,22 +54,28 @@ public class CanvasResizePopUp extends JDialog {
 			public void actionPerformed(ActionEvent e) {
 				controller.setCanvasX(Integer.parseInt(tFieldWidht.getText()));
 				controller.setCanvasY(Integer.parseInt(tFieldHeight.getText()));
-				canvas.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
-				for (int i = 4; i < tabbedPane.getTabCount(); i++) {
+				int width = model.getCanvasX();
+				int height = model.getCanvasY();
+				Dimension preferedSize = new Dimension(width, height);
+				canvas.setPreferredSize(new Dimension(preferedSize));
+				for (int i = 1; i < tabbedPane.getTabCount(); i++) {
 					if (tabbedPane.getComponentAt(i) != null) {
-						GroupNodeCanvas unc = ((GroupNodeCanvas) ((JScrollPane) tabbedPane.getComponentAt(i))
+						JScrollPane scollPane = (JScrollPane) tabbedPane.getComponentAt(i);
+						GroupNodeCanvas groupNodeCanvas = ((GroupNodeCanvas) (scollPane)
 								.getViewport().getComponent(0));
-						unc.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
-						unc.repaint();
+						groupNodeCanvas.setPreferredSize(new Dimension(preferedSize));
+						groupNodeCanvas.repaint();
 					}
 				}
-				if (tabbedPane2 != null && tabbedPane2.getSelectedIndex() >= 4) {
-					GroupNodeCanvas unc = ((GroupNodeCanvas) ((JScrollPane) tabbedPane2.getSelectedComponent())
-							.getViewport().getComponent(0));
-					unc.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
-					unc.repaint();
-				}
+				canvas.revalidate();
 				canvas.repaint();
+				
+				controller.getModel().getAllAbstractObjectsOnCanvas().stream().forEach(obj -> {
+					Vector2Int position = obj.getPosition();
+					position.clampX(0, width);
+					position.clampY(0, height);
+				});
+				controller.updateCanvas();
 				dispose();
 			}
 		});

+ 4 - 6
src/ui/view/CreateNewDialog.java → src/ui/view/dialog/CreateNewDialog.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.dialog;
 
 import java.awt.BorderLayout;
 import java.awt.CardLayout;
@@ -39,13 +39,12 @@ public class CreateNewDialog extends JDialog{
 	JComboBox<String> optionList = new JComboBox<String>(optionStrings);
 	JTextField inputName = new JTextField();
 	JButton saveButton = new JButton("Save");
-	//TODO
 	JTextField inputNameSwitch = new JTextField();
 	JComboBox<String> selectedCategorySwitch = new JComboBox<String>();
 	
 	
 	
-	CreateNewDialog(Control controller, JFrame parentFrame){
+	public CreateNewDialog(Control controller, JFrame parentFrame){
 		super((JFrame)parentFrame, "Create a..");
 		actualController = controller;
 		setVisible(true);
@@ -64,7 +63,6 @@ public class CreateNewDialog extends JDialog{
 			actualOption = Option.getEnumAtIndex(optionList.getSelectedIndex());
 		    cl.show(cards, actualOption.name());
 		    saveButton.setEnabled(actualOption != Option.None);  
-		    //TODO delete and make own iterface
 		    saveButton.setVisible(actualOption != Option.Object);	
 		});
 		
@@ -79,7 +77,7 @@ public class CreateNewDialog extends JDialog{
 	}
 
 
-	CreateNewDialog(Control controller, Option aOption, JFrame parentFrame){
+	public CreateNewDialog(Control controller, Option aOption, JFrame parentFrame){
 		super((JFrame)parentFrame, "Create a " + aOption.name());
 		actualController = controller;
 		if(aOption == Option.None)
@@ -239,7 +237,7 @@ public class CreateNewDialog extends JDialog{
 				dispose();
 			}
 			else if (actualOption == Option.Switch)
-			{//TODO
+			{
 				try {
 					actualController.addSwitch(actualController.searchCategory(selectedCategorySwitch.getSelectedItem().toString()), inputNameSwitch.getText());
 				} catch (IOException e) {

+ 9 - 9
src/ui/view/CreateTemplatePopUp.java → src/ui/view/dialog/CreateTemplatePopUp.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.dialog;
 
 import java.awt.BorderLayout;
 import java.awt.Choice;
@@ -210,8 +210,8 @@ public class CreateTemplatePopUp extends JDialog {
 		 * Add Elements to List
 		 */
 		for (HolonElement he : template.getElements())
-			listModel.addElement(he.getAmount() + " * " + he.getEleName()
-					+ ": " + he.getMaximumEnergy() + "U");
+			listModel.addElement(he.getEleName()
+					+ ": " + he.getEnergy() + "U");
 
 		/**
 		 * Add ScrollPane to List
@@ -321,8 +321,8 @@ public class CreateTemplatePopUp extends JDialog {
 		popUp.setVisible(true);
 		HolonElement he = popUp.getElement();
 		if (he != null) {
-			listModel.addElement(he.getAmount() + " * " + he.getEleName()
-					+ ": " + he.getMaximumEnergy() + "U");
+			listModel.addElement(he.getEleName()
+					+ ": " + he.getEnergy() + "U");
 			template.addElement(he);
 			he.setSaving(new Pair<>(category, textField_name.getText()));
 		}
@@ -335,7 +335,7 @@ public class CreateTemplatePopUp extends JDialog {
 		int index = list.getSelectedIndex();
 		if (index == -1)
 			return;
-		template.deleteElement(index);
+		template.removeElement(index);
 		listModel.remove(index);
 	}
 
@@ -354,9 +354,9 @@ public class CreateTemplatePopUp extends JDialog {
 		HolonElement he = popUp.getElement();
 		if (he != null) {
 			listModel.remove(index);
-			listModel.addElement(he.getAmount() + " * " + he.getEleName()
-					+ ": " + he.getMaximumEnergy() + "U");
-			template.deleteElement(index);
+			listModel.addElement(he.getEleName()
+					+ ": " + he.getEnergy() + "U");
+			template.removeElement(index);
 			template.addElement(he);
 			he.setSaving(new Pair<>(category, textField_name.getText()));
 		}

+ 4 - 3
src/ui/view/EditEdgesPopUp.java → src/ui/view/dialog/EditEdgesPopUp.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.dialog;
 
 import java.awt.BorderLayout;
 import java.awt.Font;
@@ -18,6 +18,7 @@ import javax.swing.border.EmptyBorder;
 
 import classes.Edge;
 import ui.controller.Control;
+import ui.view.canvas.Canvas;
 
 /**
  * Popup for Editing Edges.
@@ -34,7 +35,7 @@ public class EditEdgesPopUp extends JDialog {
 	private JRadioButton rdbtnChangeForNew;
 	private JRadioButton rdbtnChangeForAll1;
 	private Control controller;
-	private MyCanvas canvas;
+	private Canvas canvas;
 
 	/**
 	 * Launch the application.
@@ -130,7 +131,7 @@ public class EditEdgesPopUp extends JDialog {
 	 * @param can
 	 *            the Canvas
 	 */
-	public void setCanvas(MyCanvas can) {
+	public void setCanvas(Canvas can) {
 		canvas = can;
 	}
 

+ 34 - 28
src/ui/view/SearchPopUp.java → src/ui/view/dialog/SearchPopUp.java

@@ -1,14 +1,23 @@
-package ui.view;
+package ui.view.dialog;
 
-import classes.AbstractCanvasObject;
-import ui.controller.Control;
-
-import javax.swing.*;
-import javax.swing.border.EmptyBorder;
-import java.awt.*;
+import java.awt.BorderLayout;
+import java.awt.Font;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
-import java.util.ArrayList;
+
+import javax.swing.ButtonGroup;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JRadioButton;
+import javax.swing.JTextField;
+import javax.swing.border.EmptyBorder;
+
+import classes.AbstractCanvasObject;
+import ui.controller.Control;
+import ui.view.canvas.Canvas;
 
 /**
  * This Class represents a popup to seatch for Objects on the Canvas.
@@ -22,7 +31,7 @@ public class SearchPopUp extends JDialog {
 	private JTextField replaceTextField;
 	private JTextField findTextField;
 	private Control controller;
-	private MyCanvas canvas;
+	private Canvas canvas;
 	private JRadioButton rdbtnForward;
 	private JRadioButton rdbtnBackward;
 	private JRadioButton rdbtnAll;
@@ -37,7 +46,7 @@ public class SearchPopUp extends JDialog {
 	 * @param can
 	 *            Canvas
 	 */
-    SearchPopUp(Control contr, MyCanvas can, JFrame parentFrame) {
+    public SearchPopUp(Control contr, Canvas can, JFrame parentFrame) {
         super((java.awt.Frame) null, true);
 		idx = -1;
 		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
@@ -114,24 +123,24 @@ public class SearchPopUp extends JDialog {
 					for (AbstractCanvasObject cps : controller.getModel().getObjectsOnCanvas()) {
 
 						if (cps.getName().equals(findTextField.getText())
-								&& !controller.getModel().getSelectedCpsObjects().contains(cps)) {
-							controller.getModel().getSelectedCpsObjects().add(cps);
+								&& !controller.getModel().getSelectedObjects().contains(cps)) {
+							controller.getModel().getSelectedObjects().add(cps);
 						}
 
 					}
 
 				}
 				if (rdbtnSingle.isSelected()) {
-					controller.getModel().getSelectedCpsObjects().clear();
+					controller.getModel().getSelectedObjects().clear();
 
 					if (!controller.getModel().getObjectsOnCanvas().isEmpty() && !findTextField.getText().isEmpty()) {
 
 						if (rdbtnForward.isSelected()) {
 							if ((idx = getNext(++idx)) != -1)
-								controller.getModel().getSelectedCpsObjects().add(getObj(idx));
+								controller.getModel().getSelectedObjects().add(getObj(idx));
 						} else if (rdbtnBackward.isSelected()) {
 							if ((idx = getPrev(--idx)) != -1)
-								controller.getModel().getSelectedCpsObjects().add(getObj(idx));
+								controller.getModel().getSelectedObjects().add(getObj(idx));
 						}
 					}
 
@@ -148,10 +157,8 @@ public class SearchPopUp extends JDialog {
 		JButton btnReplace = new JButton("Replace");
 		btnReplace.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
-
-				if (controller.getModel().getSelectedCpsObjects().size() == 1 && controller.getModel()
-						.getSelectedCpsObjects().get(0).getName().equals(findTextField.getText()))
-					controller.getModel().getSelectedCpsObjects().get(0).setName(replaceTextField.getText());
+				//TODO fix or remove SearchPopUp
+				System.out.println("REPLACE");
 				canvas.repaint();
 			}
 		});
@@ -164,16 +171,15 @@ public class SearchPopUp extends JDialog {
 		btnReplaceAll.addActionListener(new ActionListener() {
 			public void actionPerformed(ActionEvent e) {
 				canvas.tempCps = null;
-				canvas.tempSelected = new ArrayList<>();
-				controller.getModel().getSelectedCpsObjects().clear();
+				controller.getModel().getSelectedObjects().clear();
 
 				for (AbstractCanvasObject cps : controller.getModel().getObjectsOnCanvas()) {
 					if (cps.getName().equals(findTextField.getText())
-							&& !controller.getModel().getSelectedCpsObjects().contains(cps))
+							&& !controller.getModel().getSelectedObjects().contains(cps))
 						selectObj(cps);
 				}
 
-				for (AbstractCanvasObject cps : controller.getModel().getSelectedCpsObjects()) {
+				for (AbstractCanvasObject cps : controller.getModel().getSelectedObjects()) {
 					renameObj(cps, replaceTextField.getText());
 				}
 
@@ -212,7 +218,7 @@ public class SearchPopUp extends JDialog {
 	 *            The Object
 	 */
 	public void selectObj(AbstractCanvasObject obj) {
-		controller.getModel().getSelectedCpsObjects().add(obj);
+		controller.getModel().getSelectedObjects().add(obj);
 	}
 
 	/**
@@ -248,12 +254,12 @@ public class SearchPopUp extends JDialog {
 	public int getNext(int idx) {
 		for (int i = idx; i < controller.getModel().getObjectsOnCanvas().size(); i++) {
 			if (getObj(i).getName().equals(findTextField.getText())
-					&& !controller.getModel().getSelectedCpsObjects().contains(getObj(i)))
+					&& !controller.getModel().getSelectedObjects().contains(getObj(i)))
 				return i;
 		}
 		for (int i = 0; i < idx; i++) {
 			if (getObj(i).getName().equals(findTextField.getText())
-					&& !controller.getModel().getSelectedCpsObjects().contains(getObj(i)))
+					&& !controller.getModel().getSelectedObjects().contains(getObj(i)))
 				return i;
 		}
 		return -1;
@@ -269,12 +275,12 @@ public class SearchPopUp extends JDialog {
 	public int getPrev(int idx) {
 		for (int i = idx; i >= 0; i--) {
 			if (getObj(i).getName().equals(findTextField.getText())
-					&& !controller.getModel().getSelectedCpsObjects().contains(getObj(i)))
+					&& !controller.getModel().getSelectedObjects().contains(getObj(i)))
 				return i;
 		}
 		for (int i = controller.getModel().getObjectsOnCanvas().size() - 1; i > idx; i--) {
 			if (getObj(i).getName().equals(findTextField.getText())
-					&& !controller.getModel().getSelectedCpsObjects().contains(getObj(i)))
+					&& !controller.getModel().getSelectedObjects().contains(getObj(i)))
 				return i;
 		}
 		return -1;

+ 165 - 0
src/ui/view/inspector/Inspector.java

@@ -0,0 +1,165 @@
+package ui.view.inspector;
+
+import java.awt.BorderLayout;
+import java.awt.Component;
+import java.awt.Dimension;
+import java.awt.event.ItemEvent;
+import java.util.List;
+import java.util.Set;
+
+import javax.swing.Box;
+import javax.swing.GrayFilter;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JComboBox;
+import javax.swing.JLabel;
+import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JScrollPane;
+import javax.swing.JSplitPane;
+import javax.swing.JToolBar;
+
+import classes.HolonElement;
+import classes.HolonSwitch;
+import interfaces.GraphEditable;
+import interfaces.TimelineDependent;
+import ui.controller.Control;
+import utility.ImageImport;
+
+public class Inspector extends JSplitPane {
+	private final UnitGraph unitGraph;
+	private final InspectorTable table;
+	private final Control control;
+	private final JScrollPane scrollGraph = new JScrollPane();
+	private final JPanel graphLabel = new JPanel();
+	private final JLabel maxGraph = new JLabel("100%");
+	private final JLabel medGraph = new JLabel("50%");
+	private final JLabel minGraph = new JLabel("0%");
+	private final JToolBar toolBarGraph = new JToolBar();
+	private String[] comboContext = { "", "5", "10", "20", "100", "1000" };
+	private JComboBox<String> localPeriodInput = new JComboBox<String>(comboContext);
+	private JButton resetButton = new JButton("", new ImageIcon(ImageImport.loadImage("/Images/resetIcon3.png")));
+	private final ImageIcon localPeriodButtonImageEnabled = new ImageIcon(ImageImport.loadImage("/Images/Graph.png"));
+
+	private final ImageIcon localPeriodButtonImageDisabled = new ImageIcon(
+			GrayFilter.createDisabledImage(ImageImport.loadImage("/Images/Graph.png")));
+	private JButton localPeriodButton = new JButton("", localPeriodButtonImageEnabled);
+
+	public Inspector(Control control) {
+		this.control = control;
+		table = new InspectorTable(control);
+		unitGraph = new UnitGraph(control);
+		table.OnElementSelectionChanged.addListener(this::updateUnitGraph);
+		initUI();
+
+	}
+
+	private void initUI() {
+		this.setOrientation(JSplitPane.VERTICAL_SPLIT);
+		JScrollPane scrollPane = new JScrollPane(table);
+		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
+		this.setTopComponent(scrollPane);
+		this.setBottomComponent(scrollGraph);
+		this.setDividerLocation(1000);
+		scrollGraph.setViewportView(unitGraph);
+		// Set up of the Properties section
+
+		graphLabel.setLayout(new BorderLayout(0, 10));
+		graphLabel.add(maxGraph, BorderLayout.NORTH);
+		graphLabel.add(medGraph, BorderLayout.CENTER);
+		graphLabel.add(minGraph, BorderLayout.SOUTH);
+
+		toolBarGraph.setFloatable(false);
+		toolBarGraph.setAlignmentY(Component.RIGHT_ALIGNMENT);
+
+		localPeriodButton.setToolTipText("Toggle Local/Global Mode");
+		toolBarGraph.add(localPeriodButton);
+		// ComboBox
+		localPeriodInput.setEditable(true);
+		localPeriodInput.setVisible(false);
+		localPeriodInput.setMaximumSize(new Dimension(20, 23));
+		localPeriodInput.addItemListener(aListener -> {
+			if (aListener.getStateChange() == ItemEvent.DESELECTED) {
+				validateInput(localPeriodInput.getEditor().getItem().toString(), true);
+			}
+
+		});
+
+		toolBarGraph.add(localPeriodInput);
+
+		// localPeriodButtonFunction
+		localPeriodButton.addActionListener(actionEvent -> {
+			boolean newState = !localPeriodInput.isVisible();
+			changeLocalPeriodButtonAppeareance(newState);
+			unitGraph.setUseLocalPeriod(newState);
+		});
+
+		toolBarGraph.add(Box.createHorizontalGlue());
+		resetButton.setToolTipText("Reset");
+		resetButton.addActionListener(actionEvent -> unitGraph.reset());
+		toolBarGraph.add(resetButton);
+		scrollGraph.setRowHeaderView(graphLabel);
+		scrollGraph.setColumnHeaderView(toolBarGraph);
+
+	}
+
+	/**
+	 * Validate the LocalMode Input and when its valid save on the Element.
+	 * 
+	 * @param text         the inputText to validate.
+	 * @param bShowMessage when true, open a MessageDialog when text invalid.
+	 */
+	private void validateInput(String text, boolean bShowMessage) {
+		int localPeriodInputValue;
+		try {
+			localPeriodInputValue = Integer.parseInt(text);
+		} catch (NumberFormatException e) {
+			if (bShowMessage)
+				JOptionPane.showMessageDialog(null, '"' + text + '"' + " is not a valid Input. \n Use whole numbers.");
+			return;
+		}
+		unitGraph.setLocalPeriod(localPeriodInputValue);
+	}
+
+	/**
+	 * This Method updates the UnitGraph, saves the old LocalModeState and load the
+	 * new LocalModeState.
+	 * 
+	 * @param element The new Element to load the UnitGraph
+	 */
+	private void updateUnitGraph(Set<HolonElement> elements) {
+		// SaveOld LocalMode State.
+		if (localPeriodInput.isVisible()) {
+			// Save Old State
+			validateInput(localPeriodInput.getEditor().getItem().toString(), false);
+		}
+		// Update UnitGraph
+		unitGraph.clearSeries();
+		for (TimelineDependent element : elements) {
+			unitGraph.addNewSeries(element);
+		}
+		
+		if(elements.isEmpty()) {
+			control.getModel().getSelectedObjects().stream().filter(obj -> obj instanceof HolonSwitch)
+			.forEach(obj -> unitGraph.addNewSeries((HolonSwitch) obj));			
+		}
+//		if (elements.isEmpty()) {
+//			this.setDividerLocation(1.0);
+//		}
+		// Load LocalMode State.
+		changeLocalPeriodButtonAppeareance(unitGraph.isUsingLocalPeriod());
+		localPeriodInput.getEditor()
+				.setItem(unitGraph.isLocalPeriedDifferentInSeries() ? "-" : unitGraph.getFirstLocalPeriod());
+	}
+
+	/**
+	 * Displayed the actual LocalModeState.
+	 * 
+	 * @param enabled
+	 */
+	private void changeLocalPeriodButtonAppeareance(boolean enabled) {
+		localPeriodInput.setVisible(enabled);
+		localPeriodButton.setIcon(enabled ? localPeriodButtonImageEnabled : localPeriodButtonImageDisabled);
+	}
+
+}

+ 348 - 0
src/ui/view/inspector/InspectorTable.java

@@ -0,0 +1,348 @@
+package ui.view.inspector;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Container;
+import java.awt.Dimension;
+import java.math.RoundingMode;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Optional;
+import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import javax.swing.BorderFactory;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.ImageIcon;
+import javax.swing.JButton;
+import javax.swing.JCheckBox;
+import javax.swing.JComboBox;
+import javax.swing.JFormattedTextField;
+import javax.swing.JLabel;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+import javax.swing.UIManager;
+import javax.swing.border.Border;
+import javax.swing.text.NumberFormatter;
+
+import classes.AbstractCanvasObject;
+import classes.HolonElement;
+import classes.HolonElement.Priority;
+import classes.HolonObject;
+import net.miginfocom.swing.MigLayout;
+import ui.controller.Control;
+import ui.view.component.TrippleCheckBox;
+import ui.view.component.TrippleCheckBox.State;
+import utility.ImageImport;
+import utility.events.Action;
+import utility.events.SimpleDocumentListener;
+
+public class InspectorTable extends JPanel {
+	private List<ElementRow> elementRows = new ArrayList<ElementRow>();
+	private Control control;
+	private final int columnHeight = 20;
+	//UI
+	private final TrippleCheckBox selectAllCheckBox = new TrippleCheckBox();
+	private final JButton addButton = new JButton();
+	private final JButton duplicateButton = new JButton();
+	private final JButton deleteButton = new JButton();
+	private final JPanel buttonPanel = new JPanel();
+	private final static NumberFormatter doubleFormatter = generateNumberFormatter();
+	
+	//Colors
+	private final static Color selectedColor = new Color(126, 186, 255);
+	private final static Color borderColor = new Color(171, 173, 179);
+	//Events
+	public Action<Set<HolonElement>> OnElementSelectionChanged = new Action<>(); 
+
+	public InspectorTable(Control control) {
+		control.OnSelectionChanged.addListener(() -> update_ui());
+		this.control = control;
+		init();
+		generateHeader();
+	}
+
+	private void init() {
+		MigLayout layout = new MigLayout("insets 0,gap 0,wrap 7", // Layout Constraints
+				"[][fill, grow][][fill, grow][fill, grow][][]", // Column constraints
+				"[25!][20:20:20]"); // Row constraints
+		this.setLayout(layout);
+		initSelectAllCheckBox();
+		initButtonPanel();
+	}
+	private static NumberFormatter generateNumberFormatter() {
+		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
+		doubleFormat.setMinimumFractionDigits(1);
+		doubleFormat.setMaximumFractionDigits(10);
+		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
+		doubleFormat.setGroupingUsed(false);
+		NumberFormatter doubleFormatter = new NumberFormatter(doubleFormat);
+		doubleFormatter.setCommitsOnValidEdit(true);
+		doubleFormatter.setValueClass(Double.class);
+		return doubleFormatter;
+	}
+
+	private void generateHeader() {
+
+		this.add(selectAllCheckBox);
+		this.add(generateHeaderColumnTitle("Object"));
+		this.add(generateHeaderColumnTitle("Id "));
+		this.add(generateHeaderColumnTitle("Device"));
+		this.add(generateHeaderColumnTitle("Energy"));
+		this.add(generateHeaderColumnTitle("Priority"));
+		this.add(generateHeaderColumnTitle("Activ"));
+	}
+
+	private void initSelectAllCheckBox() {
+		selectAllCheckBox.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
+		// Pixel Perfect alignment
+		selectAllCheckBox.setBorder(BorderFactory.createEmptyBorder(2, 3, 0, 0));
+		selectAllCheckBox.addActionListener(clicked -> {
+			switch (selectAllCheckBox.getSelectionState()) {
+			case mid_state_selection:
+			case selected: {
+				for (ElementRow row : elementRows) {
+					row.setSelected(false);
+				}
+				duplicateButton.setEnabled(false);
+				deleteButton.setEnabled(false);
+			}
+				break;
+			case unselected:
+				if(!elementRows.isEmpty()) {					
+					for (ElementRow row : elementRows) {
+						row.setSelected(true);
+					}
+					duplicateButton.setEnabled(true);
+					deleteButton.setEnabled(true);
+				}
+			default:
+				break;
+			}
+			updateElementSelection();
+		});
+	}
+	private JLabel generateHeaderColumnTitle(String string) {
+		JLabel columnTitleLabel = new JLabel(string);
+		columnTitleLabel.setToolTipText(string);
+		columnTitleLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
+		return columnTitleLabel;
+	}
+
+
+
+	private void initButtonPanel() {
+		buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
+		buttonPanel.add(Box.createRigidArea(new Dimension(2, 0)));
+
+		addButton.setIcon(new ImageIcon(ImageImport.loadImage("Images/plus.png", 16, 16)));
+		addButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
+		addButton.addActionListener(clicked -> {
+			Optional<HolonObject> last = control.getModel().getSelectedObjects().stream()
+					.filter(obj -> obj instanceof HolonObject).reduce((prev, next) -> next)
+					.map(obj -> (HolonObject) obj);
+			last.ifPresent(obj -> {
+				obj.addElement(new HolonElement(obj, "Element", 0.0f));
+				control.calculateStateAndVisualForCurrentTimeStep();
+				update_ui();
+			});
+		});
+		buttonPanel.add(addButton);
+
+		duplicateButton.setIcon(new ImageIcon(ImageImport.loadImage("Images/duplicate.png", 16, 16)));
+		duplicateButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
+		duplicateButton.addActionListener(clicked -> {
+			for (ElementRow row : elementRows) {
+				if(row.isSelected()) {
+					row.element.parentObject.addElement(new HolonElement(row.element));
+				}
+			}
+			control.calculateStateAndVisualForCurrentTimeStep();
+			update_ui();
+		});
+		buttonPanel.add(duplicateButton);
+
+		deleteButton.setIcon(new ImageIcon(ImageImport.loadImage("Images/minus.png", 16, 16)));
+		deleteButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
+		deleteButton.addActionListener(clicked -> {
+			for (ElementRow row : elementRows) {
+				if(row.isSelected()) {
+					row.element.parentObject.removeElement(row.element);
+				}
+			}
+			control.calculateStateAndVisualForCurrentTimeStep();
+			update_ui();
+		});
+		buttonPanel.add(deleteButton);
+	}
+
+	private void update_ui() {
+		Stream<HolonElement> elements = extractElements(control.getModel().getSelectedObjects());
+		// TODO Pooling
+		this.removeAll();
+		elementRows.clear();
+		generateHeader();
+		elements.forEach(element -> elementRows.add(new ElementRow(element)));
+		this.add(buttonPanel, "span");
+		boolean isAtLeastOneHolonObjectSelected = 
+				control.getModel().getSelectedObjects().stream().anyMatch(object -> object instanceof HolonObject);
+		this.addButton.setEnabled(isAtLeastOneHolonObjectSelected);
+		duplicateButton.setEnabled(false);
+		deleteButton.setEnabled(false);
+		selectAllCheckBox.setSelectionState(State.unselected);
+		revalidate();
+		repaint();
+		this.OnElementSelectionChanged.broadcast(new HashSet<HolonElement>());
+	}
+
+
+	private void updateElementSelection() {
+		Set<HolonElement> eleSet = elementRows.stream().filter(ele -> ele.isSelected()).map(row -> row.element).collect(Collectors.toSet());
+		this.OnElementSelectionChanged.broadcast(eleSet);
+	}
+
+	private void updateButtonAppearance() {
+		long count = elementRows.stream().filter(ele -> ele.isSelected()).count();
+		if (count == elementRows.size()) {
+			selectAllCheckBox.setSelectionState(State.selected);
+		} else if (count == 0) {
+			selectAllCheckBox.setSelectionState(State.unselected);
+		} else {
+			selectAllCheckBox.setSelectionState(State.mid_state_selection);
+		}
+		duplicateButton.setEnabled(count != 0);
+		deleteButton.setEnabled(count != 0);
+	}
+
+	// Extract elements from a list of AbstractCanvasObjects
+	private Stream<HolonElement> extractElements(Collection<AbstractCanvasObject> toInspect) {
+		return toInspect.stream().filter(obj -> obj instanceof HolonObject).flatMap(obj -> {
+			HolonObject ho = (HolonObject) obj;
+			return ho.getElements().stream();
+		});
+	}
+	
+	private class ElementRow {
+		HolonElement element;
+		private JCheckBox selectionBox;
+		Container[] cellsInRow = new Container[7];
+
+		ElementRow(HolonElement element) {
+			this.element = element;
+			this.createEditFields();
+			addContainerToInspector();
+		}
+
+		private void addContainerToInspector() {
+			for (Container cell : cellsInRow) {
+				InspectorTable.this.add(cell);
+			}
+		}
+
+		public void setSelected(boolean value) {
+			selectionBox.setSelected(value);
+			// Color row
+			for (Container cell : cellsInRow) {
+				cell.setBackground(selectionBox.isSelected() ? selectedColor : Color.white);
+			}
+		}
+
+		public boolean isSelected() {
+			return selectionBox.isSelected();
+		}
+
+		private void createEditFields() {
+			// Selected
+			JPanel selectedColumnPanel = new JPanel(new BorderLayout());
+			selectedColumnPanel.setBackground(Color.white);
+			selectedColumnPanel.setBorder(BorderFactory.createLineBorder(borderColor));
+			selectionBox = new JCheckBox();
+			selectionBox.addActionListener(clicked -> {
+				setSelected(selectionBox.isSelected());
+				updateButtonAppearance();
+				updateElementSelection();
+			});
+			selectedColumnPanel.setMinimumSize(new Dimension(columnHeight, columnHeight));
+			selectedColumnPanel.setPreferredSize(new Dimension(columnHeight, columnHeight));
+			selectedColumnPanel.setMaximumSize(new Dimension(columnHeight, columnHeight));
+			selectionBox.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0));
+			selectionBox.setOpaque(false);
+			selectedColumnPanel.add(selectionBox, BorderLayout.CENTER);
+			cellsInRow[0] = selectedColumnPanel;
+
+			// ObjectName and ID
+			JTextField objectNameTextField = new JTextField(this.element.parentObject.getName());
+			objectNameTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
+				this.element.parentObject.setName(objectNameTextField.getText());
+			});
+			objectNameTextField.addActionListener(ae -> update_ui());
+			cellsInRow[1] = objectNameTextField;
+			JTextField idObjectTextField = new JTextField(Integer.toString(this.element.parentObject.getId()));
+			idObjectTextField.setMinimumSize(idObjectTextField.getPreferredSize());
+			idObjectTextField.setBackground(Color.white);
+			idObjectTextField.setEditable(false);
+			idObjectTextField.setEnabled(false);
+			cellsInRow[2] = idObjectTextField;
+			// Name
+			JTextField elementNameTextField = new JTextField(this.element.getEleName());
+			elementNameTextField.getDocument().addDocumentListener((SimpleDocumentListener) e -> {
+				this.element.setEleName(elementNameTextField.getText());
+			});
+			elementNameTextField.setBackground(Color.white);
+			cellsInRow[3] = elementNameTextField;
+			// Energy
+
+			JFormattedTextField energyTextField = new JFormattedTextField(doubleFormatter);
+			energyTextField.setInputVerifier(getInputVerifier());
+			energyTextField.setValue(this.element.getEnergy());
+			energyTextField.setBackground(Color.white);
+			energyTextField.addPropertyChangeListener(actionEvent -> {
+				try {
+					float energy = Float.parseFloat(energyTextField.getText());
+					if (this.element.getEnergy() != energy) {
+						this.element.setEnergyPerElement(energy);
+						control.calculateStateAndVisualForCurrentTimeStep();
+					}
+				} catch (NumberFormatException e) {
+					// Dont Update
+				}
+
+			});
+			cellsInRow[4] = energyTextField;
+
+			// Priority
+			JComboBox<Priority> comboBox = new JComboBox<Priority>(Priority.values());
+			comboBox.setSelectedItem(this.element.getPriority());
+			comboBox.setBackground(Color.white);
+			comboBox.setEditable(false);
+			comboBox.addActionListener(ae -> {
+				this.element.setPriority((Priority) comboBox.getSelectedItem());
+			});
+			cellsInRow[5] = comboBox;
+
+			JPanel checkBoxWrapperPanel = new JPanel(new BorderLayout());
+			checkBoxWrapperPanel.setBorder(BorderFactory.createLineBorder(borderColor));
+			checkBoxWrapperPanel.setBackground(Color.white);
+			checkBoxWrapperPanel.setMinimumSize(new Dimension(columnHeight, columnHeight));
+			checkBoxWrapperPanel.setMaximumSize(new Dimension(columnHeight, columnHeight));
+			// Active
+			JCheckBox checkbox = new JCheckBox();
+			checkbox.setSelected(this.element.isActive());
+			checkbox.setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 0));
+			checkbox.setOpaque(false);
+			checkbox.addActionListener(actionEvent -> {
+				this.element.setActive(checkbox.isSelected());
+				control.calculateStateAndVisualForCurrentTimeStep();
+			});
+			checkBoxWrapperPanel.add(checkbox, BorderLayout.CENTER);
+			cellsInRow[6] = checkBoxWrapperPanel;
+		}
+
+	}
+}

+ 900 - 0
src/ui/view/inspector/UnitGraph.java

@@ -0,0 +1,900 @@
+package ui.view.inspector;
+
+import java.awt.BasicStroke;
+import java.awt.Color;
+import java.awt.Cursor;
+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 java.awt.geom.Path2D;
+import java.awt.geom.Point2D;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.ListIterator;
+import java.util.Optional;
+
+import javax.swing.JPanel;
+
+import classes.HolonElement;
+import interfaces.GraphEditable;
+import interfaces.GraphEditable.GraphType;
+import interfaces.LocalMode;
+import interfaces.TimelineDependent;
+import ui.controller.Control;
+import ui.model.Model;
+import utility.Vector2Int;
+
+/**
+ * This Class represents a Graph where the User can model the behavior of
+ * elements and switches over time.
+ *
+ * @author Tom Troppmann
+ */
+public class UnitGraph extends JPanel implements MouseListener, MouseMotionListener, ComponentListener {
+
+	// Normal Settings
+	private static final int border = 4;
+	private static final int clickThreshholdSquared = 25;
+
+	// Display Settings
+	/**
+	 * The size of a dot in the graph. It should be at least 1.
+	 */
+	private static final int dotSize = 8;
+
+	/** The Color of a dot in the graph. */
+	private static final Color dotColor = Color.blue;
+	private static final Color editDotColor = new Color(255, 119, 0);
+	private static final Color[] seriesColorArray = { Color.blue, Color.cyan, Color.black, Color.green, Color.gray,
+			Color.magenta, Color.yellow, Color.PINK, Color.red };
+
+	// Intern Variables
+	private class Series {
+		public LinkedList<UnitGraphPoint> points = new LinkedList<UnitGraphPoint>();
+		public TimelineDependent element;
+		public GraphType type;
+		public Color color;
+	}
+
+	private ArrayList<Series> seriesList = new ArrayList<Series>();
+	private Vector2Int editPosition;
+	private Optional<Series> actualSeries;
+	private boolean editMode = false;
+
+	private enum EditPointType {
+		Normal, StartPoint, EndPoint
+	};
+
+	private Model model;
+	private int widthWithBorder, heightWithBorder;
+
+	private EditPointType editPointType;
+
+	/**
+	 * Constructor.
+	 *
+	 * @param model   the Model
+	 * @param control the Controller
+	 */
+	public UnitGraph(Control control) {
+		setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
+		this.model = control.getModel();
+		this.setBackground(Color.WHITE);
+
+		this.addMouseListener(this);
+		this.addMouseMotionListener(this);
+		this.addComponentListener(this);
+	}
+
+	/**
+	 * When the UnitGraph should represent a new GraphEditable Element. Its Updates
+	 * the Graph and give access to the Element.
+	 * 
+	 * @param element
+	 */
+	public void addNewSeries(TimelineDependent element) {
+		Series series = new Series();
+		overrideUnitGraph(series, element.getStateGraph());
+		series.element = element;
+		series.type = element.getGraphType();
+		series.color = seriesColorArray[element.hashCode() % seriesColorArray.length];
+		seriesList.add(series);
+		repaint();
+	}
+
+	public void clearSeries() {
+		seriesList.clear();
+		repaint();
+	}
+
+	/**
+	 * Paints the Graph, the Grid, the actual Line from the currentIteration
+	 * 
+	 * @param g Graphics
+	 */
+	public void paintComponent(Graphics g) {
+		super.paintComponent(g);
+		Graphics2D g2D = (Graphics2D) g;
+		drawGrid(g2D);
+		g2D.setColor(Color.BLACK);
+		g2D.setRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON));
+		g2D.setStroke(new BasicStroke(2f));
+		drawUnitGraph(g2D);
+		g2D.setColor(dotColor);
+		if (editMode) {
+			drawUnitGraphPointsReleased(g2D);
+		} else {
+			drawUnitGraphPoints(g2D);
+		}
+		g2D.setColor(dotColor);
+		g2D.setStroke(new BasicStroke(1));
+		drawCurrentIterartionLine(g2D);
+	}
+
+	// Draw Methods only to let the User see the changes. Nothing its saved here or
+	// changed.
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Methods draws the UnitGraph whether its a boolGraph or a doubleGraph.
+	 * 
+	 * @param g to draw.
+	 */
+	private void drawUnitGraph(Graphics2D g) {
+		boolean drawSnappingHintFlag = false;
+		for (Series series : this.seriesList) {
+			g.setColor(series.color);
+			switch (series.type) {
+			case boolGraph:
+				if (editMode) {
+					drawBoolGraphInEditMode(g, series);
+					drawSnappingHintFlag = true;					
+				}
+				else
+					drawBoolGraph(g, series);
+				break;
+			case doubleGraph:
+				if (editMode)
+					drawDoubleGraphInEditMode(g, series);
+				else
+					drawDoubleGraph(g, series);
+				break;
+			default:
+				throw new UnsupportedOperationException();
+			}
+		}
+		if(drawSnappingHintFlag) {
+			drawSnappingHint(g);
+		}
+			
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Methods draws the UnitGraphPoints of the UnitGraph.
+	 * 
+	 * @param g to draw.
+	 */
+	private void drawUnitGraphPoints(Graphics2D g) {
+		g.setColor(dotColor);
+		for (Series series : seriesList) {
+			for (UnitGraphPoint p : series.points) {
+				drawDot(g, p.displayedPosition);
+			}
+		}
+
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Methods draws the UnitGraphPoints of the UnitGraph when its in EditMode.
+	 * 
+	 * @param g to draw.
+	 */
+	private void drawUnitGraphPointsReleased(Graphics2D g) {
+		drawUnitGraphPoints(g);
+		g.setColor(editDotColor);
+		drawDot(g, editPosition);
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Methods draws the Grid on the Canvas.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawGrid(Graphics2D g2D) {
+		g2D.setStroke(new BasicStroke(1));
+		g2D.setColor(Color.lightGray);
+		int amountOfLines = 10;
+		int width = widthWithBorder + 2 * border;
+		int height = heightWithBorder;
+		for (int i = 0; i <= amountOfLines; i++) {
+			int linehieght = (int) (((double) i / (double) amountOfLines) * (double) height) + border;
+			g2D.drawLine(0, linehieght, width, linehieght);
+		}
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws the CurrentIterationLine.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawCurrentIterartionLine(Graphics2D g) {
+		int cur = model.getCurrentIteration();
+		int max = model.getMaxIterations();
+		if(isLocalPeriedDifferentInSeries()){
+			for(Series series: seriesList) {
+				double where;
+				if (!series.element.isUsingLocalPeriod()) {
+					where = ((double) cur) / ((double) max);
+				} else {
+					int lPeriod = series.element.getLocalPeriod();
+					where = ((double) cur % lPeriod) / ((double) lPeriod);
+				}
+				Vector2Int oben = new Vector2Int(border + (int) (where * widthWithBorder), 0);
+				Vector2Int unten = new Vector2Int(border + (int) (where * widthWithBorder), 2 * border + heightWithBorder);
+				g.setColor(series.color);
+				drawLine(g, oben, unten);
+			}
+		}
+		else {
+			double where;
+			if (!isUsingLocalPeriod()) {
+				where = ((double) cur) / ((double) max);
+			} else {
+				int lPeriod = getFirstLocalPeriod();
+				where = ((double) cur % lPeriod) / ((double) lPeriod);
+			}
+			Vector2Int oben = new Vector2Int(border + (int) (where * widthWithBorder), 0);
+			Vector2Int unten = new Vector2Int(border + (int) (where * widthWithBorder), 2 * border + heightWithBorder);
+			g.setColor(dotColor);
+			drawLine(g, oben, unten);
+		}
+		
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws a line between two Positions on the Canvas.
+	 * 
+	 * @param g2D   to draw.
+	 * @param start the Position of one end of the line to draw.
+	 * @param end   the other Ends Position of the Line to draw.
+	 */
+	private void drawLine(Graphics2D g, Vector2Int start, Vector2Int end) {
+		Path2D.Double path = new Path2D.Double();
+		path.moveTo(start.getX(), start.getY());
+		path.lineTo(end.getX(), end.getY());
+		g.draw(path);
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * Initialize a Cubic BezierCurve.
+	 * 
+	 * @param start The Position to start the Curve.
+	 */
+	private Path2D.Double initBezier(Vector2Int start) {
+		// Good Source for basic understanding for Bezier Curves
+		// http://www.theappguruz.com/blog/bezier-curve-in-games
+		Path2D.Double path = new Path2D.Double();
+		path.moveTo(start.getX(), start.getY());
+		return path;
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * Calculate the Path of a the Cubic BezierCurve with the special controlPoints
+	 * to make the wanted behavior.
+	 * 
+	 * @param path   the path of the Bezier.
+	 * @param actaul the actual Position of the Path.
+	 * @param target the end Position of the Curve.
+	 */
+	private void curveTo(Path2D.Double path, Vector2Int actual, Vector2Int target) {
+		double mitte = (actual.getX() + target.getX()) * 0.5;
+		path.curveTo(mitte, actual.getY(), mitte, target.getY(), target.getX(), target.getY());
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * Draws a Dot at a Position.
+	 * 
+	 * @param g to draw.
+	 * @param p the position of the Dot.
+	 */
+	private void drawDot(Graphics2D g, Vector2Int p) {
+		g.fillOval(p.getX() - dotSize / 2, p.getY() - dotSize / 2, dotSize, dotSize);
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws the UnitGraph as BoolGraph.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawBoolGraph(Graphics2D g, Series series) {
+		if (series.points.size() <= 1)
+			return;
+		LinkedList<Vector2Int> cornerPoints = new LinkedList<Vector2Int>();
+		ListIterator<UnitGraphPoint> iter = series.points.listIterator();
+		Vector2Int actual = series.points.getFirst().displayedPosition;
+		Path2D.Double path = new Path2D.Double();
+		path.moveTo(actual.getX(), actual.getY());
+		while (iter.hasNext()) {
+			Vector2Int target = iter.next().displayedPosition;
+			// BooleanConnection
+			path.lineTo(target.getX(), actual.getY()); // line to corner
+			cornerPoints.add(new Vector2Int(target.getX(), actual.getY())); // save corner
+			path.lineTo(target.getX(), target.getY()); // line to next Point
+
+			actual = target;
+		}
+		g.draw(path);
+		// Draw the Points on the Corner that dont exist in Data but should be visual
+		g.setColor(dotColor);
+		for (Vector2Int p : cornerPoints) {
+			drawDot(g, p);
+		}
+
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws the UnitGraph as BoolGraph in EditMode.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawBoolGraphInEditMode(Graphics2D g, Series series) {
+		LinkedList<Vector2Int> before = new LinkedList<Vector2Int>();
+		LinkedList<Vector2Int> after = new LinkedList<Vector2Int>();
+		for (UnitGraphPoint p : series.points) {
+			if (p.displayedPosition.getX() < editPosition.getX())
+				before.add(p.displayedPosition);
+			else
+				after.add(p.displayedPosition);
+		}
+		g.setColor(series.color);
+		drawBoolGraphFromList(g, before);
+		g.setColor(series.color);
+		drawBoolGraphFromList(g, after);
+		// EditGraph
+		LinkedList<Vector2Int> middle = new LinkedList<Vector2Int>();
+		if (!before.isEmpty())
+			middle.add(before.getLast());
+		middle.add(editPosition);
+		if (!after.isEmpty())
+			middle.add(after.getFirst());
+
+		g.setColor(editDotColor);
+		drawBoolGraphFromList(g, middle);
+
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws a red Hint to signal the User the snapping of the hovered
+	 * Point under the Cursor in EditMode.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawSnappingHint(Graphics2D g) {
+		// ColorHint
+		g.setColor(Color.RED);
+		// Threshhold Line
+		final float dash1[] = { 10.0f };
+		final BasicStroke dashed = new BasicStroke(2.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash1,
+				0.0f);
+		g.setStroke(dashed);
+
+		int halfheight = border + heightWithBorder / 2;
+		g.drawLine(0, halfheight, widthWithBorder + 2 * border, halfheight);
+		// Threshhold Text
+		g.drawString("Snapping Threshold", 10, halfheight - 2);
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws a partial Graph from a Position List as BoolGraph.
+	 * 
+	 * @param g2D  to draw.
+	 * @param list the PositionList to draw a BoolGraph
+	 */
+	private void drawBoolGraphFromList(Graphics2D g, LinkedList<Vector2Int> list) {
+		if (list.size() <= 1)
+			return;
+		ListIterator<Vector2Int> iter = list.listIterator();
+		LinkedList<Vector2Int> cornerPoints = new LinkedList<Vector2Int>();
+		Vector2Int actual = list.getFirst();
+		Path2D.Double path = new Path2D.Double();
+		path.moveTo(actual.getX(), actual.getY());
+		while (iter.hasNext()) {
+			Vector2Int target = iter.next();
+			// BooleanConnection
+			path.lineTo(target.getX(), actual.getY()); // line to corner
+			cornerPoints.add(new Vector2Int(target.getX(), actual.getY())); // save corner
+			path.lineTo(target.getX(), target.getY()); // line to next Point
+			actual = target;
+		}
+		g.draw(path);
+		g.setColor(dotColor);
+		for (Vector2Int p : cornerPoints) {
+			drawDot(g, p);
+		}
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws the UnitGraph as DoubleGraph.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawDoubleGraph(Graphics2D g, Series series) {
+		if (series.points.isEmpty())
+			return;
+		ListIterator<UnitGraphPoint> iter = series.points.listIterator();
+		Vector2Int actual = iter.next().displayedPosition;
+		Path2D.Double path = this.initBezier(actual);
+		while (iter.hasNext()) {
+			Vector2Int target = iter.next().displayedPosition;
+			this.curveTo(path, actual, target);
+			actual = target;
+		}
+		g.draw(path);
+
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws the UnitGraph as DoubleGraph in EditMode.
+	 * 
+	 * @param g2D to draw.
+	 */
+	private void drawDoubleGraphInEditMode(Graphics2D g, Series series) {
+		LinkedList<Vector2Int> before = new LinkedList<Vector2Int>();
+		LinkedList<Vector2Int> after = new LinkedList<Vector2Int>();
+		for (UnitGraphPoint p : series.points) {
+			if (p.displayedPosition.getX() < editPosition.getX())
+				before.add(p.displayedPosition);
+			else
+				after.add(p.displayedPosition);
+		}
+		drawUnitGraphFromList(g, before);
+		drawUnitGraphFromList(g, after);
+		// EditGraph
+		LinkedList<Vector2Int> middle = new LinkedList<Vector2Int>();
+		if (!before.isEmpty())
+			middle.add(before.getLast());
+		middle.add(editPosition);
+		if (!after.isEmpty())
+			middle.add(after.getFirst());
+
+		g.setColor(editDotColor);
+		drawUnitGraphFromList(g, middle);
+	}
+
+	/**
+	 * Helper Method to draw the UnitGraphPanel.
+	 * {@link UnitGraph#paintComponent(Graphics)}
+	 * <p>
+	 * This Method draws a partial Graph from a Position List as DoubleGraph.
+	 * 
+	 * @param g2D  to draw.
+	 * @param list the PositionList to draw a DoubleGraph
+	 */
+	private void drawUnitGraphFromList(Graphics2D g, LinkedList<Vector2Int> list) {
+		if (list.size() <= 1)
+			return;
+		ListIterator<Vector2Int> iter = list.listIterator();
+		Vector2Int actual = list.getFirst();
+		Path2D.Double path = this.initBezier(actual);
+		while (iter.hasNext()) {
+			Vector2Int target = iter.next();
+			curveTo(path, actual, target);
+			actual = target;
+		}
+		g.draw(path);
+	}
+
+	// Under the hood functions to calculate and function the
+	/**
+	 * A unitgraphpoint have a x and y position to store the data of a graph point.
+	 * Also it have a displayposition to store the Position of the GraphPoints on
+	 * the Canvas. e.g. when the canvas has 500 width and 200 height a GraphPoint
+	 * with the X=0.5 and Y=1.0 should have a displayposition of (250,3) when border
+	 * is 3.
+	 */
+	private void updateRepresentativePositions() {
+		for (Series series : seriesList) {
+			for (UnitGraphPoint p : series.points) {
+				p.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
+			}
+		}
+	}
+
+	/**
+	 * Takes a List of GraphPoints and convert it to the actual UnitGraphPoints with
+	 * displayposition in the {@link #seriesList}
+	 * 
+	 * @param stateCurve the list of GraphPoint
+	 */
+	private void overrideUnitGraph(Series series, LinkedList<Point2D.Double> stateCurve) {
+		series.points.clear();
+		for (Point2D.Double p : stateCurve) {
+			UnitGraphPoint point = new UnitGraphPoint(p);
+			point.calcDisplayedPosition(border, widthWithBorder, heightWithBorder);
+			series.points.add(point);
+		}
+	}
+
+	/**
+	 * When the PanelSize Change the width and height to calculate the drawings have
+	 * to be adjusted.
+	 */
+	private void calculateWidthHeight() {
+		widthWithBorder = this.getWidth() - 2 * border;
+		heightWithBorder = this.getHeight() - 2 * border;
+	}
+
+	/**
+	 * Save the actualGraphPoint List to the GraphEditable Element.
+	 */
+	private void saveGraph() {
+		for (Series series : seriesList) {
+			LinkedList<Point2D.Double> actual = series.element.getStateGraph();
+			actual.clear();
+			for (UnitGraphPoint p : series.points) {
+				actual.add(p.getPoint());
+			}
+			series.element.sampleGraph();
+		}
+	}
+
+	/**
+	 * Remove a UnitGraphPoint from the UnitGraphPoint list ({@link #seriesList}
+	 * when its near a given Position.
+	 * 
+	 * @param mPosition
+	 */
+	private void removePointNearPosition(Series series, Vector2Int mPosition) {
+		ListIterator<UnitGraphPoint> iter = series.points.listIterator();
+		while (iter.hasNext()) {
+			if (near(mPosition, iter.next().displayedPosition, series.type)) {
+				iter.remove();
+				break;
+			}
+		}
+
+	}
+
+	private void removePointsNearPosition(Vector2Int mPosition) {
+		for (Series series : seriesList) {
+			removePointNearPosition(series, mPosition);
+		}
+	}
+
+	private Optional<Series> detectSeries(Vector2Int mPosition) {
+		return seriesList.stream().min((a, b) -> {
+			float minDistanceA = a.points.stream().map(point -> point.displayedPosition.getSquaredDistance(mPosition))
+					.min(Float::compare).get();
+			float minDistanceB = b.points.stream().map(point -> point.displayedPosition.getSquaredDistance(mPosition))
+					.min(Float::compare).get();
+			return Float.compare(minDistanceA, minDistanceB);
+		});
+	}
+
+	/**
+	 * Determine if the Point is a StartPoint , EndPoint or a NormalPoint a.k.a. in
+	 * between Points.
+	 * 
+	 * @param mPosition The Position to check.
+	 */
+	private EditPointType detectStartEndPoint(Series series, Vector2Int mPosition) {
+		UnitGraphPoint first = series.points.getFirst();
+		UnitGraphPoint last = series.points.getLast();
+		if (near(mPosition, first.displayedPosition, series.type))
+			return EditPointType.StartPoint;
+		else if (near(mPosition, last.displayedPosition, series.type))
+			return EditPointType.EndPoint;
+		else
+			return EditPointType.Normal;
+	}
+
+	/**
+	 * Determine if a Point is near the Cursor (depends on Mode what near means). To
+	 * detect if it should grab the Point or create a new Point.
+	 * 
+	 * @param actual
+	 * @param target
+	 * @return
+	 */
+	private boolean near(Vector2Int actual, Vector2Int target, GraphType graphType) {
+		switch (graphType) {
+		case boolGraph: // Distance only with X
+			int xDis = target.getX() - actual.getX();
+			return xDis * xDis < clickThreshholdSquared;
+		case doubleGraph:
+			return actual.getSquaredDistance(target) < clickThreshholdSquared;
+		default:
+			return false;
+		}
+	}
+
+	/**
+	 * When the Mouse Drag a Point it updates each time the position.
+	 * 
+	 * @param newPosition
+	 */
+	private void updateEditPointPosition(Vector2Int newPosition, EditPointType editPointType, GraphType graphType) {
+		// make it in the bounds of the UnitGraph no Point out of the Border
+		Vector2Int currentPosition = setInBounds(newPosition);
+		if (editPointType != EditPointType.Normal) {
+			attachToBorder(currentPosition, editPointType);
+		}
+		if (graphType == GraphType.boolGraph) {
+			snapBoolean(currentPosition);
+		}
+		editPosition = currentPosition;
+	}
+
+	/**
+	 * No Point on the UnitGraph should exit the UnitGraph.
+	 * 
+	 * @param p the Position
+	 * @return the updated Position.
+	 */
+	private Vector2Int setInBounds(Vector2Int p) {
+		p.clampX(border, border + widthWithBorder);
+		p.clampY(border, border + heightWithBorder);
+		return p;
+	}
+
+	/**
+	 * For Switches the Point have to be Snap to the Top or the Bottem.
+	 * 
+	 * @param p the Position
+	 * @return the updated Position.
+	 */
+	private Vector2Int snapBoolean(Vector2Int p) {
+		if (p.getY() < border + heightWithBorder / 2) {
+			p.setY(border);
+		} else {
+			p.setY(border + heightWithBorder);
+		}
+		return p;
+	}
+
+	/**
+	 * The First Point has to be at 0(LeftSide) and Last Point has to be at
+	 * 1(RightSide).
+	 * 
+	 * @param p the Position
+	 * @return the updated Position.
+	 */
+	private Vector2Int attachToBorder(Vector2Int p, EditPointType editPointType) {
+		switch (editPointType) {
+		case StartPoint:
+			p.setX(border);
+			break;
+		case EndPoint:
+			p.setX(border + widthWithBorder);
+			break;
+		default:
+			break;
+		}
+		return p;
+	}
+
+	/**
+	 * Insert a Position in the UnitGraphList at the right order. Its sorted based
+	 * on the xValues.
+	 * 
+	 * @param pos The new UnitGraphPoints Position
+	 */
+	private void insertNewGraphPoint(Series series, Vector2Int pos) {
+		setInBounds(pos);
+		ListIterator<UnitGraphPoint> iter = series.points.listIterator();
+		while (iter.hasNext()) {
+			Vector2Int tempPosition = iter.next().displayedPosition;
+			if (pos.getX() <= tempPosition.getX()) {
+				// previous to go back a position to make the new point before the the Position
+				// with greater X
+				iter.previous();
+				iter.add(generateUnitGraphPoint(pos));
+				break;
+			}
+		}
+		if (!iter.hasNext()) // if behind last point
+		{
+			iter.add(generateUnitGraphPoint(pos));
+		}
+	}
+
+	/**
+	 * Generate a UnitGraphPoint from a normal Position in the UnitGraph.
+	 * 
+	 * @param pos the normal pos with xValues from 0..Width and yValues from
+	 *            0..Height
+	 * @return a UnitGraphPoint
+	 */
+	private UnitGraphPoint generateUnitGraphPoint(Vector2Int pos) {
+		UnitGraphPoint temp = new UnitGraphPoint((double) (pos.getX() - border) / (double) widthWithBorder,
+				1 - (double) (pos.getY() - border) / (double) heightWithBorder, true);
+		temp.displayedPosition = pos;
+		return temp;
+	}
+
+	/**
+	 * Update the Point Position
+	 */
+	@Override
+	public void mouseDragged(MouseEvent e) {
+		actualSeries.ifPresent(series -> {
+			updateEditPointPosition(new Vector2Int(e.getPoint().x, e.getPoint().y), this.editPointType, series.type);
+			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) {
+	}
+
+	/**
+	 * The First Step. When LeftMouseButton its checks if a point is to grab under
+	 * the cursor or create a new Point. Then enter EditMode. When RightMouseButton
+	 * its delete a point if its under the Curser.
+	 */
+	@Override
+	public void mousePressed(MouseEvent e) {
+		Vector2Int mPosition = new Vector2Int(e.getPoint().x, e.getPoint().y);
+		actualSeries = detectSeries(mPosition);
+		actualSeries.ifPresent(series -> {
+			if (e.getButton() == MouseEvent.BUTTON3) {
+				// RightMouseButtonEvent
+				editPointType = detectStartEndPoint(series, mPosition);
+				if (editPointType == EditPointType.Normal) {
+					removePointsNearPosition(mPosition);
+					repaint();
+				}
+				editMode = false;
+
+			} else if (e.getButton() == MouseEvent.BUTTON1) {
+				// LeftMouseButtonEvent
+				editPointType = detectStartEndPoint(series, mPosition);
+				removePointsNearPosition(mPosition);
+				updateEditPointPosition(mPosition, editPointType, series.type);
+				editMode = true;
+				repaint();
+			}
+		});
+
+	}
+
+	/**
+	 * The last step to save the Changes. Its insert the Hovering Point and exit
+	 * EditMode.
+	 */
+	@Override
+	public void mouseReleased(MouseEvent e) {
+		if (editMode && actualSeries.isPresent()) {
+			for (Series series : seriesList) {
+				this.insertNewGraphPoint(series, editPosition);
+			}
+			editMode = false;
+			repaint();
+		}
+		saveGraph();
+	}
+
+	/**
+	 * When the Component is Resized.
+	 *
+	 * @param e ComponentEvent
+	 */
+	public void componentResized(ComponentEvent e) {
+		calculateWidthHeight();
+		updateRepresentativePositions();
+		repaint();
+	}
+
+	@Override
+	public void componentHidden(ComponentEvent e) {
+	}
+
+	@Override
+	public void componentMoved(ComponentEvent e) {
+
+	}
+
+	@Override
+	public void componentShown(ComponentEvent e) {
+	}
+
+	/**
+	 * Resets the graph to normal.
+	 */
+	public void reset() {
+		for (Series series : seriesList) {
+			series.element.reset();
+			overrideUnitGraph(series, series.element.getStateGraph());
+		}
+		repaint();
+	}
+
+	// LocalMode access methods...
+	// To access a element from the GUI for the LocalMode
+	public void setUseLocalPeriod(boolean state) {
+		for (Series series : seriesList) {
+			series.element.setUseLocalPeriod(state);
+		}
+	}
+
+	public void setLocalPeriod(int localLength) {
+		for (Series series : seriesList) {
+			series.element.setLocalPeriod(localLength);
+		}
+	}
+
+	public boolean isLocalPeriedDifferentInSeries() {
+		return seriesList.stream().map(series -> series.element.getLocalPeriod()).distinct().count() > 1;
+	}
+	public int getFirstLocalPeriod() {
+		int period = 0;
+		//seriesList.stream().findFirst().ifPresentOrElse(series -> return series.element.getLocalPeriod(), () -> period = LocalMode.STANDARD_GRAPH_ACCURACY);
+		return period;
+	}
+
+	public boolean isUsingLocalPeriod() {
+		return seriesList.stream().anyMatch(series -> series.element.isUsingLocalPeriod());
+	}
+
+}

+ 1 - 1
src/classes/UnitGraphPoint.java → src/ui/view/inspector/UnitGraphPoint.java

@@ -1,4 +1,4 @@
-package classes;
+package ui.view.inspector;
 
 import java.awt.Point;
 import java.awt.geom.Point2D;

+ 1713 - 0
src/ui/view/main/GUI.java

@@ -0,0 +1,1713 @@
+package ui.view.main;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Cursor;
+import java.awt.Dimension;
+import java.awt.GraphicsDevice;
+import java.awt.GraphicsEnvironment;
+import java.awt.HeadlessException;
+import java.awt.Image;
+import java.awt.Point;
+import java.awt.Rectangle;
+import java.awt.Toolkit;
+import java.awt.datatransfer.UnsupportedFlavorException;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
+import java.awt.event.ItemEvent;
+import java.awt.event.KeyAdapter;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.event.MouseMotionAdapter;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.ListIterator;
+
+import javax.swing.AbstractAction;
+import javax.swing.ActionMap;
+import javax.swing.Box;
+import javax.swing.BoxLayout;
+import javax.swing.GrayFilter;
+import javax.swing.ImageIcon;
+import javax.swing.InputMap;
+import javax.swing.JButton;
+import javax.swing.JCheckBoxMenuItem;
+import javax.swing.JComboBox;
+import javax.swing.JComponent;
+import javax.swing.JDialog;
+import javax.swing.JFileChooser;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JMenu;
+import javax.swing.JMenuBar;
+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 javax.swing.JTextField;
+import javax.swing.JToolBar;
+import javax.swing.JTree;
+import javax.swing.KeyStroke;
+import javax.swing.SwingUtilities;
+import javax.swing.filechooser.FileNameExtensionFilter;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.TreeCellRenderer;
+
+import org.apache.commons.compress.archivers.ArchiveException;
+
+import com.google.gson.JsonParseException;
+
+import classes.AbstractCanvasObject;
+import classes.Category;
+import classes.Edge;
+import classes.GroupNode;
+import classes.HolonObject;
+import classes.HolonSwitch;
+import classes.IdCounter;
+import classes.IdCounter.CounterType;
+import interfaces.GraphEditable;
+import ui.controller.Control;
+import ui.model.DecoratedState;
+import ui.model.Model;
+import ui.model.Model.FairnessModel;
+import ui.view.canvas.AbstractCanvas;
+import ui.view.canvas.Canvas;
+import ui.view.canvas.GroupNodeCanvas;
+import ui.view.component.ButtonTabComponent;
+import ui.view.dialog.AboutUsPopUp;
+import ui.view.dialog.AddObjectPopUp;
+import ui.view.dialog.BackgroundPopUp;
+import ui.view.dialog.CanvasResizePopUp;
+import ui.view.dialog.CreateNewDialog;
+import ui.view.dialog.CreateNewDialog.Option;
+import ui.view.inspector.Inspector;
+import ui.view.inspector.UnitGraph;
+import ui.view.dialog.EditEdgesPopUp;
+import ui.view.dialog.SearchPopUp;
+import ui.view.window.AddOnWindow;
+import ui.view.window.FlexWindow;
+import ui.view.window.Outliner;
+import utility.ImageImport;
+
+/**
+ * Graphical User Interface.
+ *
+ * @author Gruppe14
+ */
+public class GUI {
+
+	static final Color PALE_RED = new Color(255, 192, 192);
+
+	/**
+	 * Menu on the Top containing File, Edit View Help etc
+	 */
+	private final JMenuBar menuBar = new JMenuBar();
+	private final JMenu mnNewMenu = new JMenu("File");
+	private final JMenu mnNewMenuEdit = new JMenu("Edit");
+	private final JMenu mnNewMenuOptions = new JMenu("Options");
+	private final JMenu mnNewMenuView = new JMenu("View");
+	private final JMenu menuWindow = new JMenu("Window");
+
+	/** Help Menu containing helpful Informations and the AboutUs Popup */
+	private final JMenu mnHelp = new JMenu("Help");
+
+	/**
+	 * Help -> Introduction A small Introduction of the Application, SmartGrids and
+	 * Holons
+	 */
+	private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
+
+	/**
+	 * Help -> UserManual
+	 */
+	private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
+
+	/** Help -> Algorithm Help Menu */
+	private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
+
+	/** Help -> CodeDocumentation */
+	private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
+
+	/** Help -> AboutUs */
+	private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
+	/** checked if supplyBars should be shown */
+	private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem("Show supply bars.");
+	/** menu for the different fairness Models */
+	private final JMenu mnFairnessModel = new JMenu("Fairness Model");
+	/** press to supply minimum demand first */
+	private final JMenuItem mntmFairMinFirst = new JMenuItem("Minimum demand first");
+	/** press to give everyone the same energy */
+	private final JMenuItem mntmFairAlleEqual = new JMenuItem("Equal supply for everyone");
+	private final JMenuItem mntmOpen = new JMenuItem("Open");
+	private final JMenuItem mntmNew = new JMenuItem("New");
+	private final JMenuItem mntmSave = new JMenuItem("Save");
+	private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
+	private final JMenuItem mntmBackground = new JMenuItem("Set Background Image");
+	private final JSplitPane splitPane = new JSplitPane();
+	private final JSplitPane splitPane1 = new JSplitPane();
+	// the tabbed canvas containing the different sub-net tabs of the grid (Main
+	// Grid + Nodes of Nodes)
+
+	private final JPanel myPanel = new JPanel(new BorderLayout());
+	private final JTabbedPane tabbedPaneInnerOriginal = 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();
+	// private final JScrollPane holonSP = new JScrollPane();
+	// the original tabbed Pane (containing tabs for view, statistics, holon,
+	// flexibility)
+	private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(JTabbedPane.TOP);
+	private final JPopupMenu popmenuEdit = new JPopupMenu();
+	private final JMenuItem editItem = new JMenuItem("Edit Object");
+
+	private final JLabel elementGraph = new JLabel("None ");
+	private final JTree categoryTree = new JTree();
+	/******************************************
+	 ************* Right Container*************
+	 ******************************************
+	 * Right Container: here comes the information about the HolonObject, such as
+	 * HolonElements Information, Properties and Consumption/Production graph.
+	 **/
+	private final Inspector inspector;
+	private final JSplitPane splitHolonElPro = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
+	private final JSplitPane splitGraphHolonEl = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
+	private final int distanceBetweenElementsAndGraph = 350;
+
+	// Prechoosed local Periods
+
+	private final JScrollPane scrollProperties = new JScrollPane();
+	// In this section is the graph for the selected HolonElement of the clicked
+
+	private final Model model;
+	private final Control controller;
+
+	// In this section are all the Holonelements that correspond to the clicked
+	// HolonObject with consumption/production, name and amount.
+	private final JPanel panel = new JPanel();
+	private final JPanel panelHolonEl = new JPanel();
+	// Buttons
+
+	private final JButton btnAdd = new JButton();
+	private final JPopupMenu btnAddPopUp = new JPopupMenu("Newacac");
+	private final JMenuItem mItemNew = new JMenuItem("New..");
+	private final JMenuItem mItemCategory = new JMenuItem("Category");
+	private final JMenuItem mItemObject = new JMenuItem("Object");
+	private final JMenuItem mItemSwitch = new JMenuItem("Switch");
+	private final JButton btnDel = new JButton();
+
+	private final JToolBar toolBar = new JToolBar();
+	private final JToolBar toolBarHolonEl = new JToolBar();
+
+	// Languages
+	private final Canvas canvas;
+	private final UnitGraph unitGraph;
+	/** Textfield to show the period of an element */
+	private final JTextField unitGraphLocalPeriod = new JTextField(6);
+	private final JMenuItem mntmUndo = new JMenuItem("Undo");
+	private final JMenuItem mntmRedo = new JMenuItem("Redo");
+	private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
+	private final JMenuItem mntmFindReplace = new JMenuItem("Find/ Replace");
+	private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
+	private final JMenuItem mntmResetCategory = new JMenuItem("Reset Categories");
+	// TODO make GUI a JFRAME and remove holegJFrame
+	private JFrame holegJFrame;
+
+	// tabbedPaneOriginal or tabbedPaneSplit
+	private JTabbedPane tabTemp;
+	private String catOfObjToBeEdited;
+	private GroupNodeCanvas unc;
+	private JPanel contentPane;
+	// Pop up Windows
+	private AddObjectPopUp addObjectPopUP;
+	private AboutUsPopUp aboutUsPopUp;
+	// variables
+	private boolean dragging = false;
+	private String actualObjectClicked;
+	private Image img = null;
+	private AbstractCanvasObject tempCps = null;
+	// Time Stuff
+	private TimePanel timePanel;
+
+	public TimePanel getTimePanel() {
+		return timePanel;
+	}
+
+	private AbstractCanvasObject temp = null;
+	private String warningText = "Warning";
+	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 the left library in order to delete something.";
+
+	private List<Outliner> outlinerList = new ArrayList<Outliner>();
+	private List<FlexWindow> flexList = new ArrayList<FlexWindow>();
+
+	private JMenuItem removeItem = new JMenuItem("Remove");
+
+	/**
+	 * Create the application.
+	 *
+	 * @param control the Controller
+	 */
+	GUI(Control control) {
+		this.controller = control;
+		this.model = control.getModel();
+		inspector = new Inspector(control);
+		control.setGui(this);
+		control.calculateStateAndVisualForCurrentTimeStep();
+		this.unitGraph = new UnitGraph(control);
+		this.canvas = new Canvas(model, control, unitGraph);
+		initialize();
+		updateCategories(model.getCategories());
+		control.OnCategoryChanged.addListener(() -> this.updateCategoryUI(model.getCategories()));
+	}
+
+	/**
+	 * Initialize the contents of the frame.
+	 */
+	private void initialize() {
+		holegJFrame = new JFrame();
+		holegJFrame.setTitle("HOLEG Simulator");
+		// try to restore old position/dimensions
+		ArrayList<Integer> savedWindowDim = controller.loadSavedWindowDimensionsIfExistent();
+		if (savedWindowDim.size() == 4) {
+			holegJFrame.setBounds(savedWindowDim.get(0), savedWindowDim.get(1), savedWindowDim.get(2),
+					savedWindowDim.get(3));
+		}
+
+		// if the upper part of the window is showing, the windows can still be
+		// moved,
+		// but if it is not, we need to move it to somewhere else
+		if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
+			holegJFrame.setBounds(100, 100, 1000, 800);
+			holegJFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
+		}
+		holegJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
+
+		holegJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
+			@Override
+			public void windowClosing(java.awt.event.WindowEvent windowEvent) {
+				if (JOptionPane.showConfirmDialog(holegJFrame, "Are you sure you want to exit?", "HOLEG",
+						JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
+					controller
+							.deleteDirectory(new File(System.getProperty("user.home") + "/.config/HolonGUI/Autosave"));
+
+					// try to save the position and size of the window, such
+					// that (if possible)
+					// it can be opened in the same position the next time
+					try {
+						controller.savePosAndSizeOfWindow(holegJFrame.getX(), holegJFrame.getY(),
+								holegJFrame.getWidth(), holegJFrame.getHeight());
+					} catch (Exception e) {
+						e.printStackTrace();
+					}
+					System.exit(1);
+				}
+				System.exit(0);
+			}
+		});
+
+		contentPane = (JPanel) holegJFrame.getContentPane();
+
+		int condition = JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT;
+		InputMap inputMap = contentPane.getInputMap(condition);
+		ActionMap actionMap = contentPane.getActionMap();
+
+		String cntrlZDown = "controlZ";
+		inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
+		actionMap.put(cntrlZDown, new AbstractAction() {
+
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				try {
+					controller.loadAutoSave(controller.getUndoSave());
+					closeInvalidUpperNodeTabs();
+
+					controller.calculateStateAndVisualForCurrentTimeStep();
+					canvas.repaint();
+					updateUpperNodes();
+				} catch (IOException eex) {
+					eex.printStackTrace();
+				}
+			}
+		});
+
+		String cntrlYDown = "controlY";
+		inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
+		actionMap.put(cntrlYDown, new AbstractAction() {
+
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				try {
+					controller.loadAutoSave(controller.getRedoSave());
+
+					closeInvalidUpperNodeTabs();
+
+					controller.calculateStateAndVisualForCurrentTimeStep();
+					canvas.repaint();
+					updateUpperNodes();
+				} catch (IOException ex) {
+					ex.printStackTrace();
+				}
+			}
+		});
+
+		String cntrlADown = "controlA";
+		inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
+		AbstractAction controlA = new AbstractAction() {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				chooseTabTemp();
+
+				model.getSelectedObjects().clear();
+
+				// Uppernode Canvas?
+				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+				Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
+
+				if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+					GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
+					controller.addSelectedObjects(uNC.getGroupNode().getNodes());
+					uNC.repaint();
+					// or Canvas?
+				} else if (canvasOrUpperNodeCanvas instanceof Canvas) {
+					controller.addSelectedObjects(model.getObjectsOnCanvas());
+					canvas.repaint();
+				}
+				controller.getObjectsInDepth();
+			}
+		};
+		actionMap.put(cntrlADown, controlA);
+
+		String delDown = "delete";
+		inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false), delDown);
+		actionMap.put(delDown, new AbstractAction() {
+
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				chooseTabTemp();
+
+				// Uppernode Canvas?
+				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 = true;
+
+				if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+					GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
+					for (AbstractCanvasObject cps : model.getSelectedObjects()) {
+						if (uNC.getGroupNode().getNodes().contains(cps)) {
+							controller.delObjUpperNode(cps, uNC.getGroupNode());
+							unc.setToolTip(false);
+
+							// remove UpperNodeTab if UpperNode deleted
+							removeUpperNodeTab(cps);
+						}
+					}
+					uNC.repaint();
+					controller.clearSelection();
+
+					// or Canvas?
+				} else if (canvasOrUpperNodeCanvas instanceof Canvas) {
+					// Edge Deleting
+					Edge edgeHighlight = model.getSelectedEdge();
+					if (edgeHighlight != null) {
+						controller.removeEdgesOnCanvas(edgeHighlight);
+						((Canvas) canvasOrUpperNodeCanvas).edgeHighlight = null;
+					}
+					canvas.setToolTip(false);
+					for (AbstractCanvasObject cps : model.getSelectedObjects()) {
+						controller.delCanvasObject(cps, false);
+						// remove UpperNodeTab if UpperNode deleted
+						removeUpperNodeTab(cps);
+					}
+					controller.clearSelection();
+					controller.tryAutoSave();
+					canvas.repaint();
+				}
+
+				// recalculate net if a producer was deleted
+				if (wasProducerDeleted) {
+					controller.resetSimulation();
+					controller.calculateStateAndVisualForCurrentTimeStep();
+				}
+
+				model.getSelectedObjects().clear();
+			}
+		});
+
+		String cntrlFDown = "controlF";
+		inputMap.put(KeyStroke.getKeyStroke("control F"), cntrlFDown);
+		actionMap.put(cntrlFDown, new AbstractAction() {
+
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				SearchPopUp dialog = new SearchPopUp(controller, canvas, holegJFrame);
+				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+				dialog.setVisible(true);
+			}
+		});
+
+		String cntrlCDown = "controlC";
+		inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
+		AbstractAction controlC = new AbstractAction() {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				chooseTabTemp();
+				System.out.println("heiCopy - control C");
+				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+				if (!model.getSelectedObjects().isEmpty()) {
+					if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas)
+						controller.copy(((GroupNodeCanvas) scrollPane.getViewport().getComponent(0)).getGroupNode());
+					else
+						controller.copy(null);
+					if (!model.getClipboradObjects().isEmpty()) {
+						canvas.itemPaste.setEnabled(true);
+					}
+				}
+			}
+		};
+		actionMap.put(cntrlCDown, controlC);
+
+		String cntrlVDown = "controlV";
+		inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
+		AbstractAction controlV = new AbstractAction() {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				try {
+					tabTemp = null;
+					if (tabbedPaneOriginal.getMousePosition() != null) {
+						tabTemp = tabbedPaneOriginal;
+					} else {
+					}
+
+					if (tabTemp == null)
+						return;
+					JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+					Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
+
+					if (tabTemp != null && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+
+						controller.paste(((GroupNodeCanvas) canvasOrUpperNodeCanvas).getGroupNode(),
+								canvasOrUpperNodeCanvas.getMousePosition());
+						controller.calculateStateAndVisualForCurrentTimeStep();
+						scrollPane.getViewport().getComponent(0).repaint();
+					} else {
+						controller.paste(null, canvas.getMousePosition());
+						controller.calculateStateAndVisualForCurrentTimeStep();
+						canvas.repaint();
+					}
+				} catch (HeadlessException | JsonParseException | UnsupportedFlavorException | IOException e1) {
+					JLabel message = new JLabel("The Clipboard information cannot be pasted into Application.");
+					JOptionPane.showMessageDialog(holegJFrame, message, "", JOptionPane.ERROR_MESSAGE);
+				}
+
+			}
+		};
+		actionMap.put(cntrlVDown, controlV);
+
+		String cntrlXDown = "controlX";
+		inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
+		AbstractAction controlX = new AbstractAction() {
+			private static final long serialVersionUID = 1L;
+
+			@Override
+			public void actionPerformed(ActionEvent e) {
+				chooseTabTemp();
+				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+				if (!model.getSelectedObjects().isEmpty()) {
+					if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
+						controller.cut(((GroupNodeCanvas) scrollPane.getViewport().getComponent(0)).getGroupNode());
+						controller.calculateStateAndVisualForCurrentTimeStep();
+						scrollPane.getViewport().getComponent(0).repaint();
+					} else {
+						controller.cut(null);
+						controller.calculateStateAndVisualForCurrentTimeStep();
+						canvas.repaint();
+					}
+					if (!model.getClipboradObjects().isEmpty()) {
+						canvas.itemPaste.setEnabled(true);
+					}
+				}
+			}
+		};
+		actionMap.put(cntrlXDown, controlX);
+
+		holegJFrame.setJMenuBar(menuBar);
+
+		holegJFrame.setIconImage(ImageImport.loadImage("/Images/Holeg.png", 30, 30));
+
+		menuBar.add(mnNewMenu);
+
+		mnNewMenu.add(mntmNew);
+
+		mnNewMenu.add(mntmOpen);
+
+		mnNewMenu.add(mntmSave);
+
+		menuBar.add(mnNewMenuEdit);
+
+		mnNewMenuEdit.add(mntmUndo);
+
+		mnNewMenuEdit.add(mntmRedo);
+		mntmFindReplace.addActionListener(actionEvent -> {
+			try {
+				SearchPopUp dialog = new SearchPopUp(controller, canvas, holegJFrame);
+				dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+				dialog.setVisible(true);
+				controller.getObjectsInDepth();
+			} catch (Exception ex) {
+				ex.printStackTrace();
+			}
+		});
+
+		mnNewMenuEdit.add(mntmFindReplace);
+		mnNewMenuEdit.add(mntmEditEdges);
+		mntmEditEdges.addActionListener(actionEvent -> {
+			EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
+			edgePopUp.setCanvas(canvas);
+			edgePopUp.setController(controller);
+			edgePopUp.setVisible(true);
+		});
+
+		// Edit -> Align All
+
+		mnNewMenuEdit.add(mntmAlignAll);
+		mntmAlignAll.addActionListener(actionEvent -> {
+			// getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the
+			// active canvas
+			AbstractCanvas activeCanvas = ((AbstractCanvas) getScrollPaneFromTabbedPane().getViewport()
+					.getComponent(0));
+			if (activeCanvas != null) {
+				activeCanvas.tryToAlignObjects();
+				activeCanvas.repaint();
+			}
+		});
+
+		menuBar.add(mnNewMenuOptions);
+
+		mnNewMenuOptions.add(mntmResetCategory);
+		mntmResetCategory.addActionListener(actionEvent -> {
+			ArrayList<Category> cat = model.getCategories();
+			try {
+				while (!cat.isEmpty()) {
+					controller.deleteCategory(cat.get(0).getName());
+
+				}
+				controller.resetCategorys();
+			} catch (Exception e2) {
+				System.out.println(e2.getMessage());
+			}
+			categoryTree.revalidate();
+			categoryTree.repaint();
+		});
+
+		/**
+		 * Add Fairness Model Option to the option Menu
+		 */
+		mnNewMenuOptions.add(mnFairnessModel);
+
+		mnFairnessModel.add(mntmFairMinFirst);
+		mntmFairMinFirst.setForeground(Color.BLUE);
+		mntmFairMinFirst
+				.setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
+						+ "After that as many HolonObjects as possible will get fully supplied.");
+
+		mntmFairMinFirst.addActionListener(arg0 -> {
+			controller.setFairnessModel(FairnessModel.MininumDemandFirst);
+			mntmFairMinFirst.setForeground(Color.BLUE);
+			mntmFairAlleEqual.setForeground(mnFairnessModel.getForeground());
+			controller.calculateStateAndVisualForCurrentTimeStep();
+			// Update UpperNodes
+			Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane().getViewport().getComponent(0);
+			if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+				((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
+			}
+		});
+
+		mnFairnessModel.add(mntmFairAlleEqual);
+		mntmFairAlleEqual.setToolTipText("HolonObjects will all get the same amount of energy.");
+
+		mntmFairAlleEqual.addActionListener(arg0 -> {
+			controller.setFairnessModel(FairnessModel.AllEqual);
+			mntmFairAlleEqual.setForeground(Color.BLUE);
+			mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
+			controller.calculateStateAndVisualForCurrentTimeStep();
+			// Update UpperNodes
+			Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane().getViewport().getComponent(0);
+			if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+				((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
+			}
+		});
+
+		menuBar.add(mnNewMenuView);
+
+		mnNewMenuView.add(mntmCanvasSize);
+		mntmCanvasSize.addActionListener(actionEvent -> {
+			CanvasResizePopUp popUp = new CanvasResizePopUp(model, controller, canvas, this.tabbedPaneInnerOriginal,
+					holegJFrame);
+			popUp.setVisible(true);
+		});
+
+		tabbedPaneInnerOriginal.addChangeListener(change -> {
+			controller.clearSelection();
+		});
+		mnNewMenuView.add(mntmCanvasSize);
+
+		/*
+		 * Adds Checkbox to turn supply bars on/off
+		 */
+		mnNewMenuView.add(showSupplyBarsCheckBox);
+		showSupplyBarsCheckBox.setSelected(true);
+		showSupplyBarsCheckBox.addActionListener(arg0 -> {
+			controller.setShowSupplyBars(showSupplyBarsCheckBox.isSelected());
+
+			canvas.repaint();
+
+			// Update UpperNodes
+			JScrollPane spane = getScrollPaneFromTabbedPane();
+			if (spane != null) {
+				Component canvasOrUpperNodeCanvas = spane.getViewport().getComponent(0);
+				if (canvasOrUpperNodeCanvas != null && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+					((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
+				}
+			}
+		});
+		initWindowMenu();
+
+		mnNewMenuView.add(mntmBackground);
+
+		mntmBackground.addActionListener(actionEvent -> {
+			tabTemp = tabbedPaneOriginal;
+			JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+
+			if (scrollPane.getViewport().getComponent(0) instanceof Canvas) {
+				BackgroundPopUp backgroundDialog = new BackgroundPopUp(model, controller, canvas, null, holegJFrame);
+				backgroundDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+				backgroundDialog.setVisible(true);
+			} else if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
+				GroupNodeCanvas uNodeCanvas = (GroupNodeCanvas) (scrollPane.getViewport().getComponent(0));
+				BackgroundPopUp backgroundDialog = new BackgroundPopUp(model, controller, null,
+						uNodeCanvas.getGroupNode(), holegJFrame);
+				backgroundDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
+				backgroundDialog.setVisible(true);
+				uNodeCanvas.repaint();
+			}
+		});
+
+		/**
+		 * add Help Menu and its items
+		 */
+		menuBar.add(mnHelp);
+		mnHelp.add(mntmIntroduction);
+		mnHelp.add(mntmUserManual);
+		mnHelp.add(mntmAlgorithmHelp);
+		mnHelp.add(mntmCodeDoc);
+		mnHelp.add(mntmAboutUs);
+
+		canvas.setBackground(Color.WHITE);
+		canvas.setPreferredSize(new Dimension(model.getCanvasX(), model.getCanvasY()));
+		/********************
+		 * RIGHT CONTAINER (INFORMATION)
+		 **********************/
+
+		panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
+		toolBarHolonEl.setFloatable(false);
+		panelHolonEl.add(toolBarHolonEl);
+
+	
+
+
+
+	
+		/***********************
+		 * HolonElement Graph Actions
+		 **********************/
+
+		/*
+		 * Update Local Period of an Element Graph
+		 */
+		unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
+			@Override
+			public void keyReleased(KeyEvent e) {
+				try {
+					int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
+					unitGraphLocalPeriod.setBackground(Color.WHITE);
+					/**
+					 * set local graph Period
+					 */
+					if (e.getKeyCode() == KeyEvent.VK_ENTER)
+						unitGraph.setLocalPeriod(localLength);
+				} catch (NumberFormatException ex) {
+					unitGraphLocalPeriod.setBackground(PALE_RED);
+				}
+
+			}
+		});
+
+		/*****************************
+		 * RIGHT CONTAINER DONE
+		 *****************************/
+
+		holegJFrame.getContentPane().setLayout(new BorderLayout(0, 0));
+		/****************
+		 * Tree Stuff
+		 ****************/
+
+		// Override Key Actions
+		inputMap = categoryTree.getInputMap();
+		inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
+		inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
+		inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
+		inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
+
+		TreeCellRenderer customRenderer = new TreeCellRenderer() {
+			@Override
+			public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded,
+					boolean leaf, int row, boolean hasFocus) {
+				JLabel label = new JLabel();
+				Image imgR;
+				if (leaf) {
+					for (Category cat : model.getCategories()) {
+						for (AbstractCanvasObject cps : cat.getObjects()) {
+							if (value.toString().compareTo(cps.getName()) == 0) {
+								imgR = ImageImport.loadImage(cps.getImage(), 50, 50);
+								if (imgR != null) {
+									label.setIcon(new ImageIcon(imgR));
+								}
+								label.setText(cps.getName());
+							}
+						}
+					}
+				}
+				tree.setRowHeight(50);
+				if (hasFocus) {
+					label.setForeground(new Color(0, 0, 255));
+					label.setOpaque(true);
+				}
+				if (label.getText().length() == 0) {
+					label.setText(value.toString());
+					if (value.toString().compareTo("Categories") != 0) {
+						label.setIcon(new ImageIcon(ImageImport.loadImage("/Images/folder.png")));
+					}
+				}
+
+				return label;
+
+			}
+		};
+
+		categoryTree.setCellRenderer(customRenderer);
+
+		categoryTree.addMouseMotionListener(new MouseMotionAdapter() {
+
+			public void mouseDragged(MouseEvent e) {
+				checkForDragAndDrop(e);
+			}
+
+			/**
+			 * checks if an object of the current Panel could be replaced by the dragged
+			 * object
+			 * 
+			 * @param e
+			 */
+			private void checkForDragAndDrop(MouseEvent e) {
+				try {
+					/**
+					 * if no object gets dragged -> finished
+					 */
+					if (!dragging)
+						return;
+
+					/**
+					 * select the current Panel
+					 */
+					chooseTabTemp();
+					JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+					if (scrollPane == null)
+						return;
+					Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
+
+					/**
+					 * check for replacements on the canvas
+					 */
+					if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+						GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
+						if (unc.getMousePosition() == null)
+							return;
+						int x = (int) unc.getMousePosition().getX() + 16;
+						int y = (int) unc.getMousePosition().getY() + 16;
+
+						/**
+						 * check for replacement
+						 */
+						unc.checkForReplacement(x, y);
+
+						/**
+						 * repaint
+						 */
+						unc.invalidate();
+						unc.repaint();
+					} else {
+						if (canvas.getMousePosition() == null)
+							return;
+						int x = (int) canvas.getMousePosition().getX() + 16;
+						int y = (int) canvas.getMousePosition().getY() + 16;
+
+						/**
+						 * check for replacement
+						 */
+						canvas.checkForReplacement(x, y);
+
+						/**
+						 * repaint
+						 */
+						canvas.invalidate();
+						canvas.repaint();
+					}
+					contentPane.updateUI();
+
+				} catch (Exception eex) {
+					eex.printStackTrace();
+				}
+			}
+		});
+
+		categoryTree.addMouseListener(new MouseAdapter() {
+
+			public void mouseReleased(MouseEvent e) {
+				try {
+					if (dragging) {
+						chooseTabTemp();
+						JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+						Component canvasOrUpperNodeCanvas = scrollPane.getViewport().getComponent(0);
+
+						if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
+							GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
+							int x = (int) unc.getMousePosition().getX() + 16;
+							int y = (int) unc.getMousePosition().getY() + 16;
+
+							AbstractCanvasObject h = null;
+							if (tempCps instanceof HolonObject) {
+								h = new HolonObject((HolonObject) tempCps);
+							}
+							if (tempCps instanceof HolonSwitch) {
+								h = new HolonSwitch(tempCps);
+							}
+							h.setPosition(x, y);
+
+							/**
+							 * close UpperNodeTabs of replaced UpperNode
+							 */
+							if (unc.mayBeReplaced != null && unc.mayBeReplaced instanceof GroupNode) {
+								unc.closeUpperNodeTab(unc.mayBeReplaced.getId());
+							}
+							controller.addObjUpperNode(h, unc.getGroupNode());
+
+							/**
+							 * object would be replaced
+							 */
+							unc.mayBeReplaced = null;
+							unc.invalidate();
+							controller.calculateStateAndVisualForCurrentTimeStep();
+							unc.repaint();
+							unc.setXY((int) canvas.getMousePosition().getX(), (int) canvas.getMousePosition().getY());
+						} else {
+							int x = (int) canvas.getMousePosition().getX() + 16;
+							int y = (int) canvas.getMousePosition().getY() + 16;
+
+							AbstractCanvasObject h = null;
+							if (tempCps instanceof HolonObject) {
+								h = new HolonObject((HolonObject) tempCps);
+							}
+							if (tempCps instanceof HolonSwitch) {
+								h = new HolonSwitch(tempCps);
+							}
+
+							h.setPosition(x, y);
+
+							/**
+							 * close UpperNodeTabs of replaced UpperNode
+							 */
+							if (canvas.mayBeReplaced != null && canvas.mayBeReplaced instanceof GroupNode) {
+								canvas.closeUpperNodeTab(canvas.mayBeReplaced.getId());
+							}
+							controller.addObjectCanvas(h);
+							/**
+							 * no object should get replaced
+							 */
+							canvas.mayBeReplaced = null;
+							canvas.invalidate();
+							canvas.setXY((int) canvas.getMousePosition().getX(),
+									(int) canvas.getMousePosition().getY());
+							canvas.repaint();
+						}
+						controller.calculateStateAndVisualForCurrentTimeStep();
+						contentPane.updateUI();
+						dragging = false;
+					}
+				} catch (Exception eex) {
+				}
+				holegJFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
+			}
+		});
+
+		popmenuEdit.add(editItem);
+		popmenuEdit.add(removeItem);
+		editItem.setEnabled(false);
+		editItem.addActionListener(actionEvent -> {
+		});
+		categoryTree.addMouseListener(new MouseAdapter() {
+
+			public void mousePressed(MouseEvent e) {
+				try {
+					actualObjectClicked = categoryTree.getPathForLocation(e.getX(), e.getY()).getLastPathComponent()
+							.toString();
+					// if an Object was selected, the porperties are shown in
+					// the table
+					DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) categoryTree
+							.getPathForLocation(e.getX(), e.getY()).getLastPathComponent();
+					if (selectedNode.getLevel() == 2) {
+						controller.searchCategoryObject(selectedNode.getParent().toString(), selectedNode.toString());
+						// if (selected instanceof HolonObject && selected !=
+						// null) {
+						// selected = (HolonObject) selected;
+						// fillElementTable(((HolonObject)
+						// selected).getElements());
+						// }
+					}
+					if (SwingUtilities.isRightMouseButton(e)) {
+						for (Category cat : model.getCategories()) {
+							for (AbstractCanvasObject cps : cat.getObjects()) {
+								if (actualObjectClicked.compareTo(cps.getName()) == 0
+										&& !(cps instanceof HolonSwitch)) {
+									editItem.setEnabled(true);
+									popmenuEdit.show(e.getComponent(), e.getX(), e.getY());
+									catOfObjToBeEdited = selectedNode.getParent().toString();
+									tempCps = cps;
+								}
+							}
+						}
+					} else {
+						for (Category cat : model.getCategories()) {
+							for (AbstractCanvasObject cps : cat.getObjects()) {
+								if (actualObjectClicked.compareTo(cps.getName()) == 0) {
+									File checkPath = new File(cps.getImage());
+									if (checkPath.exists()) {
+										img = new ImageIcon(cps.getImage()).getImage().getScaledInstance(32, 32,
+												java.awt.Image.SCALE_SMOOTH);
+									} else {
+										img = ImageImport.loadImage(cps.getImage(), 32, 32);
+									}
+									tempCps = cps;
+									dragging = true;
+									Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(0, 0),
+											"Image");
+									holegJFrame.setCursor(cursor);
+								}
+							}
+						}
+					}
+				} catch (Exception eex) {
+				}
+			}
+		});
+		editItem.addActionListener(actionEvent -> {
+			// Remove the selected Object object
+			// AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame
+			// parentFrame)
+			System.out.println("Edit");
+			addObjectPopUP = new AddObjectPopUp(true, tempCps, catOfObjToBeEdited, holegJFrame);
+			addObjectPopUP.setCategory(catOfObjToBeEdited);
+			addObjectPopUP.setController(controller);
+			addObjectPopUP.setVisible(true);
+		});
+		removeItem.addActionListener(actionEvent -> {
+			// Remove the selected Object object
+			try {
+				System.out.println("catOfObjToBeEdited:" + catOfObjToBeEdited + ", tempCps:" + tempCps);
+				controller.delObjectCategory(catOfObjToBeEdited, tempCps.getName());
+			} catch (IOException e) {
+				System.err.println("IOException");
+				e.printStackTrace();
+			}
+		});
+		scrollPane1.setViewportView(categoryTree);
+
+		scrollPane1.setColumnHeaderView(panel);
+		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
+		toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
+		toolBar.setFloatable(false);
+
+		panel.add(toolBar);
+		btnAddPopUp.add(mItemNew);
+		mItemNew.addActionListener(actionEvent -> {
+			new CreateNewDialog(controller, holegJFrame);
+		});
+		btnAddPopUp.addSeparator();
+		btnAddPopUp.add(mItemCategory);
+		mItemCategory.addActionListener(actionEvent -> {
+			new CreateNewDialog(controller, Option.Category, holegJFrame);
+		});
+		btnAddPopUp.add(mItemObject);
+		mItemObject.addActionListener(actionEvent -> {
+			new CreateNewDialog(controller, Option.Object, holegJFrame);
+		});
+		btnAddPopUp.add(mItemSwitch);
+		mItemSwitch.addActionListener(actionEvent -> {
+			new CreateNewDialog(controller, Option.Switch, holegJFrame);
+		});
+		btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
+		btnAdd.setIcon(new ImageIcon(ImageImport.loadImage("Images/plus.png", 16, 16)));
+		btnAdd.setToolTipText("<html><b>New</b><br>Add a new Category or Item to the library.</html>");
+		toolBar.add(btnAdd);
+		/**
+		 * Help Menu Action Listeners
+		 */
+
+		/**
+		 * URL of the telecommunication git Wiki
+		 */
+		String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
+
+		/** open Introduction Web Page */
+		mntmIntroduction.addMouseListener(new MouseAdapter() {
+			@Override
+			public void mousePressed(MouseEvent e) {
+				openWebpage(tkWikiWebpage + "Introduction+V2.1");
+			}
+		});
+
+		/** open UserManual WebPage */
+		mntmUserManual.addMouseListener(new MouseAdapter() {
+			@Override
+			public void mousePressed(MouseEvent e) {
+				openWebpage(tkWikiWebpage + "User+Manual+V2.1");
+			}
+		});
+
+		/** open Algorithm Help Web Page */
+		mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
+			@Override
+			public void mousePressed(MouseEvent e) {
+				openWebpage(tkWikiWebpage + "Algorithms+V2.1");
+			}
+		});
+
+		/** open Code Documentation Web Page */
+		mntmCodeDoc.addMouseListener(new MouseAdapter() {
+			@Override
+			public void mousePressed(MouseEvent e) {
+				openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
+			}
+		});
+
+		/**
+		 * Pop up - About Us with some important information about the developers,
+		 * source and programming stuff
+		 */
+		mntmAboutUs.addMouseListener(new MouseAdapter() {
+			@Override
+			public void mousePressed(MouseEvent e) {
+				aboutUsPopUp = new AboutUsPopUp(holegJFrame);
+				aboutUsPopUp.setVisible(true);
+			}
+		});
+		// Del Button
+		btnDel.addActionListener(actionEvent -> {
+			Object nodeInfo = categoryTree.getLastSelectedPathComponent();
+			if (nodeInfo != null) {
+				DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
+				String nodeName = selectedNode.getUserObject().toString();
+				int depthOfNode = selectedNode.getLevel();
+				try {
+					switch (depthOfNode) {
+					case 1:
+						int dialogResult = JOptionPane.showConfirmDialog(holegJFrame, eraseCategory + nodeName + "?",
+								warningText, JOptionPane.YES_NO_OPTION);
+						if (dialogResult == JOptionPane.YES_OPTION) {
+							controller.deleteCategory(nodeName);
+						}
+						break;
+					case 2:
+						DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
+						controller.delObjectCategory(parent.getUserObject().toString(), nodeName);
+						break;
+
+					default:
+						JOptionPane.showMessageDialog(holegJFrame, selectObjBeforeErase);
+					}
+				} catch (Exception e2) {
+				}
+
+			} else {
+				JOptionPane.showMessageDialog(holegJFrame, selectObjBeforeErase);
+			}
+			categoryTree.repaint();
+		});
+		btnDel.setIcon(new ImageIcon(ImageImport.loadImage("Images/minus.png", 16, 16)));
+		btnDel.setToolTipText("<html><b>Delete</b><br>Removes a Category or a Category Item.</html>");
+		toolBar.add(btnDel);
+
+		holegJFrame.getContentPane().add(splitPane);
+
+		mntmNew.addActionListener(actionEvent -> {
+			if (model.getObjectsOnCanvas().size() != 0) {
+				int newWarning = JOptionPane.YES_NO_OPTION;
+				int dialogForNewWarning = JOptionPane.showConfirmDialog(holegJFrame, saveBeforeNew, warningText,
+						newWarning);
+				if (dialogForNewWarning == JOptionPane.YES_OPTION) {
+					mntmSave.doClick();
+				}
+			}
+			// Remove all but main tab
+			while (tabbedPaneInnerOriginal.getTabCount() > 1) {
+				tabbedPaneInnerOriginal.remove(1);
+			}
+			controller.clearSelection();
+			model.getEdgesOnCanvas().clear();
+			model.getObjectsOnCanvas().clear();
+			controller.OnSelectionChanged.broadcast();
+			controller.setSelectedObjectID(0);
+			controller.setSelecteEdge(null);
+			controller.setCurIteration(0);
+			elementGraph.setText("None");
+			canvas.tempCps = null;
+			canvas.repaint();
+			IdCounter.resetObjectCounter(CounterType.Object);
+			IdCounter.resetObjectCounter(CounterType.Element);
+			controller.calculateStateAndVisualForCurrentTimeStep();
+		});
+
+		mntmOpen.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent evt) {
+				menuFileExitActionPerformed();
+			}
+
+			private void menuFileExitActionPerformed() {
+				JFileChooser fileChooser = new JFileChooser();
+				fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir") + "/exampleNetworks/"));
+				FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
+				fileChooser.setFileFilter(holonFilter);
+
+				if (fileChooser.showOpenDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
+					File file = fileChooser.getSelectedFile();
+
+					try {
+						while (tabbedPaneInnerOriginal.getTabCount() > 1) {
+							tabbedPaneInnerOriginal.remove(1);
+						}
+						model.getSelectedObjects().clear();
+						controller.loadFile(file.getAbsolutePath());
+						canvas.repaint();
+						categoryTree.repaint();
+						controller.calculateStateAndVisualForCurrentTimeStep();
+					} catch (IOException | ArchiveException e) {
+						e.printStackTrace();
+						JLabel message = new JLabel("The savefile is corrupt and cannot be opened.");
+						JOptionPane.showMessageDialog(holegJFrame, message, "", JOptionPane.ERROR_MESSAGE);
+					}
+				}
+			}
+		});
+
+		mntmSave.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent evt) {
+				menuSaveActionPerformed();
+			}
+
+			private void menuSaveActionPerformed() {
+				JFileChooser fileChooser = new JFileChooser();
+				FileNameExtensionFilter holonFilter = new FileNameExtensionFilter("Holon Save File(*.holon)", "holon");
+				fileChooser.setFileFilter(holonFilter);
+
+				if (fileChooser.showSaveDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
+					File selectedFile = fileChooser.getSelectedFile();
+					String fileName = selectedFile.getName();
+					String fullPath = fileChooser.getSelectedFile().getPath();
+					if (fileChooser.getFileFilter().equals(holonFilter)) {
+						if (!fileName.contains("."))
+							fullPath += ".holon";
+					}
+					if (!fullPath.endsWith(".holon")) {
+						String suffix = fullPath.substring(fullPath.lastIndexOf("."), fullPath.length());
+						String[] options = new String[] { "keep .holon", "use " + suffix };
+
+						JLabel message = new JLabel(
+								"Are you sure to use the extension \"" + suffix + "\" instead of \".holon\"?");
+
+						int response = JOptionPane.showOptionDialog(holegJFrame, message, "",
+								JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1]);
+
+						if (response == 0)
+							fullPath = fullPath.replace(suffix, ".holon");
+					}
+
+					try {
+						controller.saveFile(new File(fullPath).getAbsolutePath());
+					} catch (IOException | ArchiveException e) {
+						e.printStackTrace();
+					}
+				}
+			}
+		});
+
+		mntmUndo.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent evt) {
+				menuUndoActionPerformed();
+			}
+
+			private void menuUndoActionPerformed() {
+				try {
+					controller.loadAutoSave(controller.getUndoSave());
+
+					closeInvalidUpperNodeTabs();
+
+					controller.calculateStateAndVisualForCurrentTimeStep();
+					canvas.repaint();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+			}
+		});
+
+		mntmRedo.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent evt) {
+				menuRedoActionPerformed();
+			}
+
+			private void menuRedoActionPerformed() {
+				try {
+					controller.loadAutoSave(controller.getRedoSave());
+
+					closeInvalidUpperNodeTabs();
+
+					controller.calculateStateAndVisualForCurrentTimeStep();
+					canvas.repaint();
+				} catch (IOException e) {
+					e.printStackTrace();
+				}
+			}
+		});
+
+		timePanel = new TimePanel(controller);
+		timePanel.setBorder(null);
+		timePanel.getTimeSlider().addChangeListener(changeEvent -> {
+			// TimeSliderChanged event
+			controller.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
+			unitGraph.repaint();
+			contentPane.updateUI();
+		});
+		splitPane1.setMinimumSize(new Dimension(0, 25));
+		splitPane.setRightComponent(splitPane1);
+		splitPane.setDividerLocation(200);
+		splitPane1.setDividerLocation(500);
+
+		splitPane.setLeftComponent(scrollPane1);
+		tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
+
+		myPanel.add(canvasSP, BorderLayout.CENTER);
+
+		tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
+		splitPane1.setLeftComponent(tabbedPaneOriginal);
+		splitPane1.setRightComponent(splitHolonElPro);
+
+		splitPane1.setResizeWeight(0.9);
+
+		splitHolonElPro.setDividerLocation(700);
+		// containing the graph and the elements-list
+		splitHolonElPro.setTopComponent(splitGraphHolonEl);
+		// containing the object's properties
+		splitHolonElPro.setBottomComponent(scrollProperties);
+
+		splitGraphHolonEl.setTopComponent(inspector);
+		splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
+		canvasSP.setViewportView(canvas);
+
+		tabbedPaneOriginal.setBorder(null);
+		scrollProperties.setBorder(null);
+		splitPane.setBorder(null);
+		splitPane1.setBorder(null);
+		splitHolonElPro.setBorder(null);
+		splitGraphHolonEl.setBorder(null);
+		panelHolonEl.setBorder(null);
+		canvasSP.setBorder(null);
+
+		holegJFrame.getContentPane().add(timePanel, BorderLayout.SOUTH);
+
+		try {
+			controller.loadAutoSave(System.getProperty("user.home") + "/.config/HolonGUI/Category/Category.json");
+		} catch (IOException e1) {
+		}
+
+		String autoPath = System.getProperty("user.home") + "/.config/HolonGUI/Autosave/";
+		File dest = new File(autoPath);
+		ArrayList<File> oldAutoSaves = controller.filterOldAutoSaveFiles();
+		int nrOfOldSaves = oldAutoSaves.size();
+
+		if (nrOfOldSaves > 0) {
+			int dialogButton = JOptionPane.YES_NO_OPTION;
+			int dialogResult = JOptionPane.showConfirmDialog(holegJFrame,
+					"Old autosave file was found, should it be loaded?", warningText, dialogButton);
+			if (dialogResult == JOptionPane.YES_OPTION) {
+				if (dest.exists()) {
+					model.setAutoSaveNr(nrOfOldSaves - 1);
+					mntmRedo.doClick();
+				} else {
+					JOptionPane.showMessageDialog(holegJFrame, "Autosave could not be loaded.");
+					setUpAutoSave(dest);
+				}
+			} else {
+				setUpAutoSave(dest);
+			}
+
+			// after all: delete the obsolete/old autosave files from the
+			// directory
+			controller.deleteObsoleteAutoSaveFiles();
+		}
+
+		canvasSP.addComponentListener(new ComponentAdapter() {
+			@Override
+			public void componentResized(ComponentEvent e) {
+				controller.setCanvasX(Math.max(model.getCanvasX(), canvasSP.getViewport().getWidth()));
+				controller.setCanvasY(Math.max(model.getCanvasY(), canvasSP.getViewport().getHeight()));
+				canvas.repaint();
+			}
+		});
+	}
+
+	private void initWindowMenu() {
+		menuBar.add(menuWindow);
+		// Algo
+		JMenuItem openMenu = new JMenuItem("Open Algorithm Panel", new ImageIcon(ImageImport
+				.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openMenu.addActionListener(actionEvent -> {
+			new AddOnWindow(holegJFrame, controller);
+		});
+		openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
+		menuWindow.add(openMenu);
+		// Outliner
+		JMenuItem openOutliner = new JMenuItem("Open Outliner", new ImageIcon(ImageImport
+				.loadImage("/Button_Images/iconOutliner.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openOutliner.addActionListener(actionEvent -> {
+			outlinerList.add(new Outliner(holegJFrame, model, controller));
+		});
+		openOutliner
+				.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
+		menuWindow.add(openOutliner);
+		// FlexWindow
+		JMenuItem openFlexMenuItem = new JMenuItem("Open Flexibility Panel", new ImageIcon(ImageImport
+				.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
+		openFlexMenuItem.addActionListener(actionEvent -> {
+			flexList.add(new FlexWindow(holegJFrame, controller));
+		});
+		openFlexMenuItem
+				.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()));
+		menuWindow.add(openFlexMenuItem);
+	}
+
+	public void updateOutliners(DecoratedState state) {
+		// remove closed Outliner
+		ListIterator<Outliner> iter = outlinerList.listIterator();
+		while (iter.hasNext()) {
+			if (iter.next().isClosed)
+				iter.remove();
+		}
+		// update open Outliner
+		for (Outliner out : outlinerList) {
+			out.repaintWithDecoratedState(state);
+		}
+	}
+
+	public void updateFlexWindows() {
+		// remove closed Outliner
+		ListIterator<FlexWindow> iter = flexList.listIterator();
+		while (iter.hasNext()) {
+			if (iter.next().isClosed)
+				iter.remove();
+		}
+		// update open Flex
+		for (FlexWindow out : flexList) {
+			out.update();
+		}
+	}
+	private boolean isUpperPanelInsideBounds() {
+		int x = holegJFrame.getX();
+		int y = holegJFrame.getY();
+		int width = holegJFrame.getWidth();
+
+		// get all connected screen devices
+		GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
+		boolean isUpperPanelVisible = false;
+
+		// and check whether they contain the upper left or upper right point of
+		// the frame
+		for (GraphicsDevice device : screenDevices) {
+			Rectangle bounds = device.getDefaultConfiguration().getBounds();
+			if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
+				isUpperPanelVisible = true;
+				break;
+			}
+		}
+
+		return isUpperPanelVisible;
+	}
+
+	/**
+	 * Sets up autosave if no old one is loaded at the beginning
+	 *
+	 * @param dest path to save-folder
+	 */
+	private void setUpAutoSave(File dest) {
+		dest.mkdirs();
+		try {
+			controller.autoSave();
+		} catch (IOException e1) {
+			e1.printStackTrace();
+		}
+	}
+
+	/**
+	 * reloads the Categories from Model.
+	 *
+	 * @param categories the current categories
+	 */
+	private void updateCategories(final ArrayList<Category> categories) {
+		DefaultTreeModel treemodel = new DefaultTreeModel(new DefaultMutableTreeNode("Categories") {
+
+			private static final long serialVersionUID = 1L;
+
+			{
+				DefaultMutableTreeNode node1;
+				for (Category c : categories) {
+					node1 = new DefaultMutableTreeNode(c.getName());
+
+					for (AbstractCanvasObject obj : c.getObjects()) {
+						node1.add(new DefaultMutableTreeNode(obj.getName()));
+					}
+					add(node1);
+				}
+
+			}
+		});
+		categoryTree.setModel(treemodel);
+	}
+
+	/**
+	 * When changes are made to the Categories.
+	 *
+	 * @param categories the Categories
+	 */
+	public void updateCategoryUI(ArrayList<Category> categories) {
+		DefaultTreeModel model = (DefaultTreeModel) categoryTree.getModel();
+		updateCategories(categories);
+		model.reload();
+	}
+
+	void setVisible(boolean value) {
+		holegJFrame.setVisible(value);
+	}
+
+	/*
+	 * Open a new Tab with an UpperNodeCanvas
+	 */
+	public void openNewUpperNodeTab(GroupNode node) {
+		chooseTabTemp();
+
+		JScrollPane scrollPane = getScrollPaneFromTabbedPane();
+		if (scrollPane.getViewport().getComponent(0) instanceof Canvas) {
+			unc = new GroupNodeCanvas(model, controller, unitGraph, node, "",
+					scrollPane.getViewport().getComponent(0));
+
+		} else {
+			unc = new GroupNodeCanvas(model, controller, unitGraph, node,
+					((GroupNodeCanvas) scrollPane.getViewport().getComponent(0)).getParentPath() + " -> ",
+					scrollPane.getViewport().getComponent(0));
+		}
+
+		// check if tab already open for clicked NodeOfNode
+		boolean dupl = false;
+
+		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
+			JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
+			if (paneOriginal != null && ((GroupNodeCanvas) paneOriginal.getViewport().getComponent(0)).getGroupNode()
+					.getId() == node.getId()) {
+				dupl = true;
+				// set selected component to view
+				tabbedPaneOriginal.setSelectedComponent(tabbedPaneInnerOriginal);
+				// set selected tab in view to found upper-node-canvas
+				tabbedPaneInnerOriginal.setSelectedComponent(tabbedPaneInnerOriginal.getComponentAt(i));
+			}
+
+			// if we found a duplicate, break
+			if (dupl) {
+				break;
+			}
+		}
+		if (!dupl) {
+			JScrollPane sp = new JScrollPane(unc);
+			sp.setBorder(null);
+
+			// Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
+			if (tabTemp == tabbedPaneOriginal) {
+				this.tabbedPaneInnerOriginal.add(node.getName(), sp);
+				this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
+				this.tabbedPaneInnerOriginal.setTabComponentAt(this.tabbedPaneInnerOriginal.getTabCount() - 1,
+						new ButtonTabComponent(this.tabbedPaneInnerOriginal));
+
+			}
+		}
+	}
+
+	// TODO refactor tabbedPane and access to groupNodeViews
+	private void updateUpperNodes() {
+		for (Component c : tabbedPaneInnerOriginal.getComponents()) {
+			if (!(c instanceof JScrollPane)) {
+				continue;
+			}
+			Component pane = ((JScrollPane) c).getViewport().getComponent(0);
+			if (pane instanceof GroupNodeCanvas) {
+				temp = model.getHashcodeMap().get(((GroupNodeCanvas) pane).hashCode());
+				((GroupNodeCanvas) pane).setGroupNode((GroupNode) temp);
+			}
+		}
+	}
+
+	/**
+	 * Removes UpperNodeTab if UpperNode was deleted
+	 *
+	 * @param cps the CPS object that is currently selected
+	 */
+	private void removeUpperNodeTab(AbstractCanvasObject cps) {
+		if (cps instanceof GroupNode) {
+			for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
+				JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
+
+				if (scrollPaneOriginal == null) {
+				} else if (((GroupNodeCanvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode()
+						.getId() == cps.getId()) {
+					((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
+					break;
+				}
+			}
+		}
+	}
+
+	/**
+	 * chooses whether to set the tabTemp to tabbedPaneOriginal or tabbedPaneSplit
+	 */
+	private void chooseTabTemp() {
+		// TODO Remove tabTabbed
+		tabTemp = tabbedPaneOriginal;
+	}
+
+	private JScrollPane getScrollPaneFromTabbedPane() {
+		return getScrollPaneFromTabbedPane(-1);
+	}
+
+	private JScrollPane getScrollPaneFromTabbedPane(int index) {
+		Component upperLevelSelectedComponent;
+		if (tabTemp == null) {
+			return null;
+		}
+		if (index == -1) {
+			upperLevelSelectedComponent = tabTemp.getSelectedComponent();
+		} else {
+			upperLevelSelectedComponent = tabTemp.getComponentAt(index);
+		}
+		if (upperLevelSelectedComponent instanceof JTabbedPane) {
+			Component nextLevel = ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
+			if (nextLevel instanceof JPanel)
+				return (JScrollPane) ((JPanel) nextLevel).getComponent(0);
+			else
+				return (JScrollPane) nextLevel;
+
+		} else if (upperLevelSelectedComponent instanceof JScrollPane) {
+			return (JScrollPane) upperLevelSelectedComponent;
+		} else {
+			return null;
+		}
+	}
+
+	
+
+
+	private void openWebpage(String URL) {
+		try {
+			java.awt.Desktop.getDesktop().browse(new URI(URL));
+		} catch (Exception e) {
+			e.printStackTrace();
+		}
+	}
+
+	/**
+	 * closes all UpperNodeTabs, that don't have a valid UpperNode (e.g. if it was
+	 * ungrouped/deleted/replaced and so on)
+	 */
+	private void closeInvalidUpperNodeTabs() {
+		/**
+		 * close bugged Tabs
+		 */
+		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
+			JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
+			if (((GroupNodeCanvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode() == null) {
+				((ButtonTabComponent) tabbedPaneInnerOriginal.getTabComponentAt(i)).removeTabs();
+				break;
+			}
+		}
+	}
+
+	public void repaintCanvas() {
+		tabbedPaneInnerOriginal.revalidate();
+		tabbedPaneInnerOriginal.repaint();
+		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
+			JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
+			scrollPaneOriginal.revalidate();
+		}
+	}
+
+	/**
+	 * TODO: Class should be reworked as soon as possible!
+	 * 
+	 * @param state
+	 */
+	public void guiDisable(boolean state) {
+		canvas.disabled = state;
+		for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
+			JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal.getComponentAt(i);
+			if (((GroupNodeCanvas) scrollPaneOriginal.getViewport().getComponent(0)).getGroupNode() != null) {
+				((GroupNodeCanvas) scrollPaneOriginal.getViewport().getComponent(0)).disabled = state;
+			}
+		}
+	}
+}

+ 54 - 0
src/ui/view/main/Main.java

@@ -0,0 +1,54 @@
+package ui.view.main;
+
+import ui.controller.Control;
+import ui.controller.IndexTranslator;
+import ui.model.Model;
+
+import javax.swing.*;
+
+import java.awt.*;
+import java.util.Locale;
+
+/**
+ * The main Class in this Program. The GUI is created in this Class.
+ * 
+ * @author Gruppe14
+ * 
+ */
+public class Main {
+
+	/**
+	 * main method of this program.
+	 * 
+	 * @param args standard
+	 */
+	public static void main(String[] args) {
+		setLookAndFeel();
+		setLocale();
+		EventQueue.invokeLater(() -> {
+				Model model = new Model();
+				Control control = new Control(model);
+				GUI view = new GUI(control);
+				IndexTranslator.model = model;
+				view.setVisible(true);
+		});
+	}
+
+	private static void setLocale() {
+		Locale.setDefault(Locale.US);
+	}
+
+	/**
+	 * This method loads the System LookAndFeel. Except for Linux OS.
+	 */
+	private static void setLookAndFeel() {
+		try {
+			if (!System.getProperty("os.name").startsWith("Linux")) {
+				UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
+			}
+		} catch (ClassNotFoundException | InstantiationException | IllegalAccessException
+				| UnsupportedLookAndFeelException e) {
+		}
+	}
+
+}

+ 11 - 18
src/ui/view/TimePanel.java → src/ui/view/main/TimePanel.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.main;
 
 import java.awt.BorderLayout;
 import java.awt.Color;
@@ -116,20 +116,13 @@ public class TimePanel extends JPanel implements ActionListener{
 		super();
 		this.controller = cont;
 		// One Iteration
-		timer = new Timer(0, new ActionListener() {//TODO: Merge all these damned listeners.
+		timer = new Timer(0, new ActionListener() {
 			@Override
 			public void actionPerformed(ActionEvent ae) {
 				timeSlider.setValue(timeSlider.getValue() + 1);
 				controller.setCurIteration(timeSlider.getValue());
 				timer.setDelay(cont.getModel().getTimerSpeed());
-				if (timeSlider.getValue() >= cont.getModel().getIterations() - 1) {
-					/*/calc and print performance
-					performanceTime = System.nanoTime()-performanceTime;
-					
-					System.out.println(performanceTime/1000000000 + " Sekunden "
-							+ (performanceTime%1000000000)/1000000 + " Millisekunden "
-							+ (performanceTime%1000000)/1000 + " Mikrosekunden ");
-					//*/
+				if (timeSlider.getValue() >= cont.getModel().getMaxIterations() - 1) {
 					running = false;
 					playBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/play.png", 30, 30)));
 					timer.stop();
@@ -143,24 +136,24 @@ public class TimePanel extends JPanel implements ActionListener{
 		// Slider
 		timeSlider.setPaintTicks(true);
 		timeSlider.setPaintLabels(true);
-		timeSlider.setMajorTickSpacing((int)Math.ceil(((double)cont.getModel().getIterations())/20));
-		timeSlider.setMinorTickSpacing((int)Math.ceil(((double)cont.getModel().getIterations())/100));
+		timeSlider.setMajorTickSpacing((int)Math.ceil(((double)cont.getModel().getMaxIterations())/20));
+		timeSlider.setMinorTickSpacing((int)Math.ceil(((double)cont.getModel().getMaxIterations())/100));
 		timeSlider.setToolTipText("Time Slider");
-		timeSlider.setMaximum(cont.getModel().getIterations() - 1);
+		timeSlider.setMaximum(cont.getModel().getMaxIterations() - 1);
 		timeSlider.setValue(0);
 		timeSlider.addChangeListener(changeEvent -> controller.setCurIteration(timeSlider.getValue()));
 
 		timeSlider.addMouseListener(new MouseAdapter() {
 			@Override
 			public void mousePressed(MouseEvent e) {
-				dragResetIteration = cont.getModel().getCurIteration();
+				dragResetIteration = cont.getModel().getCurrentIteration();
 			}
 		});
 
 		timeSlider.addMouseMotionListener(new MouseAdapter() {
 			@Override
 			public void mouseDragged(MouseEvent e) {
-				if (dragResetIteration != cont.getModel().getCurIteration()) {
+				if (dragResetIteration != cont.getModel().getCurrentIteration()) {
 					if (running) {
 						playBtn.doClick();
 					}
@@ -182,7 +175,7 @@ public class TimePanel extends JPanel implements ActionListener{
 		playBtn.addActionListener(new ActionListener() {
 			@Override
 			public void actionPerformed(ActionEvent e) {
-				if(cont.getModel().getCurIteration()==cont.getModel().getIterations()-1)timeSlider.setValue(timeSlider.getMinimum());
+				if(cont.getModel().getCurrentIteration()==cont.getModel().getMaxIterations()-1)timeSlider.setValue(timeSlider.getMinimum());
 				running = !running;
 				if (running) {
 					timer.setDelay(cont.getModel().getTimerSpeed());
@@ -303,7 +296,7 @@ public class TimePanel extends JPanel implements ActionListener{
 		hint.setForeground(Color.red);
 		hint.setText(" ");
 		iterationsField=new JTextField(6);//Considering hundreds of thousands in an extreme case
-		iterationsField.setText(""+cont.getModel().getIterations());
+		iterationsField.setText(""+cont.getModel().getMaxIterations());
 		iterationsField.setToolTipText("0-" + MAX_ITERATIONS  );
 		iterationsField.addActionListener(this);
 		ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(1);
@@ -397,7 +390,7 @@ public class TimePanel extends JPanel implements ActionListener{
 			else resetField=false;
 			if(resetField)iterationsField.setText(""+iterations);
 			controller.getModel().setIterations(Integer.parseInt(iterationsField.getText()));
-			timeSlider.setMaximum(controller.getModel().getIterations()-1);
+			timeSlider.setMaximum(controller.getModel().getMaxIterations()-1);
 			timeSlider.setLabelTable(null);//Otherwise the ticks won't update
 			timeSlider.setMajorTickSpacing((int)Math.ceil(((double)iterations)/20));
 			timeSlider.setMinorTickSpacing((int)Math.ceil(((double)iterations)/100));//Even though the final mark can't actually be reached.

+ 2 - 2
src/ui/view/AddOnWindow.java → src/ui/view/window/AddOnWindow.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.window;
 
 import java.awt.BorderLayout;
 import java.awt.Dimension;
@@ -33,7 +33,7 @@ public class AddOnWindow extends JFrame{
 	private AddOn actual;
 	private Control control;
 	private JPanel content = new JPanel();
-	AddOnWindow(JFrame parentFrame, Control control){
+	public AddOnWindow(JFrame parentFrame, Control control){
 		this.control = control;
 		this.setTitle("Add-Ons");
 		this.setVisible(true);

+ 3 - 3
src/ui/view/FlexWindow.java → src/ui/view/window/FlexWindow.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.window;
 
 import java.awt.BorderLayout;
 import java.awt.Color;
@@ -478,7 +478,7 @@ public class FlexWindow extends JFrame {
 		Flexibility toDeleteFlex =(Flexibility) JOptionPane.showInputDialog(this, "Select to Delete Flexibility:", "Flexibility?",  JOptionPane.OK_OPTION,new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)) , allFlexes, "");
 		if(toDeleteFlex != null) {
 			toDeleteFlex.getElement().flexList.remove(toDeleteFlex);
-			controller.getSimManager().calculateStateForTimeStep(model.getCurIteration(), true);
+			controller.getSimManager().calculateStateForTimeStep(model.getCurrentIteration(), true);
 			updateSelectedPanel();
 		}
 	}
@@ -701,7 +701,7 @@ public class FlexWindow extends JFrame {
 			
 			
 			//if(!model.getSelectedCpsObjects().contains(holonObjectSelector.getSelectedItem()))model.getSelectedCpsObjects().add((AbstractCpsObject)holonObjectSelector.getSelectedItem());
-			controller.getSimManager().calculateStateForTimeStep(model.getCurIteration(), true);
+			controller.getSimManager().calculateStateForTimeStep(model.getCurrentIteration(), true);
 			
 			update();
 			addDialog.dispose();

+ 2 - 6
src/ui/view/Outliner.java → src/ui/view/window/Outliner.java

@@ -1,4 +1,4 @@
-package ui.view;
+package ui.view.window;
 
 import java.awt.BorderLayout;
 import java.awt.Color;
@@ -41,7 +41,7 @@ public class Outliner extends JFrame {
 	JPanel statePanel = new JPanel(new BorderLayout());
 	public boolean isClosed = false;
 	ArrayList<MinimumNetwork> list;
-	Outliner(JFrame parentFrame, Model model, Control controller){ 
+	public Outliner(JFrame parentFrame, Model model, Control controller){ 
 		setBounds(0, 0, 400, parentFrame.getHeight());
 		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png", 30, 30));
 		this.setTitle("Outliner");
@@ -165,25 +165,21 @@ public class Outliner extends JFrame {
 
 		@Override
 		public void treeNodesChanged(TreeModelEvent tmE) {
-			// TODO Auto-generated method stub
 			System.out.println("treeNodesChanged");
 		}
 
 		@Override
 		public void treeNodesInserted(TreeModelEvent tmE) {
-			// TODO Auto-generated method stub
 			System.out.println("treeNodesInserted");
 		}
 
 		@Override
 		public void treeNodesRemoved(TreeModelEvent tmE) {
-			// TODO Auto-generated method stub
 			System.out.println("treeNodesRemoved");
 		}
 
 		@Override
 		public void treeStructureChanged(TreeModelEvent tmE) {
-			// TODO Auto-generated method stub
 			System.out.println("treeStructureChanged");
 		}
 	

+ 1 - 1
src/utility/Action.java → src/utility/events/Action.java

@@ -1,4 +1,4 @@
-package utility;
+package utility.events;
 
 import java.util.HashSet;
 import java.util.Set;

+ 1 - 1
src/utility/Event.java → src/utility/events/Event.java

@@ -1,4 +1,4 @@
-package utility;
+package utility.events;
 import java.util.HashSet;
 import java.util.Set;
 

+ 16 - 0
src/utility/events/LostFocusListener.java

@@ -0,0 +1,16 @@
+package utility.events;
+
+import java.awt.event.FocusEvent;
+import java.awt.event.FocusListener;
+
+@FunctionalInterface
+public interface LostFocusListener extends FocusListener {
+	void update(FocusEvent e);
+	
+	default void focusGained(FocusEvent e) {
+	}
+
+	default void focusLost(FocusEvent e) {
+		update(e);
+	}
+}

+ 24 - 0
src/utility/events/SimpleDocumentListener.java

@@ -0,0 +1,24 @@
+package utility.events;
+
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+
+@FunctionalInterface
+public interface SimpleDocumentListener extends DocumentListener {
+    void update(DocumentEvent e);
+
+    @Override
+    default void insertUpdate(DocumentEvent e) {
+        update(e);
+    }
+    @Override
+    default void removeUpdate(DocumentEvent e) {
+        update(e);
+    }
+    @Override
+    default void changedUpdate(DocumentEvent e) {
+        update(e);
+    }
+}
+
+

+ 1 - 1
tests/tests/PraktikumHolonsAdapter.java

@@ -44,7 +44,7 @@ public class PraktikumHolonsAdapter {
 	 */
 	public void generateElements(ArrayList<HolonElement> arr) {
 		for (int i = 1; i < 18279; i++) {
-			arr.add(new HolonElement(null, generate(i), 1, 10, IdCounter.nextId(CounterType.Element)));
+			arr.add(new HolonElement(null, generate(i), 1, IdCounter.nextId(CounterType.Element)));
 		}
 	}
 	

+ 3 - 3
tests/tests/PraktikumHolonsTestCanvasController.java

@@ -198,9 +198,9 @@ public class PraktikumHolonsTestCanvasController {
 
 		
 		assertTrue("Clipboard not empty", model.getClipboradObjects().isEmpty());
-		model.getSelectedCpsObjects().add(a);
-		model.getSelectedCpsObjects().add(b);
-		model.getSelectedCpsObjects().add(c);
+		model.getSelectedObjects().add(a);
+		model.getSelectedObjects().add(b);
+		model.getSelectedObjects().add(c);
 		//controller.copyObjects();
 		//assertTrue("Clipboard empty", !model.getClipboradObjects().isEmpty());
 	

+ 6 - 6
tests/tests/PraktikumHolonsTestCategoryController.java

@@ -43,7 +43,7 @@ public class PraktikumHolonsTestCategoryController {
 		assertTrue("Number of Categories is not 3", model.getCategories().size() == 3);
 		assertTrue("Second Category is not Building", model.getCategories().get(1).getName().equals("Building"));
 		assertTrue("Category Building is Empty", !model.getCategories().get(1).getObjects().isEmpty());
-		assertEquals("Object is not a Power Plant", mp.searchCat("Energy").getObjects().get(0).getObjName(),
+		assertEquals("Object is not a Power Plant", mp.searchCat("Energy").getObjects().get(0).getName(),
 				"Power Plant");
 		assertFalse("A Switch should not be a Holon Object",
 				mp.searchCatObj(mp.searchCat("Component"), "Switch") instanceof HolonObject);
@@ -126,18 +126,18 @@ public class PraktikumHolonsTestCategoryController {
 		assertTrue("Number of Objects in Energy is not 4", mp.searchCat("Energy").getObjects().size() == 4);
 		assertTrue("Number of Object-Indices in Energy is not 4", mp.searchCat("Energy").getObjIdx().size() == 4);
 		assertTrue("Object was not renamed to \"Power Plant_0\" ",
-				mp.searchCat("Energy").getObjects().get(1).getObjName().equals("Power Plant_0"));
+				mp.searchCat("Energy").getObjects().get(1).getName().equals("Power Plant"));
 		assertTrue("Object was not renamed to \"Power Plant_1\" ",
-				mp.searchCat("Energy").getObjects().get(2).getObjName().equals("Power Plant_1"));
+				mp.searchCat("Energy").getObjects().get(2).getName().equals("Power Plant"));
 		assertTrue("3th Object was not \"Power Plant_1\"",
-				mp.searchCat("Energy").getObjects().get(2).getName().equals("Power Plant_1"));
+				mp.searchCat("Energy").getObjects().get(2).getName().equals("Power Plant"));
 		controller.deleteObject("Energy", "Power Plant_1");
 		assertTrue("3th Object was not deleted",
 				mp.searchCat("Energy").getObjects().get(2).getName().equals("Solar Plant"));
 		assertTrue("Number of Objects in Energy is not 3", mp.searchCat("Energy").getObjects().size() == 3);
 		controller.addNewHolonObject(mp.searchCat("Energy"), "Solar Plant", null, "");
 		assertTrue("Object was not renamed to \"Solar Plant_0\" ",
-				mp.searchCat("Energy").getObjects().get(3).getObjName().equals("Solar Plant_0"));
+				mp.searchCat("Energy").getObjects().get(3).getName().equals("Solar Plant_0"));
 		assertTrue("Number of Objects in Energy is not 4", mp.searchCat("Energy").getObjects().size() == 4);
 	}
 
@@ -155,7 +155,7 @@ public class PraktikumHolonsTestCategoryController {
 			assertTrue("Objects were not added", mp.searchCat("Energy").getObjects().size() == i * 2 + 1);
 
 			assertTrue("Object was not renamed to \"" + adapter.generate(i) + "_0\"", mp.searchCat("Energy")
-					.getObjects().get(i * 2).getObjName().equals(adapter.generate(i) + "_0"));
+					.getObjects().get(i * 2).getName().equals(adapter.generate(i) + "_0"));
 		}
 		//deleting the duplicates
 		controller.deleteObject("Energy", "E_0");

+ 4 - 8
tests/tests/PraktikumHolonsTestClasses.java

@@ -54,7 +54,7 @@ public class PraktikumHolonsTestClasses {
 		HolonObject test1 = new HolonObject("Test1");
 		HolonObject test2 = new HolonObject("Test2");
 		HolonObject test3 = new HolonObject(test1);
-		HolonElement ele = new HolonElement(test1, "Element", 1, 10, IdCounter.nextId(CounterType.Element));
+		HolonElement ele = new HolonElement(test1, "Element", 10, IdCounter.nextId(CounterType.Element));
 		ArrayList<HolonElement> arr = new ArrayList<>();
 		assertTrue("Should be Empty", test1.getElements().isEmpty());
 		test1.setElements(arr);
@@ -69,7 +69,7 @@ public class PraktikumHolonsTestClasses {
 		assertTrue("Current Energy not corrent", test2.getEnergyAtTimeStep(20) == 20);
 		String str = test2.toStringElements();
 		assertTrue("String not corrent", str.equals("Element, Element"));
-		test2.deleteElement(0);
+		test2.removeElement(0);
 		test2.addElement(ele);
 		
 		assertTrue("Element not Found", test3.searchElement("Element") != null);
@@ -134,17 +134,13 @@ public class PraktikumHolonsTestClasses {
 	 */
 	@Test
 	public void testHolonElement() {
-		HolonElement ele1 = new HolonElement(null, "TV", 2, -20f, IdCounter.nextId(CounterType.Element));
-		HolonElement ele2 = new HolonElement(null, "Fridge", 1, -50f, IdCounter.nextId(CounterType.Element));
+		HolonElement ele1 = new HolonElement(null, "TV", -20f, IdCounter.nextId(CounterType.Element));
+		HolonElement ele2 = new HolonElement(null, "Fridge", -50f, IdCounter.nextId(CounterType.Element));
         assertTrue("Array not empty",  ele1.getEnergyAtTimeStep(0) == -40);
         assertTrue("Array not empty", ele1.getEnergyAtTimeStep(2) == -40);
         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.getMaximumEnergy() == ele2.getAmount() * ele2.getEnergyPerElement());
 	}
 	/**
 	 * Test for Position.

+ 2 - 2
tests/tests/PraktikumHolonsTestGlobalController.java

@@ -37,7 +37,7 @@ public class PraktikumHolonsTestGlobalController {
 		int prevScaleDiv2 = controller.getScaleDiv2();
 		int prevNumberSav = controller.getNumbersOfSaves();
 		int timer = model.getTimerSpeed();
-		int it = model.getCurIteration();
+		int it = model.getCurrentIteration();
 
 		controller.setScale(100);
 		controller.setNumberOfSaves(50);
@@ -48,7 +48,7 @@ public class PraktikumHolonsTestGlobalController {
 		assertTrue("ScaleDiv2 was not changed ", model.getScaleDiv2() != prevScaleDiv2);
 		assertTrue("Number of Saves was not changed", controller.getNumbersOfSaves() != prevNumberSav);
 		assertTrue("Timer speed was not changed", timer != model.getTimerSpeed());
-		assertTrue("Curr Iteration was not Set", it != model.getCurIteration());
+		assertTrue("Curr Iteration was not Set", it != model.getCurrentIteration());
 
 	}
 

+ 0 - 274
tests/tests/PraktikumHolonsTestLoadAndStoreController.java

@@ -28,278 +28,4 @@ public class PraktikumHolonsTestLoadAndStoreController {
 	protected LoadController loadController;
 	protected IdCounter id;
 	protected String path = System.getProperty("user.home") + "/HolonGUI/Test/";
-
-//	/**
-//	 * Setup for the Tests.
-//	 */
-//	@Before
-//	public void setUp() {
-//		adapter = new PraktikumHolonsAdapter();
-//		model = new Model();
-//		mp = new MultiPurposeController(model);
-//		cg = new CategoryController(model, mp);
-//		cvs = new CanvasController(model, mp);
-//		obj = new ObjectController(model, mp);
-//		storeController = new StoreController(model);
-//		loadController = new LoadController(model, cg, cvs, obj, global, mp);
-//		// cg.initCategories();
-//		// obj.initHolonElements();
-//		File file = new File(path);
-//		file.mkdirs();
-//	}
-//
-//	/**
-//	 * minimal tests for saving.
-//	 */
-//	@Test
-//	public void testStoreMinimal() {
-//		try {
-//			File sav = new File(path + "TestSavMinimal.json");
-//			storeController.writeSaveFile(sav.getAbsolutePath());
-//			assertTrue("Save File was not created", new File(path + "TestSavMinimal.json").exists());
-//
-//			File cat = new File(path + "TestCategoryMinimal.json");
-//			//storeController.writeCategoryFile(cat.getAbsolutePath());
-//			assertTrue("Category File was not created", new File(path + "TestCategoryMinimal.json").exists());
-//
-//			File canvas = new File(path + "TestCanvasMinimal.json");
-//			storeController.writeCanvasFile(canvas.getAbsolutePath());
-//			assertTrue("Canvas File was not created", new File(path + "TestCanvasMinimal.json").exists());
-//
-//			assertTrue("Non Existant File exist", !new File(path + "TestDummyMinimal.json").exists());
-//
-//		} catch (IOException e) {
-//			// TODO Auto-generated catch block
-//			e.printStackTrace();
-//		}
-//	}
-//
-//	/**
-//	 * basic tests for saving.
-//	 */
-//	@Test
-//	public void testStoreBasic() {
-//
-//		for (int i = 1; i <= 26; i++) {
-//			cg.addNewCategory(adapter.generate(i));
-//			assertTrue("Number of Categories does not match", model.getCategories().size() == i + 3);
-//			assertTrue("Category was not created", mp.searchCat(adapter.generate(i)) != null);
-//			for (int j = 1; j <= 10; j++) {
-//				cg.addNewHolonObject(mp.searchCat(adapter.generate(i)), adapter.generate(j),
-//						new ArrayList<HolonElement>(), "");
-//				assertTrue("Number of Objects does not match",
-//						mp.searchCat(adapter.generate(i)).getObjects().size() == j);
-//				assertTrue("Object was not created", mp.searchCat(adapter.generate(i)).getObjects().get(j - 1) != null);
-//			}
-//		}
-//
-//		// here some Objects were dropped on the canvas
-//		for (int i = 1; i <= 10; i++) {
-//			cvs.addNewObject(new HolonObject(mp.searchCatObj(mp.searchCat("Building"), "House")));
-//			assertTrue("Size of Objects on Canvas does not match", model.getObjectsOnCanvas().size() == i);
-//			assertTrue("Object was not added", model.getObjectsOnCanvas().get(i - 1) != null
-//					&& model.getObjectsOnCanvas().get(i - 1).getObjName().equals("House"));
-//		}
-//
-//		HolonSwitch sw = new HolonSwitch(mp.searchCatObj(mp.searchCat("Component"), "Switch"));
-//		sw.setPosition(77, 88);
-//		cvs.addNewObject(sw);
-//
-//		try {
-//			File sav = new File(path + "TestSavBasic.json");
-//			storeController.writeSaveFile(sav.getAbsolutePath());
-//			assertTrue("Save File was not created", new File(path + "TestSavBasic.json").exists());
-//
-//			File canvas = new File(path + "TestCanvasBasic.json");
-//			storeController.writeCanvasFile(canvas.getAbsolutePath());
-//			assertTrue("Canvas File was not created", new File(path + "TestCanvasBasic.json").exists());
-//
-//			assertTrue("Non Existant File exist", !new File(path + "TestDummyMinimal.json").exists());
-//
-//		} catch (IOException e) {
-//			// TODO Auto-generated catch block
-//			e.printStackTrace();
-//		}
-//	}
-//
-//	/**
-//	 * advanced tests for saving.
-//	 */
-//	@Test
-//	public void testStoreAdvanced() {
-//
-//		setGraphPoints((HolonObject) mp.searchCatObj(mp.searchCat("Building"), "House"));
-//
-//		int n = 0;
-//		for (int i = 0; i < 10; i++) {
-//			for (int j = 0; j < 10; j++) {
-//				HolonObject h = new HolonObject(mp.searchCatObj(mp.searchCat("Building"), "House"));
-//				h.setPosition(j * 50, i * 50);
-//				cvs.addNewObject(h);
-//				setGraphPoints(h);
-//				for (AbstractCpsObject cps : model.getObjectsOnCanvas()) {
-//					if (!cps.equals(h))
-//						cvs.addEdgeOnCanvas(new CpsEdge(h, cps));
-//				}
-//
-//				// vollständiger Graph
-//				n = model.getObjectsOnCanvas().size();
-//				assertTrue("Number of Edges does not Match", model.getEdgesOnCanvas().size() == (n * (n - 1)) / 2);
-//			}
-//		}
-//
-//		try {
-//			File sav = new File(path + "TestSavAdvanced.json");
-//			storeController.writeSaveFile(sav.getAbsolutePath());
-//			assertTrue("Save File was not created", new File(path + "TestSavAdvanced.json").exists());
-//
-//		} catch (IOException e) {
-//			// TODO Auto-generated catch block
-//			e.printStackTrace();
-//		}
-//
-//	}
-//
-//	/**
-//	 * minimal tests for loading a save file.
-//	 */
-//	@Test
-//	public void testLoadMinimal() {
-//		try {
-//			// Category Tests
-//			Category building = mp.searchCat("Building");
-//			assertTrue("Number of Categories does not match", model.getCategories().size() == 3);
-//			assertTrue("TestFile was not found", new File(path + "TestCategoryMinimal.json").exists());
-//			loadController.readJson(path + "TestCategoryMinimal.json");
-//			assertTrue("Number of Categories does not match", model.getCategories().size() == 3);
-//			// Tests if its same instance and if Name is the same
-//			assertTrue("Same instance of Category:Building", building != mp.searchCat("Building")
-//					&& building.getName().equals(mp.searchCat("Building").getName()));
-//
-//			// Canvas Tests.. basically nothing happens because nothing is on
-//			// the Canvas
-//			assertTrue("Number of Objects on Canvas does not match", model.getObjectsOnCanvas().size() == 0);
-//			assertTrue("TestFile was not found", new File(path + "TestCanvasMinimal.json").exists());
-//			loadController.readJson(path + "TestCanvasMinimal.json");
-//			assertTrue("Number of Objects on Canvas does not match", model.getObjectsOnCanvas().size() == 0);
-//
-//			// Save File tests basically both Test from Above Combined
-//			building = mp.searchCat("Building");
-//			assertTrue("Number of Objects in Energy does not Match", mp.searchCat("Energy").getObjects().size() == 1);
-//			assertTrue("TestFile was not found", new File(path + "TestSavMinimal.json").exists());
-//			loadController.readJson(path + "TestSavMinimal.json");
-//			assertTrue("Number of Objects in Energy does not Match", mp.searchCat("Energy").getObjects().size() == 1);
-//			assertTrue("Number of Objects on Canvas does not match", model.getObjectsOnCanvas().size() == 0);
-//			assertTrue("Same instance of Category:Building", building != mp.searchCat("Building")
-//					&& building.getName().equals(mp.searchCat("Building").getName()));
-//
-//		} catch (IOException e) {
-//			// TODO Auto-generated catch block
-//			e.printStackTrace();
-//		}
-//	}
-//
-//	/**
-//	 * basic tests for loading a save file.
-//	 */
-//	@Test
-//	public void testLoadBasic() {
-//		assertTrue("Non-Existant Category Exists", mp.searchCat("J") == null);
-//		assertTrue("Non-Existant Category Exists", mp.searchCat("U") == null);
-//		assertTrue("Non-Existant Category Exists", mp.searchCat("L") == null);
-//		assertTrue("Non-Existant Category Exists", mp.searchCat("I") == null);
-//		assertTrue("Non-Existant Category Exists", mp.searchCat("A") == null);
-//		assertTrue("Non-Existant Category Exists", mp.searchCat("N") == null);
-//
-//		try {
-//			assertTrue("Objects on Canvas is not 0", model.getObjectsOnCanvas().size() == 0);
-//			assertTrue("Canvas File was not found", new File(path + "TestCanvasBasic.json").exists());
-//			loadController.readJson(path + "TestCanvasBasic.json");
-//
-//			assertTrue("NUmber of Objects on Canvas does not match", model.getObjectsOnCanvas().size() == 11);
-//			for (AbstractCpsObject obj : model.getObjectsOnCanvas()) {
-//				assertTrue("Not instance of HolonObject", obj instanceof HolonObject || obj instanceof HolonSwitch);
-//
-//			}
-//
-//			assertTrue("NUmber of Categories not match", model.getCategories().size() == 3);
-//			assertTrue("Canvas File was not found", new File(path + "TestSavBasic.json").exists());
-//			loadController.readJson(path + "TestSavBasic.json");
-//			assertTrue("NUmber of Categories not match", model.getCategories().size() == 29);
-//			assertTrue("Existant Category dont Exists", mp.searchCat("J") != null);
-//			assertTrue("Existant Category dont Exists", mp.searchCat("U") != null);
-//			assertTrue("Existant Category dont Exists", mp.searchCat("L") != null);
-//			assertTrue("Existant Category dont Exists", mp.searchCat("I") != null);
-//			assertTrue("Existant Category dont Exists", mp.searchCat("A") != null);
-//			assertTrue("Existant Category dont Exists", mp.searchCat("N") != null);
-//			assertTrue("Existant Object dont Exists", mp.searchCatObj(mp.searchCat("Z"), "A") != null);
-//			assertTrue("Existant Object dont Exists", mp.searchCatObj(mp.searchCat("Z"), "B") != null);
-//			assertTrue("Existant Object dont Exists", mp.searchCatObj(mp.searchCat("Z"), "C") != null);
-//			assertTrue("Existant Object dont Exists", mp.searchCatObj(mp.searchCat("Z"), "D") != null);
-//			assertTrue("Existant Object dont Exists", mp.searchCatObj(mp.searchCat("Z"), "E") != null);
-//			assertTrue("Existant Object dont Exists", mp.searchCatObj(mp.searchCat("Z"), "F") != null);
-//
-//		} catch (IOException e) {
-//			// TODO Auto-generated catch block
-//			e.printStackTrace();
-//		}
-//	}
-//
-//	/**
-//	 * advanced tests for loading a save file.
-//	 */
-//	@Test
-//	public void testLoadAdvanced() {
-//
-//		try {
-//			assertTrue("Objects on Canvas is not 0", model.getObjectsOnCanvas().size() == 0);
-//			assertTrue("Save File was not found", new File(path + "TestSavAdvanced.json").exists());
-//			loadController.readJson(path + "TestSavAdvanced.json");
-//			assertTrue("Objects on Canvas is not 100", model.getObjectsOnCanvas().size() == 100);
-//
-//			int n = model.getObjectsOnCanvas().size();
-//			assertTrue("Number of Edges does not Match", model.getEdgesOnCanvas().size() == (n * (n - 1)) / 2);
-//			assertTrue("Element has no UnitGraph", !mp
-//					.searchEle((HolonObject) model.getObjectsOnCanvas().get(77), "Fridge").getGraphPoints().isEmpty());
-//			assertTrue("Points in UnitGraph does not Match",
-//					mp.searchEle((HolonObject) model.getObjectsOnCanvas().get(77), "Fridge").getGraphPoints()
-//							.size() == 3);
-//
-//		} catch (IOException e) {
-//			// TODO Auto-generated catch block
-//			e.printStackTrace();
-//		}
-//	}
-//
-//	/**
-//	 * Test for FileNotFound.
-//	 * 
-//	 * @throws IOException
-//	 *             FileNotFoundException
-//	 */
-//	@Test(expected = FileNotFoundException.class)
-//	public void testLoadException() throws IOException {
-//		assertTrue("Save File was not found", !new File(path + "TestSavDummy.json").exists());
-//		loadController.readJson(path + "TestSavDummy.json");
-//	}
-//
-//	/**
-//	 * sets the graph points in all elements of an Object.
-//	 * 
-//	 * @param obj
-//	 *            the Object
-//	 */
-//	public void setGraphPoints(HolonObject obj) {
-//		LinkedList<Point> list = new LinkedList<>();
-//		list.add(new Point(0, 0));
-//		list.add(new Point(125, 50));
-//		list.add(new Point(249, 0));
-//		UnitGraph u = new UnitGraph(model, null);
-//		u.repaintWithNewElement(obj.getElements());
-//		u.fillArrayofValue();
-//		for (HolonElement ele : obj.getElements()) {
-//			ele.setGraphPoints(list);
-//		}
-//
-//	}
 }

+ 9 - 9
tests/tests/PraktikumHolonsTestObjectController.java

@@ -66,9 +66,9 @@ public class PraktikumHolonsTestObjectController {
 	 */
 	@Test
 	public void testAddingAndDeletingInCategory() {
-		controller.addNewElementIntoCategoryObject("Building", "House", "A", 1, -10);
+		controller.addNewElementIntoCategoryObject("Building", "House", "A", -10);
 		for (int i = 2; i < 27; i++) {
-			controller.addNewElementIntoCategoryObject("Building", "House", adapter.generate(i), i, -10);
+			controller.addNewElementIntoCategoryObject("Building", "House", adapter.generate(i), -10);
 			// n(n+1) / 2
 					assertTrue("Number of Elements does not Match",
 					((HolonObject) mp.searchCatObj(mp.searchCat("Building"), "House")).getElements().size() == 6 + i);
@@ -86,16 +86,16 @@ public class PraktikumHolonsTestObjectController {
 		}
 
 		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-			int size = model.getSelectedCpsObjects().size();
+			int size = model.getSelectedObjects().size();
 			controller.addSelectedObject(cps);
-			assertTrue("Size does not Match", model.getSelectedCpsObjects().size() == size + 1);
+			assertTrue("Size does not Match", model.getSelectedObjects().size() == size + 1);
 		}
 		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
-			System.out.println(model.getSelectedCpsObjects().size());
-			int size = model.getSelectedCpsObjects().size();
-			controller.deleteSelectedObject(cps);
-			assertTrue("Size does not Match", model.getSelectedCpsObjects().size() == size - 1);
-			assertTrue("Object was not unselected", !model.getSelectedCpsObjects().contains(cps));
+			System.out.println(model.getSelectedObjects().size());
+			int size = model.getSelectedObjects().size();
+			controller.removeObjectFromSelection(cps);
+			assertTrue("Size does not Match", model.getSelectedObjects().size() == size - 1);
+			assertTrue("Object was not unselected", !model.getSelectedObjects().contains(cps));
 
 		}
 	}