Browse Source

Copy copies Edges

Outliner Hierarchy
Small Updates
TomTroppmann 2 years ago
parent
commit
4042cb1fdb

+ 3 - 3
src/holeg/model/Edge.java

@@ -95,9 +95,9 @@ public class Edge {
 
     @Override
     public String toString() {
-        String A = (a == null) ? "null" : a.getName() + "[" + a.getId() + "]";
-        String B = (b == null) ? "null" : b.getName() + "[" + b.getId() + "]";
-        return "CpsEdge: " + A + " to " + B;
+        String A = (a == null) ? "null" : a.getName() + " [" + a.getId() + "]";
+        String B = (b == null) ? "null" : b.getName() + " [" + b.getId() + "]";
+        return "Edge: " + A + " to " + B;
     }
 
     public EdgeState getState() {

+ 3 - 3
src/holeg/model/HolonObject.java

@@ -213,10 +213,10 @@ public class HolonObject extends AbstractCanvasObject implements PostDeserialize
     }
 
     public boolean isProducer(){
-        return getProduction() > getConsumption();
+        return getProduction() >= getConsumption();
     }
     public boolean isConsumer(){
-        return getConsumption() > getProduction();
+        return getConsumption() >= getProduction();
     }
 
     public float getEnergyFromHolon() {
@@ -259,7 +259,7 @@ public class HolonObject extends AbstractCanvasObject implements PostDeserialize
     public void calculateState() {
         if(actualEnergy > 0){
             state = HolonObjectState.PRODUCER;
-        }else if(elements.isEmpty()){
+        }else if(elements.isEmpty() || consumption == 0 && production == 0){
             state = HolonObjectState.NO_ENERGY;
         }else if(production + energyFromHolon > consumption) {
             state = (HolonObjectState.OVER_SUPPLIED);

+ 1 - 1
src/holeg/preferences/ColorPreference.java

@@ -31,7 +31,7 @@ public class ColorPreference {
         public static final Color Supplied = new Color(13, 175, 28);
         public static final Color PartiallySupplied = new Color(255, 233, 1);
         public static final Color NotSupplied = new Color(230, 120, 100);
-        public static final Color NoEnergy = new Color(211, 211, 211);
+        public static final Color NoEnergy = new Color(239, 239, 239);
 
         public static Color getStateColor(HolonObjectState state) {
             return switch (state) {

+ 1 - 0
src/holeg/preferences/PreferenceKeys.java

@@ -7,6 +7,7 @@ public class PreferenceKeys {
         public static final String YPos = "YPos";
         public static final String Width = "Width";
         public static final String Height = "Height";
+        public static final String SupplyBarVisible = "SupplyBarVisible";
     }
     public static class EmailNotification{
         public static final String Hostname = "Hostname";

+ 24 - 61
src/holeg/ui/controller/Control.java

@@ -8,12 +8,10 @@ import holeg.ui.model.GuiSettings;
 import holeg.ui.model.IdCounter;
 import holeg.ui.model.UndoHistory;
 import holeg.ui.view.category.Category;
-import holeg.ui.view.dialog.CreateTemplatePopUp;
 import holeg.utility.events.Action;
 import holeg.utility.events.Event;
 import holeg.utility.math.vector.Vec2i;
 
-import javax.swing.*;
 import java.io.File;
 import java.io.FileReader;
 import java.io.FileWriter;
@@ -21,6 +19,7 @@ import java.io.IOException;
 import java.util.*;
 import java.util.logging.Logger;
 import java.util.prefs.Preferences;
+import java.util.spi.AbstractResourceBundleProvider;
 import java.util.stream.Collectors;
 
 import static holeg.serialize.ModelDeserializer.gson;
@@ -67,15 +66,6 @@ public class Control {
         saveCategories();
     }
 
-    /**
-     * Gives all Category as String
-     *
-     * @return a array of strings from all Categorys
-     */
-    public String[] getCategoriesStrings() {
-        return GuiSettings.getCategories().stream().map(Category::getName).toArray(String[]::new);
-    }
-
     /**
      * Add new Holon Object to a Category.
      */
@@ -85,20 +75,10 @@ public class Control {
         saveCategories();
     }
 
-    /**
-     * Add new Holon Switch to a Category.
-     *
-     * @param cat Category
-     * @param obj New Object Name
-     */
-    public void addSwitch(Category cat, String obj) {
-        addNewHolonSwitch(cat, obj);
-        OnCategoryChanged.broadcast();
-        saveCategories();
-    }
 
     public void deleteCategory(Category category) {
-        removeCategory(category);
+        GuiSettings.getCategories().remove(category);
+        OnCategoryChanged.broadcast();
         saveCategories();
     }
 
@@ -114,7 +94,7 @@ public class Control {
     /**
      * removes a selectedObject from selection.
      *
-     * @param obj Cpsobject
+     * @param obj
      */
     public void removeObjectFromSelection(AbstractCanvasObject obj) {
         if (GuiSettings.getSelectedObjects().remove(obj)) {
@@ -159,7 +139,7 @@ public class Control {
      *
      * @param obj AbstractCpsObject
      */
-    public void deleteCanvasObject(AbstractCanvasObject obj) {
+    public void deleteObject(AbstractCanvasObject obj) {
         canvasController.deleteObject(obj);
         if (obj instanceof GroupNode groupnode) {
             canvasController.deleteAllObjectsInGroupNode(groupnode);
@@ -224,18 +204,6 @@ public class Control {
 
 
 
-    /**
-     * Removes an Edge from the Canvas.
-     *
-     * @param edge the edge to remove
-     */
-    public void removeEdgesOnCanvas(Edge edge) {
-        canvasController.removeEdgesOnCanvas(edge);
-        OnCanvasUpdate.broadcast();
-    }
-
-
-
     public void calculateStateForCurrentIteration() {
         simulationManager.calculateStateForIteration(model.getCurrentIteration());
     }
@@ -274,30 +242,41 @@ public class Control {
     }
 
 
-    public void replaceObject(AbstractCanvasObject toBeReplaced, AbstractCanvasObject by) {
-        canvasController.replaceObject(toBeReplaced, by);
-    }
-
     /**
      * Copy all Selected Objects.
      */
     public void copy() {
         GuiSettings.getClipboardObjects().clear();
         GuiSettings.getClipboardObjects().addAll(GuiSettings.getSelectedObjects());
+        GuiSettings.getClipboardEdges().clear();
+        GuiSettings.getClipboardEdges().addAll(getEdgesBetweenObjects(GuiSettings.getSelectedObjects()));
+    }
+
+    private List<Edge> getEdgesBetweenObjects(Collection<AbstractCanvasObject> selectedObjects) {
+        return model.getEdgesOnCanvas().stream()
+                .filter(edge -> selectedObjects.containsAll(Arrays.asList(edge.getA(), edge.getB()))).toList();
     }
 
     public void paste(GroupNode groupNode, Vec2i offset) {
         if (GuiSettings.getClipboardObjects().isEmpty()) {
             return;
         }
-        Set<AbstractCanvasObject> copies = GuiSettings.getClipboardObjects().stream().map(AbstractCanvasObject::copy).collect(Collectors.toSet());
+        HashMap<AbstractCanvasObject, AbstractCanvasObject> oldToNew = new HashMap<>();
+        Collection<AbstractCanvasObject> copies = GuiSettings.getClipboardObjects().stream().map(obj -> {
+            AbstractCanvasObject copy = obj.copy();
+            oldToNew.put(obj, copy);
+            return copy;
+        }).toList();
         copies.forEach(obj -> {
             obj.getPosition().addAssign(offset);
             obj.getPosition().clampX(0, GuiSettings.canvasSize.getX());
             obj.getPosition().clampY(0, GuiSettings.canvasSize.getY());
         });
         groupNode.addAll(copies);
-        updateStateForIteration(model.getCurrentIteration());
+        Collection<Edge> copyEdges =  GuiSettings.getClipboardEdges().stream().map(
+                edge -> new Edge(oldToNew.get(edge.getA()), oldToNew.get(edge.getB()), edge.maxCapacity)).toList();
+        model.getEdgesOnCanvas().addAll(copyEdges);
+        updateStateForCurrentIteration();
         OnSelectionChanged.broadcast();
     }
 
@@ -323,7 +302,8 @@ public class Control {
         HolonObject powerPlant = addNewHolonObject(energy, "Power Plant", new ArrayList<>(),
                 ImagePreference.Canvas.DefaultObject.PowerPlant);
         HolonObject house = addNewHolonObject(building, "House", new ArrayList<>(), ImagePreference.Canvas.DefaultObject.House);
-        addNewHolonSwitch(component, "Switch");
+        HolonSwitch sw = new HolonSwitch("Switch");
+        component.getObjects().add(sw);
         powerPlant.add(new HolonElement(null, "Power", 10000));
         energy.getObjects().add(powerPlant);
 
@@ -359,16 +339,6 @@ public class Control {
     }
 
 
-    /**
-     * remove a Category from Model.
-     *
-     * @param c Category
-     */
-    public void removeCategory(Category c) {
-        GuiSettings.getCategories().remove(c);
-        OnCategoryChanged.broadcast();
-    }
-
 
     /**
      * Add Object into a Category.
@@ -405,13 +375,6 @@ public class Control {
     }
 
 
-    public HolonSwitch addNewHolonSwitch(Category cat, String objName) {
-        HolonSwitch holonSwitch = new HolonSwitch(objName);
-        addObject(cat, holonSwitch);
-        return holonSwitch;
-    }
-
-
     public Optional<Category> findCategoryWithName(String categoryName) {
         return GuiSettings.getCategories().stream().filter(cat -> cat.getName().equals(categoryName)).findAny();
     }

+ 4 - 7
src/holeg/ui/model/GuiSettings.java

@@ -25,14 +25,8 @@ public class GuiSettings {
     private static final Set<Edge> selectedEdges = new HashSet<>();
     private static final Set<Category> categories = new HashSet<>();
     private static final Set<AbstractCanvasObject> clipboardObjects = new HashSet<>();
+    private static final Set<Edge> clipboardEdges = new HashSet<>();
 	private static final Set<AbstractCanvasObject> selectedObjects = new HashSet<>();
-    
-	public static int autoSaveNr = -1;
-
-
-
-
-
 
 
     public static float dragThresholdDistance = 5;
@@ -68,6 +62,9 @@ public class GuiSettings {
 	public static Set<AbstractCanvasObject> getClipboardObjects() {
 		return clipboardObjects;
 	}
+	public static Set<Edge> getClipboardEdges() {
+		return clipboardEdges;
+	}
 	public static Set<AbstractCanvasObject> getSelectedObjects() {
 		return selectedObjects;
 	}

+ 0 - 4
src/holeg/ui/model/UndoHistory.java

@@ -39,8 +39,4 @@ public class UndoHistory {
         jsonSaves.add(save);
     }
 
-
-
-
-
 }

+ 1 - 1
src/holeg/ui/view/canvas/Rendering.java

@@ -42,7 +42,7 @@ class Rendering {
         g.fillRect(pos.getX() - GuiSettings.getPictureScaleDiv2(), pos.getY() - GuiSettings.getPictureScaleDiv2(),
                 GuiSettings.getPictureScale(), GuiSettings.getPictureScale());
         drawCanvasObject(g, hO.getImagePath(), pos);
-        if (GuiSettings.showSupplyBars && hO.getActualEnergy() <= 0) {
+        if (GuiSettings.showSupplyBars && (hO.isConsumer() && !hO.getState().equals(HolonObject.HolonObjectState.NO_ENERGY) )) {
             drawSupplyBar(g, hO.getSupplyBarPercentage(), stateColor, pos);
         }
     }

+ 1 - 3
src/holeg/ui/view/category/CategoryPanel.java

@@ -81,7 +81,7 @@ public class CategoryPanel extends JScrollPane {
         }));
         removeItem.addActionListener(clicked -> getSelectedNode().ifPresent(selectedNode -> {
             if (selectedNode instanceof CategoryTreeNode node) {
-                GuiSettings.getCategories().remove(node.category);
+                control.deleteCategory(node.getCategory());
             } else if (selectedNode instanceof ObjectTreeNode node) {
                 node.getCategory().getObjects().remove(node.getObject());
             }
@@ -175,8 +175,6 @@ public class CategoryPanel extends JScrollPane {
         public void openEdit(){
             if(object instanceof HolonObject hO){
                 new AddObjectPopUp(control, hO, category, gui);
-            }else if(object instanceof HolonSwitch holonSwitch){
-                log.info("Edit Switch");
             }
         }
     }

+ 5 - 7
src/holeg/ui/view/dialog/AddObjectPopUp.java

@@ -18,6 +18,7 @@ import java.awt.event.KeyListener;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 import java.io.*;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.logging.Logger;
 
@@ -85,9 +86,7 @@ public class AddObjectPopUp extends JDialog {
 					objectName.setBackground(Color.WHITE);
 				}
 			});
-			if (true) {
-				objectName.setText(obj.getName());
-			}
+			objectName.setText(obj.getName());
 			objectName.setBounds(98, 18, 172, 20);
 			contentPanel.add(objectName);
 			objectName.setColumns(10);
@@ -158,14 +157,14 @@ public class AddObjectPopUp extends JDialog {
 			contentPanel.add(scrollPane);
 			{
 
-				listModel = new DefaultListModel<String>();
+				listModel = new DefaultListModel<>();
 
 				/*
 				 * 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);
+				list = new JList<>(listModel);
 				scrollPane.setViewportView(list);
 			}
 		}
@@ -267,7 +266,7 @@ public class AddObjectPopUp extends JDialog {
 			File source = new File(filePath);
 			//TODO: "CopieFile"
 			File dest = new File(System.getProperty("user.home") + "/.config/HolonGUI/Images/");
-			dest.mkdirs();
+			Files.createDirectories(dest.toPath());
 			dest = new File(dest, selectedFile.getName());
 			imagePath = "" + dest;
 
@@ -282,7 +281,6 @@ public class AddObjectPopUp extends JDialog {
 
 			inStream.close();
 			outStream.close();
-			System.out.println("File Copied..");
 		} catch (IOException eex) {
 			eex.printStackTrace();
 		}

+ 17 - 19
src/holeg/ui/view/dialog/EditEdgesPopUp.java

@@ -18,9 +18,9 @@ import java.awt.*;
 public class EditEdgesPopUp extends JDialog {
 	private final JTextField capacityField;
 	private float capacity;
-	private final JRadioButton rdbtnChangeForAll;
-	private final JRadioButton rdbtnChangeForNew;
-	private final JRadioButton rdbtnChangeForAll1;
+	private final JRadioButton existingEdgesRadioButton = new JRadioButton("Change for all existing Edges only");
+	private final JRadioButton newEdgesRadioButton = new JRadioButton("Change for new created Edges only");
+	private final JRadioButton existingAndNewEdgesRadioButton = new JRadioButton("Change for all existing and new created Edges");
 	private final Control control;
 
 
@@ -49,17 +49,14 @@ public class EditEdgesPopUp extends JDialog {
 		contentPanel.add(capacityField);
 		capacityField.setColumns(10);
 
-		rdbtnChangeForAll = new JRadioButton("Change for all existing Edges only");
-		rdbtnChangeForAll.setBounds(10, 39, 330, 23);
-		contentPanel.add(rdbtnChangeForAll);
+		existingEdgesRadioButton.setBounds(10, 39, 330, 23);
+		contentPanel.add(existingEdgesRadioButton);
 
-		rdbtnChangeForNew = new JRadioButton("Change for new created Edges only");
-		rdbtnChangeForNew.setBounds(10, 65, 330, 23);
-		contentPanel.add(rdbtnChangeForNew);
+		newEdgesRadioButton.setBounds(10, 65, 330, 23);
+		contentPanel.add(newEdgesRadioButton);
 
-		rdbtnChangeForAll1 = new JRadioButton("Change for all existing and new created Edges");
-		rdbtnChangeForAll1.setBounds(10, 95, 400, 23);
-		contentPanel.add(rdbtnChangeForAll1);
+		existingAndNewEdgesRadioButton.setBounds(10, 95, 400, 23);
+		contentPanel.add(existingAndNewEdgesRadioButton);
 
 		JButton btnCancel = new JButton("Cancel");
 		btnCancel.setActionCommand("Cancel");
@@ -75,13 +72,13 @@ public class EditEdgesPopUp extends JDialog {
 					if (capacity < 0) {
 						throw new NumberFormatException();
 					}
-					if (rdbtnChangeForAll.isSelected()) {
+					if (existingEdgesRadioButton.isSelected()) {
 						changeForExisting(capacity);
 						dispose();
-					} else if (rdbtnChangeForNew.isSelected()) {
+					} else if (newEdgesRadioButton.isSelected()) {
 						changeForNew(capacity);
 						dispose();
-					} else if (rdbtnChangeForAll1.isSelected()) {
+					} else if (existingAndNewEdgesRadioButton.isSelected()) {
 						changeForExAndNew(capacity);
 						dispose();
 					} else {
@@ -95,9 +92,10 @@ public class EditEdgesPopUp extends JDialog {
 		contentPanel.add(btnOk1);
 		this.setTitle("Edit Edge Capacities");
 		ButtonGroup bG = new ButtonGroup();
-		bG.add(rdbtnChangeForAll1);
-		bG.add(rdbtnChangeForNew);
-		bG.add(rdbtnChangeForAll);
+		bG.add(existingAndNewEdgesRadioButton);
+		bG.add(newEdgesRadioButton);
+		bG.add(existingEdgesRadioButton);
+		existingAndNewEdgesRadioButton.setSelected(true);
 		this.control = control;
 		this.setVisible(true);
 	}
@@ -130,7 +128,7 @@ public class EditEdgesPopUp extends JDialog {
 			edge.maxCapacity = cap;
         }
 		control.resetSimulation();
-		control.calculateStateForCurrentIteration();
+		control.updateStateForCurrentIteration();
 	}
 
 

+ 4 - 6
src/holeg/ui/view/image/Import.java

@@ -23,11 +23,9 @@ public class Import {
 	 * images that were found as external file. Save raw: Save all non-scaled
 	 * images. Save everything: self-explanatory.
 	 */
-	private static HashMap<String, Image> imgStorage;
-	private static Import xmp = new Import();// Used to load resources from the JAR.
-
+	private static final HashMap<String, Image> imgStorage;
 	static {
-		imgStorage = new HashMap<String, Image>();
+		imgStorage = new HashMap<>();
 	}
 
 	/**
@@ -93,10 +91,10 @@ public class Import {
 	 * 
 	 * @param url The path (and file name) of the requested resource.
 	 * @return An InputStream from the requested resource.
-	 * @throws FileNotFoundException
+	 * @throws FileNotFoundException if file cannot be found
 	 */
 	public static InputStream loadStream(String url) throws FileNotFoundException {
-		InputStream o = xmp.getClass().getResourceAsStream(url);
+		InputStream o = InputStream.class.getResourceAsStream(url);
 		if (o != null)
 			return o;
 		else {

+ 2 - 2
src/holeg/ui/view/inspector/InspectorTable.java

@@ -64,7 +64,6 @@ public class InspectorTable extends JPanel {
 	private int actualPage = 0;
 	private int maxPageNumberForThisSelection = 0;
 	private final Control control;
-	private final int columnHeight = 20;
 	// UI
 	private final TrippleCheckBox selectAllCheckBox = new TrippleCheckBox();
 	private final JButton addButton = new JButton();
@@ -425,6 +424,7 @@ public class InspectorTable extends JPanel {
 				updateButtonAppearance();
 				updateElementSelection();
 			});
+			int columnHeight = 20;
 			selectedColumnPanel.setMinimumSize(new Dimension(columnHeight, columnHeight));
 			selectedColumnPanel.setPreferredSize(new Dimension(columnHeight, columnHeight));
 			selectedColumnPanel.setMaximumSize(new Dimension(columnHeight, columnHeight));
@@ -464,7 +464,7 @@ public class InspectorTable extends JPanel {
 					float energy = Float.parseFloat(energyTextField.getText());
 					if (this.element.getEnergy() != energy) {
 						this.element.setEnergy(energy);
-						control.calculateStateForCurrentIteration();
+						control.updateStateForCurrentIteration();
 					}
 				} catch (NumberFormatException e) {
 					// Dont Update

+ 7 - 1
src/holeg/ui/view/main/Gui.java

@@ -77,6 +77,7 @@ public class Gui extends JFrame {
         } else {
             this.setLocationRelativeTo(null);
         }
+        GuiSettings.showSupplyBars = prefs.getBoolean(PreferenceKeys.Gui.SupplyBarVisible, true);
         this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
         this.addWindowListener((WindowClosingListener) e -> {
             Rectangle bounds = this.getBounds();
@@ -84,6 +85,7 @@ public class Gui extends JFrame {
             prefs.putInt(PreferenceKeys.Gui.YPos, bounds.y);
             prefs.putInt(PreferenceKeys.Gui.Width, bounds.width);
             prefs.putInt(PreferenceKeys.Gui.Height, bounds.height);
+            prefs.putBoolean(PreferenceKeys.Gui.SupplyBarVisible, GuiSettings.showSupplyBars);
             control.saveCategories();
             if (JOptionPane.showConfirmDialog(this, "Are you sure you want to exit?", "HOLEG",
                     JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
@@ -176,7 +178,7 @@ public class Gui extends JFrame {
         //ViewMenu
         private final JMenu appearanceMenu = new JMenu("Appearance");
         private final JMenuItem canvasSizeButton = new JMenuItem("Set View Size");
-        private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem("Show supply bars.", true);
+        private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem("Show supply bars.", GuiSettings.showSupplyBars);
         private final JFileChooser fileChooser = initFileChooser();
 
         private final static int IconSize = 15;
@@ -340,12 +342,16 @@ public class Gui extends JFrame {
             ungroupButton.setAccelerator(KeyStroke.getKeyStroke('U', defaultModifier));
             alignAllButton.setAccelerator(KeyStroke.getKeyStroke('L', defaultModifier));
             removeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0));
+            algorithmButton.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.ALT_DOWN_MASK));
+            outlinerButton.setAccelerator(KeyStroke.getKeyStroke('O', InputEvent.ALT_DOWN_MASK));
+            flexMenuButton.setAccelerator(KeyStroke.getKeyStroke('F', InputEvent.ALT_DOWN_MASK));
         }
 
 
 
         private void toggleSupplyBarAppearance() {
             GuiSettings.showSupplyBars = showSupplyBarsCheckBox.isSelected();
+            control.OnCanvasUpdate.broadcast();
         }
 
         private void saveFile() {

+ 1 - 1
src/holeg/ui/view/main/TimePanel.java

@@ -165,7 +165,7 @@ public class TimePanel extends JPanel implements ActionListener {
 				timeSlider.setValue(timeSlider.getMinimum());
 				control.getModel().setCurrentIteration(timeSlider.getValue());
 				control.resetSimulation();
-				control.calculateStateForCurrentIteration();
+				control.updateStateForCurrentIteration();
 				if (running) {
 					play();
 				}

+ 578 - 663
src/holeg/ui/view/window/FlexWindow.java

@@ -1,15 +1,22 @@
 package holeg.ui.view.window;
 
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
+import holeg.model.*;
+import holeg.model.Flexibility.FlexState;
+import holeg.model.HolonElement.Priority;
+import holeg.preferences.ColorPreference;
+import holeg.preferences.ImagePreference;
+import holeg.ui.controller.Control;
+import holeg.ui.view.image.Import;
+import holeg.utility.listener.WindowClosingListener;
+
+import javax.swing.*;
+import javax.swing.border.EmptyBorder;
+import javax.swing.text.NumberFormatter;
+import javax.swing.tree.DefaultMutableTreeNode;
+import javax.swing.tree.DefaultTreeModel;
+import javax.swing.tree.TreePath;
+import java.awt.*;
 import java.awt.Dialog.ModalityType;
-import java.awt.Dimension;
-import java.awt.FlowLayout;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.awt.Rectangle;
 import java.awt.event.ItemEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
@@ -18,673 +25,581 @@ import java.math.RoundingMode;
 import java.text.NumberFormat;
 import java.util.List;
 import java.util.Locale;
+import java.util.Optional;
 import java.util.stream.Collectors;
 
-import javax.swing.BorderFactory;
-import javax.swing.Box;
-import javax.swing.BoxLayout;
-import javax.swing.DefaultComboBoxModel;
-import javax.swing.ImageIcon;
-import javax.swing.JButton;
-import javax.swing.JCheckBox;
-import javax.swing.JComboBox;
-import javax.swing.JDialog;
-import javax.swing.JFormattedTextField;
-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.JTabbedPane;
-import javax.swing.JTree;
-import javax.swing.SwingUtilities;
-import javax.swing.border.EmptyBorder;
-import javax.swing.text.NumberFormatter;
-import javax.swing.tree.DefaultMutableTreeNode;
-import javax.swing.tree.DefaultTreeModel;
-import javax.swing.tree.TreePath;
-
-import holeg.model.Constrain;
-import holeg.model.Flexibility;
-import holeg.model.Flexibility.FlexState;
-import holeg.model.GroupNode;
-import holeg.model.HolonElement;
-import holeg.model.HolonElement.Priority;
-import holeg.model.HolonObject;
-import holeg.preferences.ColorPreference;
-import holeg.preferences.ImagePreference;
-import holeg.ui.controller.Control;
-import holeg.ui.view.image.Import;
-import holeg.utility.listener.WindowClosingListener;
-
 
 public class FlexWindow extends JFrame {
-	private JPanel nothingSelectedPanel;
-	private JPanel selectedPanel;
-	
-	
-	private final JTabbedPane contentPanel = new JTabbedPane();
-	private JScrollPane usageViewPanel;
-	private final static int boxWidth = 70;
-	private final Control control;
-	
-	public boolean isClosed = false;
-	
-	//Flexibility Intermediate
-	private final Flexibility intermediateFlex = new Flexibility(null);
-	private boolean offered = true, onConstrain = true, offConstrain =false;
-	
-	
-	
-	//JTree
-	private DefaultMutableTreeNode listOfAllSelectedHolonObjects;
-	private JTree stateTree;
-	private DefaultTreeModel treeModel;
-	
-	//Tabs
-	String gridTabString = "Grid";
-	String orderTabString = "Order";
-	
-	Runnable update = this::update;
-	
-	public FlexWindow(JFrame parentFrame, Control  control){
-		this.intermediateFlex.name = "name";
-		this.control = control;
-		//InitWindow
-		createMenuBar();
-		initWindowPanel(parentFrame);
-		this.addWindowListener((WindowClosingListener) e -> {
-			control.OnCanvasUpdate.removeListener(update);
-		});
-		updateSelectedPanel();
-		control.OnCanvasUpdate.addListener(update);
-	}
-
-
-
-	private void initWindowPanel(JFrame parentFrame) {
-		this.setBounds(0, 0, 400, parentFrame.getHeight()>20?parentFrame.getHeight()- 20:parentFrame.getHeight());
-		this.setIconImage(Import.loadImage(ImagePreference.Logo, 30, 30));
-		this.setTitle("Flexibility");
-		this.setLocationRelativeTo(parentFrame);
-		this.setVisible(true);
-		//this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
-		createNothingSelectedPanel();
-		createSelectedPanel();
-		createUsageViewPanel();
-		contentPanel.addTab(gridTabString, nothingSelectedPanel);
-		contentPanel.addTab(orderTabString, usageViewPanel);
-		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
-		this.setContentPane(contentPanel);
-		this.revalidate();
-		
+    private final static int boxSideLength = 70;
+    private final JTabbedPane contentPanel = new JTabbedPane();
+    private final Control control;
+    //Flexibility Intermediate
+    private final Flexibility intermediateFlex = new Flexibility(null);
+    //Tabs
+    String gridTabString = "Grid";
+    String orderTabString = "Order";
+    private JPanel nothingSelectedPanel;
+    private JPanel selectedPanel;
+    private JScrollPane usageViewPanel;
+    private boolean offered = true, onConstrain = true, offConstrain = false;
+    //JTree
+    private DefaultMutableTreeNode listOfAllSelectedHolonObjects;
+    private JTree stateTree;
+    private DefaultTreeModel treeModel;
+	private final JPopupMenu menu = new JPopupMenu();
+	private final JMenuItem priorityItem = new JMenuItem("EditPriorities");
+	private final JMenuItem flexItem = new JMenuItem("AddFlex");
+
+
+    Runnable update = this::update;
+
+    public FlexWindow(JFrame parentFrame, Control control) {
+        this.intermediateFlex.name = "name";
+        this.control = control;
+        //InitWindow
+        createMenuBar();
+        initWindowPanel(parentFrame);
+        this.addWindowListener((WindowClosingListener) e -> control.OnCanvasUpdate.removeListener(update));
+        updateSelectedPanel();
+        control.OnCanvasUpdate.addListener(update);
+    }
+
+
+    private void initWindowPanel(JFrame parentFrame) {
+        this.setBounds(0, 0, 400, parentFrame.getHeight() > 20 ? parentFrame.getHeight() - 20 : parentFrame.getHeight());
+        this.setIconImage(Import.loadImage(ImagePreference.Logo, 30, 30));
+        this.setTitle("Flexibility");
+        this.setLocationRelativeTo(parentFrame);
+        this.setVisible(true);
+        //this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+        createNothingSelectedPanel();
+        createSelectedPanel();
+        createUsageViewPanel();
+        contentPanel.addTab(gridTabString, nothingSelectedPanel);
+        contentPanel.addTab(orderTabString, usageViewPanel);
+        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
+        this.setContentPane(contentPanel);
+        this.revalidate();
+
+    }
+
+    private void createMenuBar() {
+        JMenuBar menuBar = new JMenuBar();
+        JMenu canvas = new JMenu("Canvas");
+        menuBar.add(canvas);
+        JMenuItem updateMenuItem = new JMenuItem("Update");
+        updateMenuItem.addActionListener(clicked -> updateSelectedPanel());
+        canvas.add(updateMenuItem);
+        JMenu flex = new JMenu("Flex");
+        menuBar.add(flex);
+        JMenuItem addMenuItem = new JMenuItem("Add Flexibility");
+        addMenuItem.addActionListener(clicked -> createAddDialog(null));
+        flex.add(addMenuItem);
+        JMenuItem deleteMenuItem = new JMenuItem("Delete Flexibility");
+        deleteMenuItem.addActionListener(clicked -> createDeleteDialog());
+        flex.add(deleteMenuItem);
+
+        this.setJMenuBar(menuBar);
+    }
+
+
+    private void createUsageViewPanel() {
+        JPanel panel = new JPanel(new GridBagLayout());
+        usageViewPanel = new JScrollPane(panel);
+        panel.setBackground(Color.white);
+        FlexState[] titles = FlexState.values();
+
+
+        for (int i = 0; i < 5; i++) {
+            final int titleIndex = i;
+            List<Flexibility> flexList = control.getModel().getAllFlexibilities();
+            List<Flexibility> listOfFlexWithState = flexList.stream().filter(flex -> flex.getState().equals(titles[titleIndex])).toList();
+            JLabel label = new JLabel(titles[i].toString() + "[" + listOfFlexWithState.size() + "]");
+            GridBagConstraints labelC = new GridBagConstraints();
+            labelC.gridx = 1;
+            labelC.gridy = i * 2;
+            labelC.anchor = GridBagConstraints.LINE_START;
+            labelC.fill = GridBagConstraints.HORIZONTAL;
+            labelC.weightx = 0.5;
+            labelC.weighty = 0.0;
+            panel.add(label, labelC);
+
+            JPanel listPanel = new JPanel(new GridBagLayout());
+            createFlexPanel(listPanel, listOfFlexWithState);
+            GridBagConstraints panelC = new GridBagConstraints();
+            panelC.gridx = 0;
+            panelC.gridwidth = 2;
+            panelC.gridy = i * 2 + 1;
+            panelC.fill = GridBagConstraints.BOTH;
+            panel.add(listPanel, panelC);
+
+
+            JButton expandButton = new JButton("-");
+            GridBagConstraints buttonC = new GridBagConstraints();
+            buttonC.gridx = 0;
+            buttonC.gridy = i * 2;
+            panel.add(expandButton, buttonC);
+            expandButton.addActionListener(clicked -> {
+                listPanel.setVisible(!listPanel.isVisible());
+                expandButton.setText(listPanel.isVisible() ? "-" : "+");
+            });
+
+        }
+        //Add Spacer
+        JLabel spacer = new JLabel();
+        GridBagConstraints c = new GridBagConstraints();
+        c.gridx = 0;
+        c.gridy = 5 * 2;
+        c.fill = GridBagConstraints.VERTICAL;
+        c.weightx = 0.0;
+        c.weighty = 1;
+        panel.add(spacer, c);
+    }
+
+
+    private void createFlexPanel(JPanel listPanel, List<Flexibility> flexList) {
+        listPanel.setBackground(Color.white);
+        Insets insets = new Insets(2, 2, 2, 2);
+        int panelWidth = Math.max(boxSideLength, this.getWidth() - 90);
+        int maxButtonsPerLine = panelWidth / boxSideLength;
+
+
+        int i = 0;
+        for (Flexibility flex : flexList) {
+            GridBagConstraints c = new GridBagConstraints();
+            c.gridx = Math.floorMod(i, maxButtonsPerLine);
+            c.weightx = 0.0;
+            c.insets = insets;
+            JButton labelButton = new JButton(flex.name);
+            labelButton.setPreferredSize(new Dimension(boxSideLength, boxSideLength));
+            labelButton.setBorder(BorderFactory.createLineBorder(Color.black));
+            listPanel.add(labelButton, c);
+            labelButton.addActionListener(clicked -> {
+                flex.order();
+                control.calculateStateForCurrentIteration();
+            });
+            labelButton.setToolTipText(createToolTip(flex));
+            i++;
+        }
+        //AddSpacer
+        JLabel spacer = new JLabel();
+        GridBagConstraints c = new GridBagConstraints();
+        c.gridx = maxButtonsPerLine;
+        c.gridy = 0;
+        c.fill = GridBagConstraints.VERTICAL;
+        c.weightx = 1;
+        c.weighty = 0;
+
+        listPanel.add(spacer, c);
+    }
+
+
+    private String createToolTip(Flexibility actual) {
+        return "<html>" +
+                "<b>" + actual.name + "( </b>" + actual.getElement().getName() + "<b> )</b><br>"
+                + ((actual.remainingDuration() != 0) ? "<i>Remaining Duration:" + actual.remainingDuration() + "</i><br>" : "")
+                + ((actual.remainingTimeTillActivation() != 0) ? "<i>Remaining TimeTillActivation:" + actual.remainingTimeTillActivation() + "</i><br>" : "")
+                + "Duration: " + actual.getDuration() + "<br>"
+                + "Cooldown: " + actual.getCooldown() + "<br>"
+                + "Cost: " + actual.cost + "<br>"
+                + "EnergyReleased: " + actual.energyReleased() + "<br>"
+                + "Constrains: " + actual.constrainList.stream().map(Constrain::getName).collect(Collectors.joining(",")) + "<br>"
+                + "</html>";
+    }
+
+
+    public void update() {
+        updateSelectedPanel();
+        createUsageViewPanel();
+        contentPanel.setComponentAt(contentPanel.indexOfTab(orderTabString), usageViewPanel);
+        contentPanel.revalidate();
+    }
+
+
+    private void createSelectedPanel() {
+        listOfAllSelectedHolonObjects = new DefaultMutableTreeNode("HolonObjects");
+        treeModel = new DefaultTreeModel(listOfAllSelectedHolonObjects);
+        stateTree = new JTree(treeModel);
+		JPopupMenu menu = createPopUpMenu();
+
+
+		stateTree.addMouseListener(new MouseAdapter() {
+            public void mousePressed(MouseEvent e) {
+                if (SwingUtilities.isRightMouseButton(e)) {
+
+
+                    TreePath pathUnderCursor = stateTree.getPathForLocation(e.getX(), e.getY());
+                    Rectangle pathBounds = stateTree.getUI().getPathBounds(stateTree, pathUnderCursor);
+                    if (pathBounds != null && pathBounds.contains(e.getX(), e.getY())) {
+                        TreePath[] selectedPaths = stateTree.getSelectionPaths();
+                        if (selectedPaths == null) {
+                            stateTree.addSelectionPath(pathUnderCursor);
+                        } else {
+                            boolean isInSelectedPaths = false;
+                            for (TreePath path : stateTree.getSelectionPaths()) {
+                                if (path.equals(pathUnderCursor)) {
+                                    isInSelectedPaths = true;
+                                    break;
+                                }
+                            }
+                            if (!isInSelectedPaths) {
+                                stateTree.clearSelection();
+                                stateTree.addSelectionPath(pathUnderCursor);
+                            }
+                        }
+
+                        menu.show(stateTree, pathBounds.x, pathBounds.y + pathBounds.height);
+                    }
+                }
+            }
+        });
+        selectedPanel = new JPanel(new BorderLayout());
+        selectedPanel.add(new JScrollPane(stateTree));
+    }
+
+	private JPopupMenu createPopUpMenu() {
+		priorityItem.addActionListener(clicked -> getInfoFromSelection().ifPresent(eleInfo -> {
+			Priority priority = (Priority) JOptionPane.showInputDialog(stateTree,
+						"Select the Priority:", "Priority?", JOptionPane.INFORMATION_MESSAGE,
+						new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)),
+						Priority.values(), "");
+			if (priority == null){
+				return;
+			}
+			eleInfo.ele.setPriority(priority);
+			control.updateStateForCurrentIteration();
+		}));
+		flexItem.addActionListener(clicked -> getInfoFromSelection().ifPresent(eleInfo -> createAddDialog(eleInfo.ele)));
+		menu.add(priorityItem);
+		menu.add(flexItem);
+		return menu;
 	}
 
-	private void createMenuBar(){
-		JMenuBar menuBar = new JMenuBar();
-		JMenu canvas = new JMenu("Canvas");
-		menuBar.add(canvas);
-		JMenuItem updateMenuItem = new JMenuItem("Update");
-		updateMenuItem.addActionListener(clicked -> updateSelectedPanel());
-		canvas.add(updateMenuItem);
-		JMenu flex = new JMenu("Flex");
-		menuBar.add(flex);
-		JMenuItem addMenuItem = new JMenuItem("Add Flexibility");
-		addMenuItem.addActionListener(clicked -> createAddDialog(null));
-		flex.add(addMenuItem);
-		JMenuItem deleteMenuItem = new JMenuItem("Delete Flexibility");
-		deleteMenuItem.addActionListener(clicked -> createDeleteDialog());
-		flex.add(deleteMenuItem);
-		
-		this.setJMenuBar(menuBar);
-	}
-	
-	
-
-	
-	private void createUsageViewPanel() {
-		//GridBagApprouch
-		JPanel gridbagPanel =  new JPanel(new GridBagLayout());
-		usageViewPanel = new JScrollPane(gridbagPanel);
-		gridbagPanel.setBackground(Color.white);
-		//5breit
-		FlexState[] titles = FlexState.values();
-		
-		
-		
-		for(int i = 0; i<5; i++){
-			final int titileIndex = i;
-			List<Flexibility> flexList = control.getModel().getAllFlexibilities();
-			List<Flexibility> listOfFlexWithState = flexList.stream().filter(flex -> flex.getState().equals(titles[titileIndex])).toList();
-			JLabel label = new JLabel(titles[i].toString() + "[" + listOfFlexWithState.size()+ "]");									
-			GridBagConstraints labelC = new GridBagConstraints();
-			labelC.gridx = 1;
-			labelC.gridy = i*2;
-			labelC.anchor = GridBagConstraints.LINE_START;
-			labelC.fill = GridBagConstraints.HORIZONTAL;
-			labelC.weightx = 0.5;
-			labelC.weighty = 0.0;
-			gridbagPanel.add(label, labelC);
-			
-			JPanel listPanel = new JPanel(new GridBagLayout());
-			createFlexPanel(listPanel, listOfFlexWithState);
-			GridBagConstraints panelC = new GridBagConstraints();
-			panelC.gridx = 0;
-			panelC.gridwidth = 2;
-			panelC.gridy = i*2 +1;
-			panelC.fill = GridBagConstraints.BOTH;
-			gridbagPanel.add(listPanel, panelC);
-
-			
-			
-			JButton expandButton = new JButton("-");
-			GridBagConstraints buttonC = new GridBagConstraints();
-			buttonC.gridx = 0;
-			buttonC.gridy = i*2;
-			gridbagPanel.add(expandButton, buttonC);
-			expandButton.addActionListener(clicked -> {
-				listPanel.setVisible(!listPanel.isVisible());
-				expandButton.setText(listPanel.isVisible()?"-":"+");
-			});
-			
+	private Optional<ElementInfo> getInfoFromSelection(){
+		TreePath path = stateTree.getSelectionPath();
+		if (path == null){
+			return Optional.empty();
 		}
-		//Add Spacer
-		JLabel spacer = new JLabel();
-		GridBagConstraints c = new GridBagConstraints();
-		c.gridx = 0;
-		c.gridy = 5*2;
-		c.fill = GridBagConstraints.VERTICAL;
-		c.weightx = 0.0;
-		c.weighty = 1;
-		gridbagPanel.add(spacer, c);
-	}
-
-	
-
-
-	private void createFlexPanel(JPanel listPanel, List<Flexibility> flexList) {
-		listPanel.setBackground(Color.white);
-		Insets insets = new Insets(2,2,2,2);
-		int panelWidth = Math.max(boxWidth, this.getWidth() - 90);
-		int maxButtonsPerLine = panelWidth / boxWidth;
-		
-		
-		int i = 0;
-		for(Flexibility flex: flexList) {
-			GridBagConstraints c = new GridBagConstraints();
-			c.gridx = Math.floorMod(i, maxButtonsPerLine);
-			c.weightx = 0.0;	
-			c.insets = insets;
-			JButton labelButton = new JButton(flex.name);
-			labelButton.setPreferredSize(new Dimension(boxWidth,boxWidth));
-			labelButton.setBorder(BorderFactory.createLineBorder(Color.black));
-			listPanel.add(labelButton, c);
-			labelButton.addActionListener(clicked ->{
-				flex.order();
-				control.calculateStateForCurrentIteration();
-			});
-			labelButton.setToolTipText(createToolTipp(flex));
-			i++;
+		Object userObject = ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
+		if(userObject instanceof ElementInfo eleInfo){
+			return Optional.of(eleInfo);
 		}
-		//AddSpacer
-		JLabel spacer = new JLabel();
-		GridBagConstraints c = new GridBagConstraints();
-		c.gridx = maxButtonsPerLine;
-		c.gridy = 0;
-		c.fill = GridBagConstraints.VERTICAL;
-		c.weightx = 1;
-		c.weighty = 0;
-	
-		listPanel.add(spacer, c);
-		i++;
-	}
-
-
-	private String createToolTipp(Flexibility actual) {
-		return "<html>" +
-	"<b>" + actual.name + "( </b>" + actual.getElement().getName() + "<b> )</b><br>"
-	+ ((actual.remainingDuration() != 0)?"<i>Remaining Duration:"+ actual.remainingDuration()+"</i><br>":"")
-	+ ((actual.remainingTimeTillActivation() != 0)?"<i>Remaining TimeTillActivation:"+ actual.remainingTimeTillActivation()+"</i><br>":"")
-	+ "Duration: " + actual.getDuration()  + "<br>"
-	+ "Cooldown: " + actual.getCooldown() + "<br>"
-	+ "Cost: " + actual.cost + "<br>"
-	+ "EnergyReleased: " + actual.energyReleased() + "<br>"
-	+ "Constrains: " + actual.constrainList.stream().map(Constrain::getName).collect(Collectors.joining( "," )) + "<br>"
-	+ "</html>";
-	}
-
-
-
-	public void update() {
-		updateSelectedPanel();
-		createUsageViewPanel();
-		contentPanel.setComponentAt(contentPanel.indexOfTab(orderTabString), usageViewPanel);
-		contentPanel.revalidate();
+		return Optional.empty();
 	}
 
-	
-	
-	
-	private void createSelectedPanel() {
-		//Liste aller Flexibilities
-		listOfAllSelectedHolonObjects = new DefaultMutableTreeNode("HolonObjects");
-		treeModel = new DefaultTreeModel(listOfAllSelectedHolonObjects);
-		stateTree = new JTree(treeModel);
-		stateTree.addMouseListener ( new MouseAdapter ()
-		    {
-		        public void mousePressed ( MouseEvent e )
-		        {
-		            if ( SwingUtilities.isRightMouseButton ( e ) )
-		            {
-		            	
-		            	
-		                TreePath pathUnderCursor = stateTree.getPathForLocation ( e.getX (), e.getY () );
-		                Rectangle pathBounds = stateTree.getUI ().getPathBounds ( stateTree, pathUnderCursor );
-		                if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
-		                {
-		                	TreePath[] selectedPaths = stateTree.getSelectionPaths();
-			   	        	if(selectedPaths == null) {
-			   	        		stateTree.addSelectionPath(pathUnderCursor);
-			   	        	}else {
-			   	        		boolean isInselectedPaths = false;
-			   	        		for (TreePath path : stateTree.getSelectionPaths()) {
-			   	        			if(path.equals(pathUnderCursor)) {
-			   	        				isInselectedPaths = true;
-			   	        			}
-			   	        		}
-			   	        		if(!isInselectedPaths) {
-			   	        			stateTree.clearSelection();
-			   	        			stateTree.addSelectionPath(pathUnderCursor);
-			   	        		}
-			   	        	}
-		                    JPopupMenu menu = new JPopupMenu ();
-		                    JMenuItem priorityItem = new JMenuItem("EditPriorities");
-			         	    JMenuItem flexItem = new JMenuItem("AddFlex");
-			         	    
-							priorityItem.addActionListener(clicked -> {
-								Priority prio = null;
-								if (stateTree.getSelectionPaths() != null)
-									for (TreePath path : stateTree.getSelectionPaths()) {
-										Object treeNodeUserObject = ((DefaultMutableTreeNode) path.getLastPathComponent())
-												.getUserObject();
-										if (treeNodeUserObject instanceof ElementInfo eleInfo) {
-											if (prio == null)
-												prio = (Priority) JOptionPane.showInputDialog(stateTree,
-														"Select the Priority:", "Priority?", JOptionPane.OK_OPTION,
-														new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)),
-														Priority.values(), "");
-											if (prio == null)
-												break;
-											eleInfo.ele.setPriority(prio);
-											treeModel.reload((DefaultMutableTreeNode) path.getLastPathComponent());
-										}
-									}
-							});
-							flexItem.addActionListener(clicked -> {
-								TreePath path = stateTree.getSelectionPath();
-								if (path == null)
-									return;
-								Object treeNodeUserObject = ((DefaultMutableTreeNode) path.getLastPathComponent())
-										.getUserObject();
-								if (treeNodeUserObject instanceof ElementInfo eleInfo) {
-									createAddDialog(eleInfo.ele);									
-								}else {
-									return;									
-								}
-			   	        });
-			         	    
-		                    menu.add ( priorityItem );
-		                    menu.add ( flexItem );
-		                    menu.show ( stateTree, pathBounds.x, pathBounds.y + pathBounds.height );
-		                }else {
-		                	JPopupMenu menu = new JPopupMenu ();
-		                    menu.add ( new JMenuItem ( "Other Test" ) );
-		                    menu.show ( stateTree, e.getX(), e.getY() );
-		                }
-		            }
-		        }
-		    } );
-		selectedPanel = new JPanel(new BorderLayout());
-		selectedPanel.add(new JScrollPane(stateTree));
-	}
 
 
 	private void createNothingSelectedPanel() {
-		nothingSelectedPanel = new JPanel();
-		nothingSelectedPanel.setLayout(new BoxLayout(nothingSelectedPanel, BoxLayout.PAGE_AXIS));
-		JLabel nothingSelectedTextLabel = new JLabel("No HolonObject exist.");
-		nothingSelectedTextLabel.setForeground(Color.gray);
-		nothingSelectedTextLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
-		nothingSelectedPanel.add(Box.createVerticalGlue());
-		nothingSelectedPanel.add(nothingSelectedTextLabel);
-		nothingSelectedPanel.add(Box.createVerticalGlue());
-	}
-	
-	public void updateSelectedPanel() {
-		//Should not remove add so many Components
-		
-		listOfAllSelectedHolonObjects.removeAllChildren();
-		//Init with HolonObjects
-		control.getModel().getCanvas().getObjectsInThisLayer().forEach(aCps -> {
-			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(aCps.getName() + " ID:" + aCps.getId());
-			if(aCps instanceof HolonObject hO) expandTreeHolonObject(hO, newObjectChild);
-			if(aCps instanceof GroupNode groupnode)expandTreeUpperNode(groupnode, newObjectChild);
-			listOfAllSelectedHolonObjects.add(newObjectChild);			
-		});
-		treeModel.nodeStructureChanged(listOfAllSelectedHolonObjects);
-	
-		stateTree.revalidate();
-		expandAll(stateTree);
-		selectedPanel.revalidate();
-		contentPanel.setComponentAt(contentPanel.indexOfTab(gridTabString), selectedPanel);
-		contentPanel.revalidate();
-		this.revalidate();
-	}
-
-
-
-	private void expandAll(JTree tree) {
-		for(int i = 0; i< tree.getRowCount() ; i++) {
-			tree.expandRow(i);
-		}
-		
-	}
-
-
-
-	private void expandTreeUpperNode(GroupNode groupNode, DefaultMutableTreeNode root) {
-		groupNode.getHolonObjects().forEach(object -> {
-			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(object.getName() + " ID:" + object.getId());
-			root.add(newObjectChild);
-		});
-		groupNode.getGroupNodes().forEach(groupnode -> {
-			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(groupnode.getName() + " ID:" + groupnode.getId());
-			expandTreeUpperNode(groupnode, newObjectChild);
-			root.add(newObjectChild);
-		});
-	}
-
-
+        nothingSelectedPanel = new JPanel();
+        nothingSelectedPanel.setLayout(new BoxLayout(nothingSelectedPanel, BoxLayout.PAGE_AXIS));
+        JLabel nothingSelectedTextLabel = new JLabel("No HolonObject exist.");
+        nothingSelectedTextLabel.setForeground(Color.gray);
+        nothingSelectedTextLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
+        nothingSelectedPanel.add(Box.createVerticalGlue());
+        nothingSelectedPanel.add(nothingSelectedTextLabel);
+        nothingSelectedPanel.add(Box.createVerticalGlue());
+    }
+
+    public void updateSelectedPanel() {
+        //Should not remove add so many Components
+
+        listOfAllSelectedHolonObjects.removeAllChildren();
+        //Init with HolonObjects
+        control.getModel().getCanvas().getObjectsInThisLayer().forEach(aCps -> {
+            DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(aCps.getName() + " ID:" + aCps.getId());
+            if (aCps instanceof HolonObject hO) expandTreeHolonObject(hO, newObjectChild);
+            if (aCps instanceof GroupNode groupnode) expandTreeUpperNode(groupnode, newObjectChild);
+            listOfAllSelectedHolonObjects.add(newObjectChild);
+        });
+        treeModel.nodeStructureChanged(listOfAllSelectedHolonObjects);
+
+        stateTree.revalidate();
+        expandAll(stateTree);
+        selectedPanel.revalidate();
+        contentPanel.setComponentAt(contentPanel.indexOfTab(gridTabString), selectedPanel);
+        contentPanel.revalidate();
+        this.revalidate();
+    }
+
+
+    private void expandAll(JTree tree) {
+        for (int i = 0; i < tree.getRowCount(); i++) {
+            tree.expandRow(i);
+        }
+
+    }
+
+
+    private void expandTreeUpperNode(GroupNode groupNode, DefaultMutableTreeNode root) {
+        groupNode.getHolonObjects().forEach(object -> {
+            DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(object.getName() + " ID:" + object.getId());
+            root.add(newObjectChild);
+        });
+        groupNode.getGroupNodes().forEach(childGroupNode -> {
+            DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(childGroupNode.getName() + " ID:" + childGroupNode.getId());
+            expandTreeUpperNode(childGroupNode, newObjectChild);
+            root.add(newObjectChild);
+        });
+    }
+
+
+    private void expandTreeHolonObject(HolonObject hObject, DefaultMutableTreeNode root) {
+        hObject.elementsStream().forEach(hE -> {
+            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(new ElementInfo(hE));
+            expandTreeFlex(hE, newChild);
+            root.add(newChild);
+        });
+    }
+
+    private void expandTreeFlex(HolonElement hElement, DefaultMutableTreeNode root) {
+        for (Flexibility flex : hElement.flexList) {
+            String flexState;
+            Color color = ColorPreference.Flexibility.getStateColor(flex.getState());
+            flexState = "<font bgcolor='#" + Integer.toHexString(color.getRGB()).substring(2) + "'>" + flex.getState().name() + "</font>";
+            DefaultMutableTreeNode newChild = new DefaultMutableTreeNode("<html>" + flexState + " <b>" + flex.name + "</b>" + "</html>");
+            root.add(newChild);
+        }
+    }
+
+
+    private void createDeleteDialog() {
+        Object[] allFlexes = control.getModel().getAllFlexibilities().toArray();
+        if (allFlexes.length == 0) {
+            JOptionPane.showMessageDialog(this,
+                    "No Flexibility exist.",
+                    "Warning",
+                    JOptionPane.WARNING_MESSAGE);
+            return;
+        }
+
+        Flexibility toDeleteFlex = (Flexibility) JOptionPane.showInputDialog(this, "Select to Delete Flexibility:", "Flexibility?", JOptionPane.INFORMATION_MESSAGE, new ImageIcon(new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB)), allFlexes, "");
+        if (toDeleteFlex != null) {
+            toDeleteFlex.getElement().flexList.remove(toDeleteFlex);
+            control.calculateStateForCurrentIteration();
+            updateSelectedPanel();
+        }
+    }
+
+
+    //Add Element
+    private void createAddDialog(HolonElement element) {
+        if (control.getModel().getCanvas().getAllHolonObjectsRecursive().findAny().isEmpty()) {
+            JOptionPane.showMessageDialog(this,
+                    "No HolonObject exist.",
+                    "Warning",
+                    JOptionPane.WARNING_MESSAGE);
+            return;
+        }
+        JDialog addDialog = new JDialog();
+        addDialog.setTitle("Create Flexibility");
+        addDialog.setBounds(0, 0, 820, 400);
+        addDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
+        JPanel dialogPanel = new JPanel(new BorderLayout());
+        addDialog.setContentPane(dialogPanel);
+        JPanel selectionPanel = new JPanel(null);
+        dialogPanel.add(selectionPanel, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
+        dialogPanel.add(buttonPanel, BorderLayout.PAGE_END);
+
+
+        addDialog.setModalityType(ModalityType.APPLICATION_MODAL);
+
+
+        //Create HolonObject selection Box
+        HolonObject[] holonObjects = control.getModel().getCanvas().getAllHolonObjectsRecursive().toArray(HolonObject[]::new);
+
+        DefaultComboBoxModel<HolonObject> comboBoxModel = new DefaultComboBoxModel<>(holonObjects);
+
+
+        JComboBox<HolonObject> holonObjectSelector = new JComboBox<>(comboBoxModel);
+        holonObjectSelector.setBounds(10, 30, 800, 30);
+
+        DefaultComboBoxModel<HolonElement> comboBoxModelElements = new DefaultComboBoxModel<>(holonObjects[0].elementsStream().toArray(HolonElement[]::new));
+        JComboBox<HolonElement> holonElementSelector = new JComboBox<>(comboBoxModelElements);
+        holonElementSelector.setBounds(10, 80, 800, 30);
+
+
+        holonObjectSelector.addItemListener(aListener -> {
+            if (aListener.getStateChange() == ItemEvent.SELECTED) {
+                DefaultComboBoxModel<HolonElement> newComboBoxModelElements = new DefaultComboBoxModel<>(((HolonObject) aListener.getItem()).elementsStream().toArray(HolonElement[]::new));
+                holonElementSelector.setModel(newComboBoxModelElements);
+            }
+        });
+
+        if (element == null) {
+            selectionPanel.add(holonObjectSelector);
+            selectionPanel.add(holonElementSelector);
+            JLabel selectObjectLabel = new JLabel("Select HolonObject:");
+            selectObjectLabel.setBounds(10, 10, 200, 20);
+            selectionPanel.add(selectObjectLabel);
+            JLabel selectElementLabel = new JLabel("Select HolonElement:");
+            selectElementLabel.setBounds(10, 60, 200, 20);
+            selectionPanel.add(selectElementLabel);
+        } else {
+            JLabel selectElementLabel = new JLabel("Selected: " + element);
+            selectElementLabel.setBounds(10, 60, 2000, 20);
+            selectionPanel.add(selectElementLabel);
+        }
+
+
+        JPanel flexAttributesBorderPanel = new JPanel(null);
+        flexAttributesBorderPanel.setBounds(10, 120, 800, 200);
+        flexAttributesBorderPanel.setBorder(BorderFactory.createTitledBorder("Flexibility Attributes"));
+        selectionPanel.add(flexAttributesBorderPanel);
+        JLabel flexNameLabel = new JLabel("Name:");
+        flexNameLabel.setBounds(10, 20, 50, 20);
+        flexAttributesBorderPanel.add(flexNameLabel);
+        JFormattedTextField nameTextField = new JFormattedTextField(intermediateFlex.name);
+        nameTextField.addPropertyChangeListener(changed -> intermediateFlex.name = nameTextField.getText());
+        nameTextField.setBounds(80, 15, 200, 30);
+        flexAttributesBorderPanel.add(nameTextField);
+        JLabel flexSpeedLabel = new JLabel("Speed:");
+        flexSpeedLabel.setBounds(10, 55, 50, 20);
+        flexAttributesBorderPanel.add(flexSpeedLabel);
+        //Integer formatter
+        NumberFormat format = NumberFormat.getIntegerInstance();
+        format.setGroupingUsed(false);
+        format.setParseIntegerOnly(true);
+        NumberFormatter integerFormatter = new NumberFormatter(format);
+        integerFormatter.setMinimum(0);
+        integerFormatter.setCommitsOnValidEdit(true);
+
+
+        JFormattedTextField speedTextField = new JFormattedTextField(integerFormatter);
+        speedTextField.setValue(intermediateFlex.speed);
+        speedTextField.setToolTipText("Only positive Integer.");
+        speedTextField.addPropertyChangeListener(actionEvent -> intermediateFlex.speed = Integer.parseInt(speedTextField.getValue().toString()));
+        speedTextField.setBounds(80, 50, 200, 30);
+        flexAttributesBorderPanel.add(speedTextField);
+        speedTextField.setEnabled(false);
+
+        JLabel flexDurationLabel = new JLabel("Duration:");
+        flexDurationLabel.setBounds(10, 90, 70, 20);
+        flexAttributesBorderPanel.add(flexDurationLabel);
+
+
+        NumberFormatter moreThenZeroIntegerFormatter = new NumberFormatter(format);
+        moreThenZeroIntegerFormatter.setMinimum(1);
+        moreThenZeroIntegerFormatter.setCommitsOnValidEdit(true);
+
+        JFormattedTextField durationTextField = new JFormattedTextField(moreThenZeroIntegerFormatter);
+        durationTextField.setValue(intermediateFlex.getDuration());
+        durationTextField.setToolTipText("Only positive Integer bigger then 0.");
+        durationTextField.addPropertyChangeListener(actionEvent -> intermediateFlex.setDuration(Integer.parseInt(durationTextField.getValue().toString())));
+        durationTextField.setBounds(80, 85, 200, 30);
+        flexAttributesBorderPanel.add(durationTextField);
+
+        JLabel flexCostsLabel = new JLabel("Costs:");
+        flexCostsLabel.setBounds(10, 125, 70, 20);
+        flexAttributesBorderPanel.add(flexCostsLabel);
+
+        //Double Format:
+        NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
+        doubleFormat.setMinimumFractionDigits(1);
+        doubleFormat.setMaximumFractionDigits(2);
+        doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
+
+        //CostFormatter:
+        NumberFormatter costsFormatter = new NumberFormatter(doubleFormat);
+        costsFormatter.setMinimum(0.0);
+
+        JFormattedTextField costTextField = new JFormattedTextField(costsFormatter);
+        costTextField.setValue(intermediateFlex.cost);
+        costTextField.setToolTipText("Only non negative Double with DecimalSeparator Point('.').");
+        costTextField.addPropertyChangeListener(propertyChange -> intermediateFlex.cost = Float.parseFloat(costTextField.getValue().toString()));
+        costTextField.setBounds(80, 120, 200, 30);
+        flexAttributesBorderPanel.add(costTextField);
+
+
+        JLabel flexCooldownLabel = new JLabel("Cooldown:");
+        flexCooldownLabel.setBounds(310, 20, 70, 20);
+        flexAttributesBorderPanel.add(flexCooldownLabel);
+
+
+        JFormattedTextField cooldownTextField = new JFormattedTextField(moreThenZeroIntegerFormatter);
+        cooldownTextField.setValue(intermediateFlex.getCooldown());
+        cooldownTextField.setToolTipText("Only positive Integer.");
+        cooldownTextField.addPropertyChangeListener(actionEvent -> intermediateFlex.setCooldown(Integer.parseInt(cooldownTextField.getValue().toString())));
+        cooldownTextField.setBounds(380, 15, 200, 30);
+        flexAttributesBorderPanel.add(cooldownTextField);
+
+        JCheckBox offeredCheckBox = new JCheckBox("Offered");
+        offeredCheckBox.setSelected(this.offered);
+        offeredCheckBox.setBounds(310, 55, 200, 20);
+        flexAttributesBorderPanel.add(offeredCheckBox);
+
+        JCheckBox onConstrainCheckBox = new JCheckBox("On_Constrain");
+        onConstrainCheckBox.setSelected(this.onConstrain);
+        onConstrainCheckBox.setBounds(310, 80, 200, 20);
+        flexAttributesBorderPanel.add(onConstrainCheckBox);
+
+        JCheckBox offConstrainCheckBox = new JCheckBox("Off_Constrain");
+        offConstrainCheckBox.setSelected(this.offConstrain);
+        offConstrainCheckBox.setBounds(310, 105, 200, 20);
+        flexAttributesBorderPanel.add(offConstrainCheckBox);
+
+
+        //Both cant be true....
+        onConstrainCheckBox.addActionListener(clicked -> {
+            if (onConstrainCheckBox.isSelected()) offConstrainCheckBox.setSelected(false);
+        });
+        offConstrainCheckBox.addActionListener(clicked -> {
+            if (offConstrainCheckBox.isSelected()) onConstrainCheckBox.setSelected(false);
+        });
+
+        JButton createFlexButton = new JButton("Create");
+        createFlexButton.addActionListener(clicked -> {
+            HolonElement ele;
+            if (element == null) {
+                ele = (HolonElement) holonElementSelector.getSelectedItem();
+            } else {
+                ele = element;
+            }
+            Flexibility toCreateFlex = new Flexibility(ele);
+            toCreateFlex.name = intermediateFlex.name;
+            toCreateFlex.speed = intermediateFlex.speed;
+            toCreateFlex.setDuration(intermediateFlex.getDuration());
+            toCreateFlex.cost = intermediateFlex.cost;
+            toCreateFlex.setCooldown(intermediateFlex.getCooldown());
+            toCreateFlex.offered = offeredCheckBox.isSelected();
+            if (onConstrainCheckBox.isSelected()) toCreateFlex.constrainList.add(Constrain.createOnConstrain());
+            if (offConstrainCheckBox.isSelected()) toCreateFlex.constrainList.add(Constrain.createOffConstrain());
+
+            assert ele != null;
+            ele.flexList.add(toCreateFlex);
+            //save checkboxes
+            this.offered = offeredCheckBox.isSelected();
+            this.onConstrain = onConstrainCheckBox.isSelected();
+            this.offConstrain = offConstrainCheckBox.isSelected();
+
+
+            control.updateStateForCurrentIteration();
+            addDialog.dispose();
+        });
+        buttonPanel.add(createFlexButton);
+        JButton cancelButton = new JButton("Cancel");
+        cancelButton.addActionListener(clicked -> addDialog.dispose());
+        buttonPanel.add(cancelButton);
+
+
+        //last
+        addDialog.setLocationRelativeTo(this);
+        addDialog.setVisible(true);
+    }
+
+
+    static class ElementInfo {
+        HolonElement ele;
+
+        public ElementInfo(HolonElement ele) {
+            this.ele = ele;
+        }
+
+        @Override
+        public String toString() {
+            return ele.getName() + " Priority:" + ele.getPriority();
+        }
+    }
 
-	private void expandTreeHolonObject(HolonObject hObject, DefaultMutableTreeNode root) {
-		hObject.elementsStream().forEach(hE -> {
-			DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(new ElementInfo(hE));
-			expandTreeFlex(hE, newChild);
-			root.add(newChild);			
-		});
-	}
-	private void expandTreeFlex(HolonElement hElement, DefaultMutableTreeNode root) {
-		for(Flexibility flex: hElement.flexList) {
-			String flexState = "";
-			Color color = ColorPreference.Flexibility.getStateColor(flex.getState());
-			flexState = "<font bgcolor='#" + Integer.toHexString(color.getRGB()).substring(2) + "'>" + flex.getState().name() + "</font>";
-			DefaultMutableTreeNode newChild = new DefaultMutableTreeNode("<html>"+ flexState + " <b>" + flex.name+ "</b>" + "</html>");
-			root.add(newChild);
-		}
-	}
-	
-	
-	private void createDeleteDialog() {
-		Object[] allFlexes = control.getModel().getAllFlexibilities().toArray();
-		if(allFlexes.length == 0) {
-			JOptionPane.showMessageDialog(this,
-					"No Flexibility exist.",
-					"Warning",
-					JOptionPane.WARNING_MESSAGE);
-			return;
-		}
-		
-		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);
-			control.calculateStateForCurrentIteration();
-			updateSelectedPanel();
-		}
-	}
-	
-	
-	
-
-
-
-	//Add Element
-	private void createAddDialog(HolonElement element){
-		if(control.getModel().getCanvas().getAllHolonObjectsRecursive().findAny().isEmpty()) {
-			JOptionPane.showMessageDialog(this,
-					"No HolonObject exist.",
-					"Warning",
-					JOptionPane.WARNING_MESSAGE);
-			return;
-		}
-		JDialog addDialog = new JDialog();
-		addDialog.setTitle("Create Flexibility");
-		addDialog.setBounds(0, 0, 820, 400);	
-		addDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
-		JPanel dialogPanel = new JPanel(new BorderLayout());
-		addDialog.setContentPane(dialogPanel);
-		JPanel selectionPanel = new JPanel(null);
-		dialogPanel.add(selectionPanel, BorderLayout.CENTER);
-		JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
-		dialogPanel.add(buttonPanel, BorderLayout.PAGE_END);
-		
-		
-		
-		
-		addDialog.setModalityType(ModalityType.APPLICATION_MODAL);
-		
-		
-
-		//Create HolonObject selection Box
-		HolonObject[] holonObjects = control.getModel().getCanvas().getAllHolonObjectsRecursive().toArray(HolonObject[]::new);
-
-		DefaultComboBoxModel<HolonObject> comboBoxModel = new DefaultComboBoxModel<HolonObject>( holonObjects );
-
-
-		JComboBox<HolonObject> holonObjectSelector = new JComboBox<HolonObject>(comboBoxModel);
-		holonObjectSelector.setBounds(10,30, 800, 30);
-		
-		DefaultComboBoxModel<HolonElement> comboBoxModelElements = new DefaultComboBoxModel<HolonElement>( holonObjects[0].elementsStream().toArray(size -> new HolonElement[size]));
-		JComboBox<HolonElement> holonElementSelector  = new JComboBox<HolonElement>(comboBoxModelElements);
-		holonElementSelector.setBounds(10,80, 800, 30);
-		
-		
-		holonObjectSelector.addItemListener(aListener -> {
-			if(aListener.getStateChange() == ItemEvent.SELECTED) {
-				DefaultComboBoxModel<HolonElement> newComboBoxModelElements = new DefaultComboBoxModel<HolonElement>( ((HolonObject) aListener.getItem()).elementsStream().toArray(size -> new HolonElement[size]));
-				holonElementSelector.setModel(newComboBoxModelElements);
-			}
-		});
-			
-		if(element == null) {
-			selectionPanel.add(holonObjectSelector);
-			selectionPanel.add(holonElementSelector);
-			JLabel selectObjectLabel = new JLabel("Select HolonObject:");
-			selectObjectLabel.setBounds(10, 10, 200, 20);
-			selectionPanel.add(selectObjectLabel);
-			JLabel selectElementLabel = new JLabel("Select HolonElement:");
-			selectElementLabel.setBounds(10, 60, 200, 20);
-			selectionPanel.add(selectElementLabel);
-		}
-		else {
-			JLabel selectElementLabel = new JLabel("Selected: " +element.toString());
-			selectElementLabel.setBounds(10, 60, 2000, 20);
-			selectionPanel.add(selectElementLabel);
-		}
-		
-		
-		
-		
-		
-		
-		JPanel flexAttributesBorderPanel = new  JPanel(null);
-		flexAttributesBorderPanel.setBounds(10, 120, 800, 200);
-		flexAttributesBorderPanel.setBorder(BorderFactory.createTitledBorder("Flexibility Attributes"));
-		selectionPanel.add(flexAttributesBorderPanel);	
-		JLabel flexNameLabel = new JLabel("Name:");
-		flexNameLabel.setBounds(10,20, 50, 20);
-		flexAttributesBorderPanel.add(flexNameLabel);
-		JFormattedTextField nameTextField = new JFormattedTextField(intermediateFlex.name);
-		nameTextField.addPropertyChangeListener(changed -> intermediateFlex.name = nameTextField.getText());
-		nameTextField.setBounds(80, 15, 200, 30);
-		flexAttributesBorderPanel.add(nameTextField);
-		JLabel flexSpeedLabel = new JLabel("Speed:");
-		flexSpeedLabel.setBounds(10,55, 50, 20);
-		flexAttributesBorderPanel.add(flexSpeedLabel);
-		//Integer formatter
-		NumberFormat format = NumberFormat.getIntegerInstance();
-		format.setGroupingUsed(false);
-		format.setParseIntegerOnly(true);
-		NumberFormatter integerFormatter = new NumberFormatter(format);
-		integerFormatter.setMinimum(0);
-		integerFormatter.setCommitsOnValidEdit(true);
-		
-		
-		JFormattedTextField speedTextField = new  JFormattedTextField(integerFormatter);
-		speedTextField.setValue(intermediateFlex.speed);
-		speedTextField.setToolTipText("Only positive Integer.");
-		speedTextField.addPropertyChangeListener(actionEvent -> intermediateFlex.speed = Integer.parseInt(speedTextField.getValue().toString()));
-		speedTextField.setBounds(80, 50, 200, 30);
-		flexAttributesBorderPanel.add(speedTextField);
-		speedTextField.setEnabled(false);
-		
-		JLabel flexDurationLabel = new JLabel("Duration:");
-		flexDurationLabel.setBounds(10,90, 70, 20);
-		flexAttributesBorderPanel.add(flexDurationLabel);
-		
-		
-		NumberFormatter moreThenZeroIntegerFormatter = new NumberFormatter(format);
-		moreThenZeroIntegerFormatter.setMinimum(1);
-		moreThenZeroIntegerFormatter.setCommitsOnValidEdit(true);
-		
-		JFormattedTextField durationTextField = new  JFormattedTextField(moreThenZeroIntegerFormatter);
-		durationTextField.setValue(intermediateFlex.getDuration());
-		durationTextField.setToolTipText("Only positive Integer bigger then 0.");
-		durationTextField.addPropertyChangeListener(actionEvent -> intermediateFlex.setDuration(Integer.parseInt(durationTextField.getValue().toString())));
-		durationTextField.setBounds(80, 85, 200, 30);
-		flexAttributesBorderPanel.add(durationTextField);
-		
-		JLabel flexCostsLabel = new JLabel("Costs:");
-		flexCostsLabel.setBounds(10,125, 70, 20);
-		flexAttributesBorderPanel.add(flexCostsLabel);
-		
-		//Double Format:
-		NumberFormat doubleFormat = NumberFormat.getNumberInstance(Locale.US);
-		doubleFormat.setMinimumFractionDigits(1);
-		doubleFormat.setMaximumFractionDigits(2);
-		doubleFormat.setRoundingMode(RoundingMode.HALF_UP);
-
-		//CostFormatter:
-		NumberFormatter costsFormatter = new NumberFormatter(doubleFormat);
-		costsFormatter.setMinimum(0.0);
-		
-		JFormattedTextField costTextField = new JFormattedTextField(costsFormatter);
-		costTextField.setValue(intermediateFlex.cost);
-		costTextField.setToolTipText("Only non negative Double with DecimalSeperator Point('.').");
-		costTextField.addPropertyChangeListener(propertyChange -> intermediateFlex.cost = Float.parseFloat(costTextField.getValue().toString()));
-		costTextField.setBounds(80, 120, 200, 30);
-		flexAttributesBorderPanel.add(costTextField);
-		
-		
-		
-		JLabel flexCooldownLabel = new JLabel("Cooldown:");
-		flexCooldownLabel.setBounds(310,20, 70, 20);
-		flexAttributesBorderPanel.add(flexCooldownLabel);
-		
-		
-		JFormattedTextField cooldownTextField = new  JFormattedTextField(moreThenZeroIntegerFormatter);
-		cooldownTextField.setValue(intermediateFlex.getCooldown());
-		cooldownTextField.setToolTipText("Only positive Integer.");
-		cooldownTextField.addPropertyChangeListener(actionEvent -> intermediateFlex.setCooldown(Integer.parseInt(cooldownTextField.getValue().toString())));
-		cooldownTextField.setBounds(380, 15, 200, 30);
-		flexAttributesBorderPanel.add(cooldownTextField);
-		
-		JCheckBox offeredCheckBox = new JCheckBox("Offered");
-		offeredCheckBox.setSelected(this.offered);
-		offeredCheckBox.setBounds(310, 55, 200, 20);
-		flexAttributesBorderPanel.add(offeredCheckBox);
-		
-		JCheckBox onConstrainCheckBox = new JCheckBox("On_Constrain");
-		onConstrainCheckBox.setSelected(this.onConstrain);
-		onConstrainCheckBox.setBounds(310, 80, 200, 20);
-		flexAttributesBorderPanel.add(onConstrainCheckBox);
-		
-		JCheckBox offConstrainCheckBox = new JCheckBox("Off_Constrain");
-		offConstrainCheckBox.setSelected(this.offConstrain);
-		offConstrainCheckBox.setBounds(310, 105, 200, 20);
-		flexAttributesBorderPanel.add(offConstrainCheckBox);
-		
-		
-		
-		
-		//Both cant be true....
-		onConstrainCheckBox.addActionListener(clicked -> {
-			if(onConstrainCheckBox.isSelected()) offConstrainCheckBox.setSelected(false);
-			});
-		offConstrainCheckBox.addActionListener(clicked -> {
-			if(offConstrainCheckBox.isSelected()) onConstrainCheckBox.setSelected(false);
-			});
-		
-		JButton createFlexButton = new JButton("Create");
-		createFlexButton.addActionListener(clicked -> {
-			HolonElement ele;
-			if(element ==null) {				
-				ele = (HolonElement) holonElementSelector.getSelectedItem();
-			}else {
-				ele =  element;
-			}
-			Flexibility toCreateFlex = new Flexibility(ele);
-			toCreateFlex.name = intermediateFlex.name;
-			toCreateFlex.speed = intermediateFlex.speed;
-			toCreateFlex.setDuration(intermediateFlex.getDuration());
-			toCreateFlex.cost = intermediateFlex.cost;
-			toCreateFlex.setCooldown(intermediateFlex.getCooldown());
-			toCreateFlex.offered=offeredCheckBox.isSelected();
-			if(onConstrainCheckBox.isSelected())toCreateFlex.constrainList.add(Constrain.createOnConstrain());
-			if(offConstrainCheckBox.isSelected())toCreateFlex.constrainList.add(Constrain.createOffConstrain());
-
-			assert ele != null;
-			ele.flexList.add(toCreateFlex);
-			//save checkboxes
-			this.offered=offeredCheckBox.isSelected();
-			this.onConstrain = onConstrainCheckBox.isSelected();
-			this.offConstrain = offConstrainCheckBox.isSelected();
-			
-			
-			control.calculateStateForCurrentIteration();
-			
-			update();
-			addDialog.dispose();
-		});
-		buttonPanel.add(createFlexButton);
-		JButton cancelButton = new JButton("Cancel");
-		cancelButton.addActionListener(clicked -> {
-			addDialog.dispose();
-		});
-		buttonPanel.add(cancelButton);
-		
-		
-		
-		//last 
-		addDialog.setLocationRelativeTo(this);
-		addDialog.setVisible(true);
-	}
-	
-	
-	class ElementInfo {
-		HolonElement ele;
-		public ElementInfo(HolonElement ele) {
-			this.ele = ele;
-		}
-		@Override
-		public String toString() {
-			return ele.getName() + " Priority:" + ele.getPriority();
-		}
-	}
-	
 
-	
 }

+ 98 - 35
src/holeg/ui/view/window/Outliner.java

@@ -1,5 +1,7 @@
 package holeg.ui.view.window;
 
+import holeg.model.AbstractCanvasObject;
+import holeg.model.GroupNode;
 import holeg.model.Holon;
 import holeg.model.HolonObject;
 import holeg.preferences.ColorPreference;
@@ -14,13 +16,14 @@ import javax.swing.tree.DefaultMutableTreeNode;
 import javax.swing.tree.DefaultTreeCellRenderer;
 import java.awt.*;
 import java.util.logging.Logger;
+import java.util.stream.Stream;
 
 public class Outliner extends JFrame {
 	private static final Logger log = Logger.getLogger(Outliner.class.getName());
 	private final Control control;
 	JTabbedPane tabbedPane = new JTabbedPane();
-	JPanel listPanel = new JPanel(new BorderLayout());
-	JPanel statePanel = new JPanel(new BorderLayout());
+	JPanel hierarchyPanel = new JPanel(new BorderLayout());
+	JPanel holonPanel = new JPanel(new BorderLayout());
 	Runnable update = this::update;
 
 	private static final String ConsumptionFontHTMLBracket = "<font bgcolor='#"
@@ -29,6 +32,21 @@ public class Outliner extends JFrame {
 			+ Integer.toHexString(ColorPreference.Energy.Production.getRGB()).substring(2) + "'>";
 	private static final String FontClosingBracket = "</font> ";
 
+	private static final String ProducerNodeText = getColoredHtmlText(ColorPreference.HolonObject.Producer, "Producer");
+	private static final String OverSuppliedNodeText = getColoredHtmlText(ColorPreference.HolonObject.OverSupplied, "Over supplied");
+	private static final String SuppliedNodeText = getColoredHtmlText(ColorPreference.HolonObject.Supplied, "Supplied");
+	private static final String PartiallySuppliedNodeText = getColoredHtmlText(ColorPreference.HolonObject.PartiallySupplied, "Partially supplied");
+	private static final String NotSuppliedNodeText = getColoredHtmlText(ColorPreference.HolonObject.NotSupplied, "Not supplied");
+	private static final String NoEnergyNodeText = getColoredHtmlText(ColorPreference.HolonObject.NoEnergy, "No energy");
+
+	private static String getColoredHtmlText(Color color, String text){
+		return "<html><font bgcolor='#"
+				+ Integer.toHexString(color.getRGB()).substring(2) + "'>" +
+				text + FontClosingBracket;
+	}
+
+
+
 
 	public Outliner(JFrame parentFrame, Control control) {
 		setBounds(0, 0, 400, parentFrame.getHeight());
@@ -41,12 +59,13 @@ public class Outliner extends JFrame {
 		this.getContentPane().add(tabbedPane);
 		this.addWindowListener((WindowClosingListener) e -> control.OnCanvasUpdate.removeListener(update));
 		control.OnCanvasUpdate.addListener(update);
-		tabbedPane.addTab("State", statePanel);
+		tabbedPane.addTab("Hierarchy", hierarchyPanel);
+		tabbedPane.addTab("Holons", holonPanel);
 	}
 
 	public void update() {
-		listPanel.removeAll();
-		statePanel.removeAll();
+		hierarchyPanel.removeAll();
+		holonPanel.removeAll();
 		DefaultMutableTreeNode topListPanel = new DefaultMutableTreeNode();
 		DefaultMutableTreeNode objects = new DefaultMutableTreeNode("HolonObjects");
 		DefaultMutableTreeNode switches = new DefaultMutableTreeNode("Switches");
@@ -56,38 +75,84 @@ public class Outliner extends JFrame {
 		topListPanel.add(switches);
 		topListPanel.add(nodes);
 		topListPanel.add(cables);
-		DefaultMutableTreeNode topStatePanel = new DefaultMutableTreeNode();
+		DefaultMutableTreeNode topHolonNode = createHolonNode();
+		DefaultMutableTreeNode topHierarchyNode = createHierarchyNode();
+
+		JTree hierarchyTree = new JTree(topHierarchyNode);
+		signIconsForTree(hierarchyTree);
+		hierarchyTree.setRootVisible(false);
+		for (int i = 0; i < hierarchyTree.getRowCount(); i++) {
+			hierarchyTree.expandRow(i);
+		}
+		hierarchyPanel.add(new JScrollPane(hierarchyTree));
+
+		JTree holonTree = new JTree(topHolonNode);
+		signIconsForTree(holonTree);
+		holonTree.setRootVisible(false);
+		for (int i = 0; i < holonTree.getRowCount(); i++) {
+			holonTree.expandRow(i);
+		}
+		holonPanel.add(new JScrollPane(holonTree));
+
+		holonPanel.revalidate();
+		hierarchyPanel.repaint();
+	}
 
-		for (Holon dNet : control.getModel().holons) {
-			DefaultMutableTreeNode network = new DefaultMutableTreeNode("Holon");
-			for(HolonObject hObject : dNet.holonObjects){
+	private DefaultMutableTreeNode createHolonNode() {
+		DefaultMutableTreeNode topHolonNode = new DefaultMutableTreeNode();
+		for (Holon holon : control.getModel().holons) {
+			DefaultMutableTreeNode holonNode = new DefaultMutableTreeNode("Holon");
+			DefaultMutableTreeNode producer = new DefaultMutableTreeNode(ProducerNodeText);
+			DefaultMutableTreeNode overSupplied = new DefaultMutableTreeNode(OverSuppliedNodeText);
+			DefaultMutableTreeNode supplied = new DefaultMutableTreeNode(SuppliedNodeText);
+			DefaultMutableTreeNode partiallySupplied = new DefaultMutableTreeNode(PartiallySuppliedNodeText);
+			DefaultMutableTreeNode notSupplied = new DefaultMutableTreeNode(NotSuppliedNodeText);
+			DefaultMutableTreeNode noEnergy = new DefaultMutableTreeNode(NoEnergyNodeText);
+
+			for(HolonObject hObject : holon.holonObjects){
 				DefaultMutableTreeNode holonObjectNode = createColoredTreeNodeFromHolonObject(hObject);
-				network.add(holonObjectNode);
+				switch(hObject.getState()){
+					case PRODUCER -> producer.add(holonObjectNode);
+					case OVER_SUPPLIED -> overSupplied.add(holonObjectNode);
+					case SUPPLIED -> supplied.add(holonObjectNode);
+					case PARTIALLY_SUPPLIED -> partiallySupplied.add(holonObjectNode);
+					case NOT_SUPPLIED -> notSupplied.add(holonObjectNode);
+					case NO_ENERGY -> noEnergy.add(holonObjectNode);
+				}
 			}
-			topStatePanel.add(network);
+			Stream.of(producer, overSupplied, supplied, partiallySupplied, notSupplied, noEnergy)
+					.filter(node -> !node.isLeaf()).forEach(holonNode::add);
+			topHolonNode.add(holonNode);
 		}
-		JTree listTree = new JTree(topListPanel);
-		signIconsForTree(listTree);
-		listTree.setRootVisible(false);
-		for (int i = 0; i < listTree.getRowCount(); i++) {
-			listTree.expandRow(i);
-		}
-		JScrollPane listScroller = new JScrollPane(listTree);
-		listPanel.add(listScroller);
-
-		JTree stateTree = new JTree(topStatePanel);
-		signIconsForTree(stateTree);
-		stateTree.setRootVisible(false);
-		for (int i = 0; i < stateTree.getRowCount(); i++) {
-			stateTree.expandRow(i);
-		}
-		statePanel.add(new JScrollPane(stateTree));
+		return topHolonNode;
+	}
+	private DefaultMutableTreeNode createHierarchyNode() {
+		DefaultMutableTreeNode hierarchyNode = new DefaultMutableTreeNode();
+		hierarchyNode.add(getNodeFromGroupNode(control.getModel().getCanvas()));
+		DefaultMutableTreeNode edgeNode = new DefaultMutableTreeNode("Edges");
+		control.getModel().getEdgesOnCanvas().forEach(edge -> {
+			edgeNode.add(new DefaultMutableTreeNode(edge.toString()));
+		});
+		hierarchyNode.add(edgeNode);
+		return hierarchyNode;
+	}
+	private DefaultMutableTreeNode getNodeFromGroupNode(GroupNode groupNode){
+		DefaultMutableTreeNode node = new DefaultMutableTreeNode(groupNode.getName());
+		groupNode.getHolonObjects().forEach(obj -> node.add(canvasObjectToNode(obj)));
+		groupNode.getSwitches().forEach(obj -> node.add(canvasObjectToNode(obj)));
+		groupNode.getNodes().forEach(obj -> node.add(canvasObjectToNode(obj)));
+		groupNode.getGroupNodes().forEach(obj -> node.add(getNodeFromGroupNode(obj)));
+		return node;
+	}
 
-		listPanel.revalidate();
-		statePanel.revalidate();
-		listPanel.repaint();
+	private DefaultMutableTreeNode canvasObjectToNode(AbstractCanvasObject obj) {
+		return new DefaultMutableTreeNode(obj.getName() + " [" + obj.getId()+"]");
 	}
 
+
+
+
+
 	private void signIconsForTree(JTree t) {
 		ImageIcon ClosedIcon = new ImageIcon(Import.loadImage(ImagePreference.Button.Outliner.Closed, 9, 9));
 		ImageIcon OpenIcon = new ImageIcon(Import.loadImage(ImagePreference.Button.Outliner.Open, 9, 9));
@@ -101,11 +166,9 @@ public class Outliner extends JFrame {
 
 
 	private DefaultMutableTreeNode createColoredTreeNodeFromHolonObject(HolonObject obj){
-		String context = "<html>" + obj.getName() + "<font bgcolor='#"
-				+ Integer.toHexString(ColorPreference.HolonObject.getStateColor(obj.getState()).getRGB()).substring(2) + "'>" +
-				" " + obj.getState().toString() + FontClosingBracket
-				+ ConsumptionFontHTMLBracket + Format.doubleTwoPlaces(obj.getConsumption()) + FontClosingBracket
-				+ ProductionFontHTMLBracket + Format.doubleTwoPlaces(obj.getProduction()) + FontClosingBracket
+		float energy = obj.getActualEnergy();
+		String context = "<html>" + obj.getName() + "&nbsp;&nbsp;&nbsp;&nbsp;"
+				+ (obj.isConsumer()? ConsumptionFontHTMLBracket : ProductionFontHTMLBracket ) + Format.doubleTwoPlaces(energy) + FontClosingBracket
 				+ "</html>";
 		return new DefaultMutableTreeNode(context);
 	}