Browse Source

Merge remote-tracking branch 'remotes/origin/BP_master' into BatteryMerge

Merge Newest Version of BPMaster to Battery
tolatesry 6 years ago
parent
commit
9d4bead74e

+ 19 - 14
src/classes/HolonElement.java

@@ -2,6 +2,8 @@ package classes;
 
 import com.google.gson.annotations.Expose;
 
+import ui.model.Model;
+
 import java.awt.*;
 import java.util.LinkedList;
 
@@ -45,6 +47,10 @@ public class HolonElement {
     /* ID */
     @Expose
     private int id;
+    
+    private static final int DEFAULT_GRAPH_LENGTH=100;
+    //private int graphLength=DEFAULT_GRAPH_LENGTH; Unimplementable due to former developer's dark magic.
+    
     /*
      * Energy at each point of the graph with 100 predefined points. At the
      * beginning, it starts with all values at energyPerElement.
@@ -59,25 +65,23 @@ public class HolonElement {
      * @param eleName String
      * @param amount  int
      * @param energy  float
+     * @param model Model
      */
+    public HolonElement(String eleName, int amount, float energy, Model model) {
+    	this(eleName, amount, energy, IdCounterElem.nextId(),model);
+    }
+    
     public HolonElement(String eleName, int amount, float energy) {
-        setEleName(eleName);
-        setAmount(amount);
-        setEnergyPerElement(energy);
-        setActive(true);
-        setSign(energy);
-        setAvailableEnergyPerElementAt(energy);
-        setGraphPoints(new LinkedList<>());
-        setId(IdCounterElem.nextId());
-        setFlexibleEnergyAvailable(0);
-        setFlexible(false);
+    	this(eleName, amount, energy, IdCounterElem.nextId(),null);//TODO: This is just for the old tests...
     }
 
     /**
      * same as standard constructor, but with already given id (so the counter is not increased twice)
      */
-    public HolonElement(String eleName, int amount, float energy, int id) {
-        setEleName(eleName);
+    public HolonElement(String eleName, int amount, float energy, int id, Model model){
+    	//if(model!=null)graphLength=model.getGraphIterations();
+    	//if(graphLength==0)graphLength=DEFAULT_GRAPH_LENGTH;//This would work if the used HolonElements were actually made using a proper constructor.
+    	setEleName(eleName);
         setAmount(amount);
         setEnergyPerElement(energy);
         setActive(true);
@@ -95,6 +99,7 @@ public class HolonElement {
      * @param element element to copy
      */
     public HolonElement(HolonElement element) {
+    	//graphLength=element.graphLength;//Should I add a getter?
         setEleName(element.getEleName());
         setAmount(element.getAmount());
         setEnergyPerElement(element.getEnergyPerElement());
@@ -151,7 +156,7 @@ public class HolonElement {
      * Get the energyPerElement currently available
      */
     public float getAvailableEnergyAt(int timestep) {
-        return this.availableEnergyPerElementAt[timestep];
+        return this.availableEnergyPerElementAt[timestep%DEFAULT_GRAPH_LENGTH];//TODO:use an attribute here
     }
 
     /**
@@ -259,7 +264,7 @@ public class HolonElement {
         if (flexible) {
             return ((float) amount) * energyPerElement;
         } else {
-            return ((float) amount) * availableEnergyPerElementAt[x];
+            return ((float) amount) * availableEnergyPerElementAt[x%DEFAULT_GRAPH_LENGTH];//TODO: use an attribute
         }
     }
 

+ 5 - 2
src/classes/HolonObject.java

@@ -26,6 +26,8 @@ public class HolonObject extends AbstractCpsObject {
     public final static int PRODUCER = 3;
     public final static int PARTIALLY_SUPPLIED = 4;
     public final static int OVER_SUPPLIED = 5;
+    
+    private static final int DEFAULT_GRAPH_LENGTH = 100;//TODO
     /*
      * Color of the actual state (red = no supplied, yellow = partially supplied
      * and green = supplied)
@@ -156,7 +158,8 @@ public class HolonObject extends AbstractCpsObject {
      */
     public float getCurrentEnergyAtTimeStep(int x) {
         float temp = 0;
-        float cons = 0, prod = currentSupply;
+        float cons = 0;
+        float prod = currentSupply;
         float t;
         for (HolonElement e : getElements()) {
             if (e.isActive()) {
@@ -170,7 +173,7 @@ public class HolonObject extends AbstractCpsObject {
             }
         }
         currentEnergy = temp;
-        suppliedPercentage = -prod / cons;
+        suppliedPercentage = prod / -cons;
         return currentEnergy;
     }
 

+ 43 - 0
src/ui/controller/CanvasController.java

@@ -46,6 +46,49 @@ public class CanvasController {
 	public void addObject(AbstractCpsObject object) {
 		model.getCvsObjIdx().put(object.getId(), model.getObjectsOnCanvas().size());
 		model.getObjectsOnCanvas().add(object);
+		/**
+		 * check if we should drag & drop replace
+		 */
+		
+		/** x of the dragged Object */
+		int x = object.getPosition().x;
+		
+		/** y of the dragged Object */
+		int y = object.getPosition().y;
+		
+		/** distance treshold for replacement */
+		int treshhold = model.getScale()/4;
+		
+		/** number of Objects that might be replaced (should be 1) */
+		int replaceCounter = 0;
+		
+		/** last object that could be replaced */
+		AbstractCpsObject toBeReplaced = null;
+		
+		/** for each cps on Canvas */
+		for (AbstractCpsObject cps : model.getObjectsOnCanvas()){
+			
+			/** same object -> ignore */
+			if(cps == object)continue;
+			
+			/** x of object that might get replaced */
+			int c_x = cps.getPosition().x;
+			
+			/** y of object that might get replaced */
+			int c_y = cps.getPosition().y;
+			
+			/** if near enough */
+			if(Math.abs(x-c_x)<treshhold && Math.abs(y-c_y)<treshhold){
+				replaceCounter++;
+				toBeReplaced = cps;
+			}
+		}
+		/** if replacement of exactly one object possible */
+		if(replaceCounter == 1 && toBeReplaced != null){
+			replaceObjectOnCanvas(toBeReplaced, object);
+		}
+		
+		
 		notifyObjListeners();
 	}
 

+ 42 - 0
src/ui/controller/NodeController.java

@@ -444,6 +444,48 @@ class NodeController {
         object.setSav("" + upperNode.getId());
 		upperNode.getNodesIdx().put(object.getId(), upperNode.getNodes().size());
 		upperNode.getNodes().add(object);
+		
+		/**
+		 * check if we should drag & drop replace
+		 */
+		
+		/** x of the dragged Object */
+		int x = object.getPosition().x;
+		
+		/** y of the dragged Object */
+		int y = object.getPosition().y;
+		
+		/** distance threshold for replacement */
+		int treshhold = model.getScale()/4;
+		
+		/** number of Objects that might be replaced (should be 1) */
+		int replaceCounter = 0;
+		
+		/** last object that could be replaced */
+		AbstractCpsObject toBeReplaced = null;
+		
+		/** for each cps on Canvas */
+		for (AbstractCpsObject cps : upperNode.getNodes()){
+			
+			/** same object -> ignore */
+			if(cps == object)continue;
+			
+			/** x of object that might get replaced */
+			int c_x = cps.getPosition().x;
+			
+			/** y of object that might get replaced */
+			int c_y = cps.getPosition().y;
+			
+			/** if near enough */
+			if(Math.abs(x-c_x)<treshhold && Math.abs(y-c_y)<treshhold){
+				replaceCounter++;
+				toBeReplaced = cps;
+			}
+		}
+		/** if replacement of exactly one object possible */
+		if(replaceCounter == 1 && toBeReplaced != null){
+			replaceObjectInUpperNode(toBeReplaced, object, upperNode);
+		}
 	}
 
 	/**

+ 2 - 2
src/ui/controller/ObjectController.java

@@ -71,7 +71,7 @@ public class ObjectController {
      * @param elementId the Element ID
      */
     public void addNewElementIntoCanvasObject(int objectId, String element, int amount, float energy, int elementId) {
-        HolonElement ele = new HolonElement(element, amount, energy, elementId);
+        HolonElement ele = new HolonElement(element, amount, energy, elementId, model);
         if (mpC.searchByID(objectId) == null) {
             addElementIntoCanvasObject((HolonObject) model.getSelectedCpsObjects().get(0), ele);
         } else {
@@ -103,7 +103,7 @@ public class ObjectController {
     public void addNewElementIntoCategoryObject(String category, String object, String element, int amount,
                                                 float energy) {
 
-        HolonElement ele = new HolonElement(element, amount, energy);
+        HolonElement ele = new HolonElement(element, amount, energy, model);//TODO: I added model
         addElementIntoCategoryObject(category, object, ele);
     }
 

+ 9 - 4
src/ui/controller/SimulationManager.java

@@ -36,8 +36,8 @@ public class SimulationManager {
 
 	/**
 	 * One Element of each HolonObject will be powered first, starting with the
-	 * smallest Demand. If alle HolonObjects have an active Element, the
-	 * simulation will try to fully suplly as many HolonObjects as possible.
+	 * smallest Demand. If ale HolonObjects have an active Element, the
+	 * simulation will try to fully supply as many HolonObjects as possible.
 	 */
 	public static final short fairnessMininumDemandFirst = 0;
 
@@ -122,9 +122,14 @@ public class SimulationManager {
 			 */
 			ArrayList<HolonObject> notSuppliedList = new ArrayList<HolonObject>();
 			/**
-			 * number of HolonObjects that need to be supplied
+			 * Number of HolonObjects that need to be supplied
 			 */
-			long numberOfConsumers;
+			long numberOfConsumers = singleSubNet.getObjects().stream()
+			.filter(hl -> (hl.getState() != HolonObject.NO_ENERGY
+					&& hl.getState() != HolonObject.PRODUCER && hl
+					.getConnectedTo().stream()
+					.filter(e -> (e.getFlow() > 0)).count() > 0))
+			.count();
 			/**
 			 * energy each HolonObject receives in AlleEqualModus
 			 */

+ 16 - 2
src/ui/model/Model.java

@@ -26,7 +26,8 @@ import java.util.List;
  */
 public class Model {
 
-    private static final int ITERATIONS = 100;
+	
+    private static final int GRAPH_ITERATIONS = 100;
     // Global Variables
     private static int sCALE = 50; // Picture Scale
     private static int sCALEdIV2 = sCALE / 2;
@@ -69,6 +70,8 @@ public class Model {
     private boolean useFlexibleDevices = true;
     /** whether the supplyBars should be shown or not */
     private boolean showSupplyBars = true;
+    //TODO:
+    private int iterations=100;
     
     /** the Fairness model in use */
     private short fairnessModel = 0;
@@ -376,7 +379,7 @@ public class Model {
      * @return ITERATIONS
      */
     public int getIterations() {
-        return ITERATIONS;
+        return iterations;
     }
 
     private void notifyGraphListeners() {
@@ -923,6 +926,13 @@ public class Model {
 		this.showSupplyBars = showSupplyBars;
 	}
 	
+	/**
+	 * @param iterations the number of steps for this simulation
+	 */
+	public void setIterations(int iterations){
+		this.iterations=iterations;
+	}
+	
 	/**
 	 * @return the fairnessModel
 	 */
@@ -936,6 +946,10 @@ public class Model {
 	public void setFairnessModel(short fairnessModel) {
 		this.fairnessModel = fairnessModel;
 	}
+	
+	public int getGraphIterations(){
+		return GRAPH_ITERATIONS;
+	}
 
 	/**
      * Initialize the Gson with wanted parameters

+ 386 - 406
src/ui/view/AbstractCanvas.java

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

+ 95 - 50
src/ui/view/AddElementPopUp.java

@@ -3,9 +3,11 @@ package ui.view;
 import classes.AbstractCpsObject;
 import classes.HolonElement;
 import classes.HolonObject;
+import ui.model.Model;
 
 import javax.swing.*;
 import javax.swing.border.EmptyBorder;
+
 import java.awt.*;
 import java.awt.event.KeyEvent;
 import java.awt.event.KeyListener;
@@ -14,6 +16,7 @@ import java.awt.event.KeyListener;
  * popup for adding an Holon Element to a holon Object.
  * 
  * @author Gruppe14
+ * @author improved by A.T.M.-B. (Gruppe007)
  */
 public class AddElementPopUp extends JDialog {
 
@@ -21,38 +24,39 @@ public class AddElementPopUp extends JDialog {
 	 * Serial.
 	 */
 	private static final long serialVersionUID = 1L;
+	/* Data */
+	/** Holon Object the Element should be added to */
+	private AbstractCpsObject tempCps;
+	/** Holon Element that should be edited (if in edit Modus */
+	private HolonElement hl;
+	
+	/* GUI */
+	/** Panel containing everything */
 	private final JPanel contentPanel = new JPanel();
+	/** Textfield for entering a Name for the Element */
 	private JTextField elementName;
+	/** Textfield for the energy the Element consumes/produces */
 	private JTextField providedEnergy;
+	/** Element is active if checked */
+	JCheckBox checkBoxActive;
+	/** Textfield to enter the amount of this Element */
 	private JTextField amount;
-	private HolonElement hl;
-	private AbstractCpsObject tempCps;
-
-	// /**
-	// * Launch the application.
-	// *
-	// * @param args
-	// * standard
-	// */
-	// public static void main(String[] args) {
-	// try {
-	//
-	// AddElementPopUp dialog = new AddElementPopUp();
-	// dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
-	// dialog.setVisible(true);
-	// } catch (Exception e) {
-	// e.printStackTrace();
-	// }
-	// }
+	/** Textfield to enter the flexible Energy of the Element */
+	private JTextField flexibleEnergy;
+	/** Flexible if checkbox is checked */
+	JCheckBox checkboxFlexible;
+	/** Model which is used */
+	private Model model;
 
 	/**
-	 * Create the dialog.
+	 * Create the AddElementPopup Dialog
+	 * @param parentFrame
 	 */
-	AddElementPopUp(JFrame parentFrame) {
+	AddElementPopUp(JFrame parentFrame, Model model) {
 		super((java.awt.Frame) null, true);
 		this.setIconImage(Util.loadImage(this, "/Images/Dummy_House.png", 30, 30));
 		setModalityType(java.awt.Dialog.ModalityType.APPLICATION_MODAL);
-		setBounds(100, 100, 400, 190);
+		setBounds(100, 100, 400, 245);
 		setLocationRelativeTo(parentFrame);
 		getContentPane().setLayout(new BorderLayout());
 		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
@@ -60,18 +64,8 @@ public class AddElementPopUp extends JDialog {
 		contentPanel.setLayout(null);
 		this.setTitle(Languages.getLanguage()[64]);
 
-		JLabel lblElementName = new JLabel(Languages.getLanguage()[65]);
-		lblElementName.setBounds(10, 11, 100, 14);
-		contentPanel.add(lblElementName);
-
-		JLabel lblProvidedEnergy = new JLabel(Languages.getLanguage()[66]);
-		lblProvidedEnergy.setBounds(10, 49, 120, 14);
-		contentPanel.add(lblProvidedEnergy);
-
-		JLabel lblAmount = new JLabel(Languages.getLanguage()[67]);
-		lblAmount.setBounds(10, 84, 100, 14);
-		contentPanel.add(lblAmount);
-
+		
+		/* Element Name Textfield and Label */
 		elementName = new JTextField();
 		elementName.addKeyListener(new KeyListener() {
 			@Override
@@ -87,22 +81,57 @@ public class AddElementPopUp extends JDialog {
 				elementName.setBackground(Color.WHITE);
 			}
 		});
-		elementName.setBounds(130, 8, 110, 20);
+		
+		JLabel lblElementName = new JLabel(Languages.getLanguage()[65]);
+		lblElementName.setBounds(10, 10, 100, 20);
+		contentPanel.add(lblElementName);
+		elementName.setBounds(130, 10, 110, 20);
 		contentPanel.add(elementName);
 		elementName.setColumns(10);
-
+		
+		/* Add Provided Energy Label and Textfield */
+		JLabel lblProvidedEnergy = new JLabel(Languages.getLanguage()[66]);
+		lblProvidedEnergy.setBounds(10, 50, 120, 20);
+		contentPanel.add(lblProvidedEnergy);
+		
 		providedEnergy = new JTextField();
-		providedEnergy.setBounds(130, 46, 110, 20);
+		providedEnergy.setBounds(130, 50, 110, 20);
 		contentPanel.add(providedEnergy);
 		providedEnergy.setColumns(10);
 		providedEnergy.setText("0");
+		
+		checkBoxActive = new JCheckBox("Active");
+		checkBoxActive.setSelected(true);
+		checkBoxActive.setBounds(250, 50, 115, 20);
+		contentPanel.add(checkBoxActive);
+		
+		/* Add Flexible Energy Textfield and CheckBox */
+		JLabel lblFlexibleEnergy = new JLabel("Flexible Energy:");
+		lblFlexibleEnergy.setBounds(10, 90, 100, 20);
+		contentPanel.add(lblFlexibleEnergy);
+		
+		flexibleEnergy = new JTextField();
+		flexibleEnergy.setText("0");
+		flexibleEnergy.setColumns(10);
+		flexibleEnergy.setBounds(130, 90, 110, 20);
+		contentPanel.add(flexibleEnergy);
+		
+		checkboxFlexible = new JCheckBox("Flexible");
+		checkboxFlexible.setBounds(250, 90, 115, 20);
+		contentPanel.add(checkboxFlexible);
+		
+		/* Add Amount Textfield and Checkbox */
+		JLabel lblAmount = new JLabel(Languages.getLanguage()[67]);
+		lblAmount.setBounds(10, 130, 100, 14);
+		contentPanel.add(lblAmount);
 
 		amount = new JTextField();
-		amount.setBounds(130, 81, 110, 20);
+		amount.setBounds(130, 130, 110, 20);
 		contentPanel.add(amount);
 		amount.setColumns(10);
 		amount.setText("1");
 
+		/* Add Buttons and Actions */
 		JPanel buttonPane = new JPanel();
 		buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
 		getContentPane().add(buttonPane, BorderLayout.SOUTH);
@@ -117,7 +146,6 @@ public class AddElementPopUp extends JDialog {
 		cancelButton.setActionCommand("Cancel");
 		buttonPane.add(cancelButton);
 		cancelButton.addActionListener(e -> dispose());
-
 	}
 
 	/**
@@ -139,15 +167,28 @@ public class AddElementPopUp extends JDialog {
 		return hl;
 	}
 
+	/**
+	 * setElement that should be edited
+	 * @param holonElement
+	 */
 	public void setElement(HolonElement holonElement) {
-		hl = new HolonElement(hl);
-
+		hl = holonElement;
+		elementName.setText(hl.getEleName());
+		amount.setText(""+hl.getAmount());
+		flexibleEnergy.setText(""+hl.getFlexibleEnergyAvailablePerElement());
+		checkboxFlexible.setSelected(hl.isFlexible());
+		providedEnergy.setText(""+hl.getEnergyPerElement());
+		checkBoxActive.setSelected(hl.isActive());
+		
 	}
-
+	
+	/**
+	 * Trys to create/edit the Element
+	 */
 	private void okAction() {
 		boolean repeated = false;
 		for (HolonElement e : ((HolonObject) tempCps).getElements()) {
-			if (elementName.getText().equals(e.getEleName())) {
+			if (elementName.getText().equals(e.getEleName())&&(hl == null || hl.getId()!=e.getId())) {
 				repeated = true;
 				break;
 			}
@@ -156,16 +197,21 @@ public class AddElementPopUp extends JDialog {
 			try {
 				float energy = Float.parseFloat(providedEnergy.getText());
 				int elementAmount = Integer.parseInt(amount.getText());
-				hl = new HolonElement(elementName.getText(), elementAmount, energy);
-
+				if(hl == null){
+					hl = new HolonElement(elementName.getText(), elementAmount, energy, model);
+				} else {
+					hl.setEleName(elementName.getText());
+					hl.setAmount(elementAmount);
+					hl.setEnergyPerElement(energy);
+				}
+				hl.setActive(checkBoxActive.isSelected());
+				hl.setFlexible(checkboxFlexible.isSelected());
+				hl.setFlexibleEnergyAvailable(Float.parseFloat(flexibleEnergy.getText()));
 				dispose();
 			} catch (NumberFormatException e) {
 				JOptionPane.showMessageDialog(new JFrame(), Languages.getLanguage()[68]);
 			}
 		} else {
-			// JOptionPane.showMessageDialog(new JFrame(),
-			// "Please enter a Name");
-
 			if (elementName.getText().length() == 0) {
 				JLabel errorString = new JLabel(Languages.getLanguage()[69]);
 				errorString.setBounds(240, 8, 100, 20);
@@ -177,6 +223,5 @@ public class AddElementPopUp extends JDialog {
 			}
 			elementName.setBackground(new Color(255, 50, 50));
 		}
-
 	}
-}
+}

+ 6 - 2
src/ui/view/AddObjectPopUp.java

@@ -7,6 +7,7 @@ import classes.HolonObject;
 import classes.Pair;
 import ui.controller.Control;
 import java.lang.NumberFormatException;
+import ui.model.Model;
 import javax.swing.*;
 import javax.swing.border.EmptyBorder;
 import javax.swing.filechooser.FileNameExtensionFilter;
@@ -42,6 +43,7 @@ public class AddObjectPopUp extends JDialog {
 	private AbstractCpsObject toEdit;
 	private boolean editState;
 	private boolean imageChanged = false;
+	private Model model;
 
 	/**
 	 * Launch the application.
@@ -77,6 +79,7 @@ public class AddObjectPopUp extends JDialog {
     	}
         toEdit = obj;
 		editState = edit;
+		this.model=model;
 		this.setIconImage(Util.loadImage(this, "/Images/Dummy_House.png",30,30));
 		setBounds(100, 100, 450, 342);
         setLocationRelativeTo(parentFrame);
@@ -168,7 +171,7 @@ public class AddObjectPopUp extends JDialog {
 		{
 			JButton btnAddDefaultElement = new JButton(Languages.getLanguage()[61]);
 			btnAddDefaultElement.addActionListener(actionEvent -> {
-                addElement = new AddElementPopUp(parentFrame);
+                addElement = new AddElementPopUp(parentFrame, model);
                 addElement.setActualCps(toEdit);
 				addElement.setVisible(true);
 				HolonElement hl = addElement.getElement();
@@ -439,7 +442,8 @@ public class AddObjectPopUp extends JDialog {
 			selectedFile = fileChooser.getSelectedFile();
 			filePath = selectedFile.getAbsolutePath();
 			sourcePath.setText(filePath);
-			ImageIcon icon = new ImageIcon(
+			ImageIcon icon = new ImageIcon(//TODO: ugly
+					
 					new ImageIcon(filePath).getImage().getScaledInstance(50, 50, Image.SCALE_SMOOTH));
 			lblImagePreview.setIcon(icon);
 			imageChanged = true;

+ 9 - 7
src/ui/view/CreateTemplatePopUp.java

@@ -79,8 +79,10 @@ public class CreateTemplatePopUp extends JDialog {
 	/**
 	 * parent Frame
 	 */
+	
+	private Model model;
+	
 	JFrame parent;
-
 	/**
 	 * Create the dialog.
 	 * 
@@ -105,6 +107,7 @@ public class CreateTemplatePopUp extends JDialog {
 		template = new HolonObject(obj);
 		this.parent = parentFrame;
 		this.controller = controller;
+		this.model=model;//Thankfully that was in the ctor already.
 		/*
 		 * create Frame and GUI
 		 */
@@ -312,7 +315,7 @@ public class CreateTemplatePopUp extends JDialog {
 	 * Add an Holon Element to the template
 	 */
 	private void addElement() {
-		AddElementPopUp popUp = new AddElementPopUp(parent);
+		AddElementPopUp popUp = new AddElementPopUp(parent, model);
 		popUp.setActualCps(template);
 		popUp.setVisible(true);
 		HolonElement he = popUp.getElement();
@@ -343,20 +346,19 @@ public class CreateTemplatePopUp extends JDialog {
 		if (index == -1)
 			return;
 		
-		AddElementPopUp popUp = new AddElementPopUp(parent);
+		AddElementPopUp popUp = new AddElementPopUp(parent, model);
 		popUp.setActualCps(template);
 		popUp.setElement(template.getElements().get(index));
 		popUp.setVisible(true);
 		HolonElement he = popUp.getElement();
 		if (he != null) {
+			listModel.remove(index);
 			listModel.addElement(he.getAmount() + " * " + he.getEleName()
 					+ ": " + he.getOverallEnergy() + "U");
+			template.deleteElement(index);
 			template.addElement(he);
 			he.setSaving(new Pair<>(category, textField_name.getText()));
 		}
-		
-		System.out.println("Edit "
-				+ template.getElements().get(index).toString());
 	}
 
-}
+}

+ 8 - 2
src/ui/view/GUI.java

@@ -1081,7 +1081,7 @@ public class GUI implements CategoryListener {
 				if (tempCpsObject != null
 						&& tempCpsObject.getClass() == HolonObject.class
 						&& tempCpsObject.getId() != 0) {
-					addElementPopUp = new AddElementPopUp(frmCyberPhysical);
+					addElementPopUp = new AddElementPopUp(frmCyberPhysical, model);//TODO: I didn't even check
 					addElementPopUp.setActualCps(updCon.getActualCps());
 					addElementPopUp.setVisible(true);
 					HolonElement ele = addElementPopUp.getElement();
@@ -1732,6 +1732,7 @@ public class GUI implements CategoryListener {
 		});
 		editItem.addActionListener(actionEvent -> {
 			// Remove the selected Object object
+			//AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame parentFrame)
 			addObjectPopUP = new AddObjectPopUp(true, tempCps,
 					catOfObjToBeEdited, frmCyberPhysical);
 			addObjectPopUP.setCategory(catOfObjToBeEdited);
@@ -2096,7 +2097,12 @@ public class GUI implements CategoryListener {
 
 		timePanel = new TimePanel(model, controller);
 		timePanel.setBorder(null);
-		((JSlider) (timePanel.getComponent(1)))
+		((JSlider)
+				(
+						((Container)timePanel.getComponent(1))//timePanel
+						.getComponent(1)//timeSlider
+				)
+		)//TODO: This hardcoded shit
 				.addChangeListener(changeEvent -> {
 					int i = model.getCurIteration();
 					controller.calculateStateForTimeStep(i);

+ 71 - 15
src/ui/view/TimePanel.java

@@ -7,8 +7,10 @@ import javax.swing.*;
 import javax.swing.event.ChangeEvent;
 import javax.swing.event.ChangeListener;
 import javax.swing.plaf.basic.BasicSliderUI;
+
 import java.awt.*;
 import java.awt.event.*;
+import java.util.Hashtable;
 
 /**
  * This Class represents a Panel where the User can start and stop the
@@ -17,18 +19,23 @@ import java.awt.event.*;
  * 
  * @author Gruppe14
  */
-public class TimePanel extends JPanel {
+public class TimePanel extends JPanel implements ActionListener{
 
 	private static final long serialVersionUID = 1L;
+	private static final int MAX_ITERATIONS=100000;
 	final JButton playBtn = new JButton();
 	final JButton timeResetBtn = new JButton();
 	final JButton timeForwardBtn = new JButton();
-	;
+	
 	final JButton timeBackwardBtn = new JButton();
+	JTextField iterationsField;
+	final JLabel iterationsLabel=new JLabel("  Iterations  ");
 	private final JPanel btnAndSpeedPanel = new JPanel();
 	private final JPanel speedPanel = new JPanel();
 	private final JPanel timeBtnPanel = new JPanel();
-	JSlider timeSlider = new JSlider() {
+	private final JPanel iterationsPanel=new JPanel();
+	private final JPanel timePanel=new JPanel();
+	JSlider timeSlider = new JSlider() {//TODO:
 		/**
 		 *
 		 */
@@ -81,7 +88,7 @@ public class TimePanel extends JPanel {
 		this.controller = cont;
 
 		// One Iteration
-		timer = new Timer(0, new ActionListener() {
+		timer = new Timer(0, new ActionListener() {//TODO: Merge all these damned listeners.
 			@Override
 			public void actionPerformed(ActionEvent ae) {
 				timeSlider.setValue(timeSlider.getValue() + 1);
@@ -101,8 +108,8 @@ public class TimePanel extends JPanel {
 		// Slider
 		timeSlider.setPaintTicks(true);
 		timeSlider.setPaintLabels(true);
-		timeSlider.setMinorTickSpacing(1);
-		timeSlider.setMajorTickSpacing(5);
+		timeSlider.setMajorTickSpacing((int)Math.ceil(((double)model.getIterations())/20));
+		timeSlider.setMinorTickSpacing((int)Math.ceil(((double)model.getIterations())/100));
 		timeSlider.setToolTipText(Languages.getLanguage()[93]);
 		timeSlider.setMaximum(model.getIterations() - 1);
 		timeSlider.setValue(0);
@@ -205,27 +212,57 @@ public class TimePanel extends JPanel {
 		speedPanel.add(speedSlider);
 		speedSlider.setPaintTicks(true);
 		speedSlider.setPaintLabels(true);
-		speedSlider.setMaximum(5000);
-		speedSlider.setMinimum(500);
-		speedSlider.setValue(1000);
-		// speedSlider.setMajorTickSpacing(100);
+		speedSlider.setMaximum(6);
+		speedSlider.setMinimum(0);
+		speedSlider.setValue(1);
+		
+		speedSlider.setPaintLabels(true);
+		Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
+		table.put (0, new JLabel("1x"));
+		table.put (1, new JLabel("2x"));
+		table.put (2, new JLabel("4x"));
+		table.put (3, new JLabel("8x"));
+		table.put (4, new JLabel("16x"));
+		table.put (5, new JLabel("32x"));
+		table.put (6, new JLabel("64x"));
+		    
+		speedSlider.setLabelTable(table);
+		
 		speedSlider.addChangeListener(new ChangeListener() {
 			@Override
 			public void stateChanged(ChangeEvent e) {
-				controller.setTimerSpeed(speedSlider.getValue());
-				speedSlider.setToolTipText("Speed: " + speedSlider.getValue());
+				/**
+				 * Shifting Powers of two:
+				 * e.g. 1<<0 -> 1 step per Second
+				 *      1<<3 -> 8 steps per Second
+				 *      and so on,
+				 */
+				int calculationsPerSecond = 1 << speedSlider.getValue();
+				controller.setTimerSpeed(1024 >> speedSlider.getValue());
+				speedSlider.setToolTipText("Speed: " + calculationsPerSecond + " Calculations per Second.");
 			}
 		});
+		
+		speedSlider.setToolTipText("Change the Number of Calculations per Secons");
 
 		// Buttons and Speed Panel
 		btnAndSpeedPanel.setLayout(new BorderLayout(0, 0));
 		btnAndSpeedPanel.setBorder(null);
 		btnAndSpeedPanel.add(timeBtnPanel, BorderLayout.NORTH);
 		btnAndSpeedPanel.add(speedPanel, BorderLayout.CENTER);
-
+		iterationsPanel.setLayout(new GridLayout(3,1));
+		iterationsPanel.add(iterationsLabel, BorderLayout.NORTH);
+		iterationsField=new JTextField(6);//Considering hundreds of thousands in an extreme case
+		iterationsField.setText(""+model.getIterations());
+		iterationsField.addActionListener(this);//TODO
+		iterationsPanel.add(iterationsField);
+		iterationsPanel.add(new JLabel(), BorderLayout.SOUTH);
+		timePanel.setLayout(new BorderLayout());
+		timePanel.add(iterationsPanel, BorderLayout.WEST);
+		timePanel.add(timeSlider, BorderLayout.CENTER);
 		this.add(btnAndSpeedPanel, BorderLayout.WEST);
-		this.add(timeSlider);
-
+		add(timePanel);
+		
 		//Disable Keys
 		timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "UP_ARROW");
 		timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "DOWN_ARROW");
@@ -269,4 +306,23 @@ public class TimePanel extends JPanel {
 	public JSlider getTimeSlider() {
 		return timeSlider;
 	}
+
+	@Override
+	public void actionPerformed(ActionEvent arg0) {//I dislike anon classes.
+		try{
+			int iterations=Integer.parseInt(iterationsField.getText());
+			boolean resetField=true;
+			if(iterations<1)iterations=1;
+			else if(iterations>MAX_ITERATIONS)iterations=MAX_ITERATIONS;
+			else resetField=false;
+			if(resetField)iterationsField.setText(""+iterations);
+			model.setIterations(Integer.parseInt(iterationsField.getText()));
+			timeSlider.setMaximum(model.getIterations());
+			timeSlider.setLabelTable(null);//Otherwise the ticks won't update
+			timeSlider.setMajorTickSpacing((int)Math.ceil(((double)model.getIterations())/20));
+			timeSlider.setMinorTickSpacing((int)Math.ceil(((double)model.getIterations())/100));
+		}catch(NumberFormatException e){
+			
+		}
+	}
 }

+ 5 - 4
src/ui/view/UnitGraph.java

@@ -128,17 +128,18 @@ public class UnitGraph extends JPanel implements MouseListener, MouseMotionListe
                 }
 
                 // Iteration Value
-                textWidth = g.getFontMetrics().stringWidth("" + arrayOfFloats[model.getCurIteration()]) + 2;
+                //TODO: added function getGraphIterations see if it works
+                textWidth = g.getFontMetrics().stringWidth("" + arrayOfFloats[model.getCurIteration()%model.getGraphIterations()]) + 2;
                 if (textWidth
                         + (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1) + 2
                         + border <= this.getWidth()) {
-                    g2.drawString("" + arrayOfFloats[model.getCurIteration()],
+                    g2.drawString("" + arrayOfFloats[model.getCurIteration()%model.getGraphIterations()],
                             (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
                                     + 2 + border,
                             this.getHeight() - 10);
                 } else {
-                    g2.drawString("" + arrayOfFloats[model.getCurIteration()],
-                            (model.getCurIteration()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
+                    g2.drawString("" + arrayOfFloats[model.getCurIteration()%model.getGraphIterations()],
+                            (model.getCurIteration()%model.getGraphIterations()) * (this.getWidth() - (border * 2)) / (model.getIterations() - 1)
                                     + border - textWidth,
                             this.getHeight() - 10);
                 }