Browse Source

merged Xchart-integration

DESKTOP-L7IQHES\Jonas 2 years ago
parent
commit
a25049e2cb
47 changed files with 2488 additions and 1184 deletions
  1. 74 0
      jars/xchart-3.8.1/CONTRIBUTORS
  2. 202 0
      jars/xchart-3.8.1/LICENSE
  3. 14 0
      jars/xchart-3.8.1/NOTICE
  4. 595 0
      jars/xchart-3.8.1/README.md
  5. BIN
      jars/xchart-3.8.1/xchart-3.8.1-custom.jar
  6. 0 1
      src/TypeAdapter/AbstractCpsObjectAdapter.java
  7. 2 2
      src/addOns/Randomizer.java
  8. 1 1
      src/addOns/Utility/EmailNotification.java
  9. 1 1
      src/addOns/Utility/HolonElementSketch.java
  10. 1 1
      src/algorithm/binary/AcoAlgorithm.java
  11. 1 1
      src/algorithm/objectiveFunction/TopologieObjectiveFunction.java
  12. 1 1
      src/algorithm/topologie/AcoAlgorithm.java
  13. 1 1
      src/algorithm/topologie/GaAlgorithm.java
  14. 1 1
      src/algorithm/topologie/PsoAlgorithm.java
  15. 2 2
      src/api/AlgorithmFrameworkFlex.java
  16. 2 2
      src/classes/HolonElement.java
  17. 49 0
      src/preferences/ColorPreference.java
  18. 1 1
      src/ui/controller/CategoryController.java
  19. 19 7
      src/ui/controller/Control.java
  20. 2 0
      src/ui/controller/LoadController.java
  21. 15 3
      src/ui/controller/ObjectController.java
  22. 120 44
      src/ui/model/DecoratedGroupNode.java
  23. 0 19
      src/ui/model/Model.java
  24. 16 8
      src/ui/model/VisualRepresentationalState.java
  25. 1 1
      src/ui/view/AboutUsPopUp.java
  26. 0 11
      src/ui/view/AbstractCanvas.java
  27. 1 1
      src/ui/view/AddElementPopUp.java
  28. 1 1
      src/ui/view/AddObjectPopUp.java
  29. 1 1
      src/ui/view/AddOnWindow.java
  30. 1 1
      src/ui/view/BackgroundPopUp.java
  31. 1 1
      src/ui/view/CanvasResizePopUp.java
  32. 1 1
      src/ui/view/Console.java
  33. 1 1
      src/ui/view/CreateTemplatePopUp.java
  34. 751 751
      src/ui/view/FlexWindow.java
  35. 18 161
      src/ui/view/GUI.java
  36. 6 6
      src/ui/view/GroupNodeCanvas.java
  37. 427 0
      src/ui/view/HolonInformationPanel.java
  38. 16 16
      src/ui/view/MyCanvas.java
  39. 1 1
      src/ui/view/TimePanel.java
  40. 1 0
      src/ui/view/outliner/Outliner.java
  41. 4 1
      src/util/Action.java
  42. 4 1
      src/util/Event.java
  43. 1 1
      src/util/FloatLog.java
  44. 127 127
      src/util/ImageImport.java
  45. 1 1
      src/util/Random.java
  46. 1 1
      src/util/StringFormat.java
  47. 2 2
      tests/tests/PraktikumHolonsTestObjectController.java

+ 74 - 0
jars/xchart-3.8.1/CONTRIBUTORS

@@ -0,0 +1,74 @@
+XChart is developed by Knowm Inc. members and the open-source community.
+
+We thank all of our contributors: https://github.com/timmolter/xchart/graphs/contributors 
+
+For the detailed history of contributions of a given file, try
+
+    git blame file
+
+To see line-by-line credits and to see the change log even across renames and rewrites, try
+
+    git log --follow file
+
+Copyright is held by the original contributor according to the versioning history; see NOTICE.
+
+The following list of authors was automatically generated from the XChart project's git repo with the command:
+
+    git log --format='%aN' | sort -u
+
+Adam Walsh
+Alex Kofke
+Alex Nugent
+AlexanderRadaev
+Anthony Quiros
+Arthur Peters
+Bryan Cardillo
+Bryn Jeffries
+Carlos Lopez-Camey
+Chiamh
+Christoffer SOOP
+Colm Costelloe
+Damian Szczypior
+Ekkart Kleinod
+Emil Sauer Lynge
+Hakan
+Hakan Işıktekin
+Hongjia Cao
+Hua Shao
+Hwaipy Li
+Jean Niklas L'orange
+Jonathan Leitschuh
+Juha-Matti Tilli
+Marc Jakobi
+Marshall Pierce
+Martin Crawford
+Matan Rubin
+Michael Stummvoll
+Mike Jensen
+Mr14huashao
+Mykola Makhin
+Nathan Klick
+Nicolas Roduit
+Niklas Polke
+Ross Jourdain
+Roughy
+Sylvain Furt
+Thomas Diesler
+Thomas Neidhart
+Tim Molter
+Tomas Svensson
+Tornai András, PMK-ACS-SWA
+alessiosavi
+alexmaycon
+dependabot-preview[bot]
+dependabot[bot]
+gitkonst
+hakantkn
+heavySea
+kalan
+kibertoad
+rebaomi
+ruX[Ruslan Zaharov]
+timmolter
+yuan
+

+ 202 - 0
jars/xchart-3.8.1/LICENSE

@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!) The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 14 - 0
jars/xchart-3.8.1/NOTICE

@@ -0,0 +1,14 @@
+Copyright 2015-2018 Knowm Inc. (http://knowm.org) and contributors.
+Copyright 2011-2015 Xeiam LLC (http://xeiam.com) and contributors.
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.

+ 595 - 0
jars/xchart-3.8.1/README.md

@@ -0,0 +1,595 @@
+## [![XChart](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_64_64.png)](http://knowm.org/open-source/xchart) XChart
+
+XChart is a light weight Java library for plotting data.
+
+## Description
+
+XChart is a light-weight and convenient library for plotting data designed to go from data to chart in the least amount of time possible and to take the guess-work out of customizing the chart style.
+
+## Simplest Example
+
+Create a `XYChart` instance via `QuickChart`, add a series of data to it, and either display it or save it as a bitmap.  
+
+```java
+
+double[] xData = new double[] { 0.0, 1.0, 2.0 };
+double[] yData = new double[] { 2.0, 1.0, 0.0 };
+
+// Create Chart
+XYChart chart = QuickChart.getChart("Sample Chart", "X", "Y", "y(x)", xData, yData);
+
+// Show it
+new SwingWrapper(chart).displayChart();
+
+// Save it
+BitmapEncoder.saveBitmap(chart, "./Sample_Chart", BitmapFormat.PNG);
+
+// or save it in high-res
+BitmapEncoder.saveBitmapWithDPI(chart, "./Sample_Chart_300_DPI", BitmapFormat.PNG, 300);
+```
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Simplest.png)
+
+## Intermediate Example
+
+Create a `XYChart` via a `XYChartBuilder`, style chart, add a series to it, style series, and display chart.
+
+```java
+
+// Create Chart
+XYChart chart = new XYChartBuilder().width(600).height(500).title("Gaussian Blobs").xAxisTitle("X").yAxisTitle("Y").build();
+
+// Customize Chart
+chart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Scatter);
+chart.getStyler().setChartTitleVisible(false);
+chart.getStyler().setLegendPosition(LegendPosition.InsideSW);
+chart.getStyler().setMarkerSize(16);
+
+// Series
+chart.addSeries("Gaussian Blob 1", getGaussian(1000, 1, 10), getGaussian(1000, 1, 10));
+XYSeries series = chart.addSeries("Gaussian Blob 2", getGaussian(1000, 1, 10), getGaussian(1000, 0, 5));
+series.setMarker(SeriesMarkers.DIAMOND);
+
+new SwingWrapper(chart).displayChart();
+```
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Intermediate.png)
+
+## Advanced Example
+
+Create a `XYChart` via a `XYChartBuilder`, style chart, add a series to it, add chart to `XChartPanel`, embed in Java Swing App, and display GUI.
+
+```java
+
+// Create Chart
+final XYChart chart = new XYChartBuilder().width(600).height(400).title("Area Chart").xAxisTitle("X").yAxisTitle("Y").build();
+
+// Customize Chart
+chart.getStyler().setLegendPosition(LegendPosition.InsideNE);
+chart.getStyler().setDefaultSeriesRenderStyle(XYSeriesRenderStyle.Area);
+
+// Series
+chart.addSeries("a", new double[] { 0, 3, 5, 7, 9 }, new double[] { -3, 5, 9, 6, 5 });
+chart.addSeries("b", new double[] { 0, 2, 4, 6, 9 }, new double[] { -1, 6, 4, 0, 4 });
+chart.addSeries("c", new double[] { 0, 1, 3, 8, 9 }, new double[] { -2, -1, 1, 0, 1 });
+
+// Schedule a job for the event-dispatching thread:
+// creating and showing this application's GUI.
+javax.swing.SwingUtilities.invokeLater(new Runnable() {
+
+  @Override
+  public void run() {
+
+    // Create and set up the window.
+    JFrame frame = new JFrame("Advanced Example");
+    frame.setLayout(new BorderLayout());
+    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+
+    // chart
+    JPanel chartPanel = new XChartPanel<XYChart>(chart);
+    frame.add(chartPanel, BorderLayout.CENTER);
+
+    // label
+    JLabel label = new JLabel("Blah blah blah.", SwingConstants.CENTER);
+    frame.add(label, BorderLayout.SOUTH);
+
+    // Display the window.
+    frame.pack();
+    frame.setVisible(true);
+  }
+});
+
+```
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Advanced.png)
+
+To make it real-time, simply call `updateXYSeries` on the `XYChart` instance to update the series data, followed by `revalidate()` and `repaint()` on the `XChartPanel` instance to repaint.
+
+## Features
+
+* [x] No *required* additional dependencies
+* [x] Multiple Y-Axis charts
+* [x] Line charts
+* [x] Step charts
+* [x] Scatter charts
+* [x] Area charts
+* [x] Step Area charts
+* [x] Bar charts
+* [x] Histogram charts
+* [x] Pie charts
+* [x] Donut charts
+* [x] Bubble charts
+* [x] Stick charts
+* [x] Dial charts
+* [x] Radar charts
+* [x] OHLC charts
+* [x] Box charts
+* [x] Heat maps
+* [x] Error bars
+* [x] Logarithmic axes
+* [x] Number, Date, Bubble and Category X-Axis
+* [x] Multiple series
+* [x] Tool tips
+* [x] Extensive customization
+* [x] Themes - XChart, GGPlot2, Matlab
+* [x] Right-click, Save-As...
+* [x] User-defined axes range
+* [x] Definable legend placement
+* [x] CSV import and export
+* [x] High resolution chart export
+* [x] Export as PNG, JPG, BMP, GIF with custom DPI setting
+* [x] Export SVG, EPS using optional `de.erichseifert.vectorgraphics2d` library
+* [x] Export PDF using optional `pdfbox-graphics2d` library
+* [x] Real-time charts
+* [x] Java 8 and up
+
+## Chart Types
+
+Currently, there are 5 major chart types. Each type has its corresponding `ChartBuilder`, `Styler` and `Series`.
+
+| Chart Type | Builder | Styler | Series | Allowed Data Types | Default Series Render Style |
+|---|---|---|---|---|---|
+| XYChart | XYChartBuilder | XYStyler | XYSeries | Number, Date | Line |
+| CategoryChart | CategoryChartBuilder | CategoryStyler | CategorySeries | Number, Date, String | Bar |
+| PieChart | PieChartBuilder | PieStyler | PieSeries | String | Pie |
+| BubbleChart | BubbleChartBuilder | BubbleStyler | BubbleSeries | Number, Date | Round |
+| DialChart | DialChartBuilder | DialStyler | DialSeries | double  | Round |
+| RadarChart | RadarChartBuilder | RadarStyler | RadarSeries | double[] | Round |
+| OHLCChart | OHLCChartBuilder | OHLCStyler | OHLCSeries | OHLC with Date | Candle |
+| BoxChart | BoxChartBuilder | BoxStyler | BoxSeries | Number, Date, String | Box |
+| HeatMapChart | HeatMapChartBuilder | HeatMapStyler | HeatMapSeries | Number, Date, String | -- |
+
+The different Stylers contain chart styling methods specific to the corresponding chart type as well as common styling methods common across all chart types.
+
+### XYChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_XYChart.png)
+
+`XYChart` charts take Date or Number data types for the X-Axis and Number data types for the Y-Axis. For both axes, the tick marks are auto generated to span the range and domain of the data in evenly-spaced intervals. 
+
+Series render styles include: `Line`, `Scatter`, `Area`, `Step` and `StepArea`.
+
+### CategoryChart 
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_CategoryChart.png)
+
+`CategoryChart` charts take Date, Number or String data types for the X-Axis and Number data types for the Y-Axis. For the X-Axis, each category is given its own tick mark.  
+
+Series render styles include: `Bar`, `Line`, `Scatter`, `Area` and `Stick`.
+
+### PieChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_PieChart.png)
+
+`PieChart` charts take String data types for the pie slice name and Number data types for the pie slice value.  
+
+Series render styles include: `Pie` and `Donut`.
+
+### BubbleChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Bubble_Chart.png)
+
+`BubbleChart` charts take Date or Number data types for the X-Axis and Number data types for the Y-Axis and bubble sizes. 
+
+Series render styles include: `Round` and in the near future `Square`.
+
+### DialChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Dial_Chart.png)
+
+`DialChart` charts take a `double` to set the position of the dial pointer.
+
+### RadarChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Radar_Chart.png)
+
+`RadarChart` charts take a `double[]` of values between `0` and `1` to set the position of radar node.
+
+Series render styles include: `Polygon` and  `Circle`.
+
+### OHLCChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_OHLC.png)
+
+`OHLCChart` charts take Date data types for the X-Axis and 4 Number data types for the Y-Axis. For both axes, the tick marks are auto generated to span the range and domain of the data in evenly-spaced intervals.
+
+Series render styles include: `Candle`, `HiLo`.
+
+### BoxChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_BoxChart.png)
+
+`BoxChart` charts take String data (seriesNames) types for the X-Axis and Number data types for the Y-Axis. Each box chart is calculated from the corresponding series yData.
+Create a BoxChart via a BoxChartBuilder, style chart, add a series to it.
+```java
+// Create Chart
+BoxChart chart =
+	new BoxChartBuilder().title("box plot demo").build();
+
+// Choose a calculation method
+chart.getStyler().setBoxplotCalCulationMethod(BoxplotCalCulationMethod.N_LESS_1_PLUS_1);
+chart.getStyler().setToolTipsEnabled(true);
+
+// Series
+chart.addSeries("boxOne", Arrays.asList(1,2,3,4));
+new SwingWrapper<BoxChart>(chart).displayChart();
+```
+Four calculation methods for boxplots:  
+- "N_PLUS_1": determine the position of the quartile, where Qi is = i (n + 1) / 4, where i = 1, 2, and 3. n represents the number of items contained in the sequence.
+Calculate the corresponding quartile based on location.
+- "N_LESS_1": Determine the position of the quartile, where Qi is = i (n-1) / 4, where i = 1, 2, and 3. n represents the number of items contained in the sequence.
+Calculate the corresponding quartile based on location.
+- "NP": Determine the position of the quartile, where Qi is np = (i * n) / 4, where i = 1, 2, and 3. n represents the number of items contained in the sequence.
+If np is not an integer, Qi = X [np + 1];
+If np is an integer, Qi = (X [np] + X [np + 1]) / 2.
+- "N_LESS_1_PLUS_1": Determine the position of the quartile, where Qi is = i (n-1) / 4 + 1, where i = 1, 2, 3. n represents the number of items contained in the sequence.
+Calculate the corresponding quartile based on location.
+
+Interquartile range, IQR = Q3-Q1.
+
+Upper whisker = Q3 + 1.5 * IQR = Q3 + 1.5 * (Q3 - Q1), if Upper whisker is greater than the maximum value of yData, Upper whisker = maximum value of yData.
+
+Lower whisker = Q1 - 1.5 * IQR = Q1 - 1.5 * (Q3 -Q1), if the lower whisker is less than the minimum value of yData, the lower whisker = the minimum value of yData.
+
+E.g:
+
+An example of a set of sequence numbers: 12, 15, 17, 19, 20, 23, 25, 28, 30, 33, 34, 35, 36, 37
+- "N_PLUS_1":
+Q1's position = (14 + 1) /4=3.75,
+Q1 = 0.25 × third term + 0.75 × fourth term = 0.25 × 17 + 0.75 × 19 = 18.5;
+- "N_LESS_1":
+Q1's location = (14-1) /4=3.25,
+Q1 = 0.75 × third term + 0.25 × fourth term = 0.75 × 17 + 0.25 × 19 = 17.5;
+- "NP":
+Q1's position = 14 * 0.25 = 3.5,
+Q1 = 19;
+- "N_LESS_1_PLUS_1":
+Q1's location = (14-1) / 4 + 1 = 4.25
+Q1 = 0.75 × the fourth term + 0.25 × the fifth term = 0.75 × 19 + 0.25 × 20 = 19.25.
+
+### HeatMapChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_HeatMap.png)
+
+`HeatMapChart` take Date, Number or String data types for the X-Axis, Y-Axis. 
+
+## Real-time Java Charts using XChart
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_SimpleRealtime.gif)
+
+Creating real-time charts is as simple as calling `updateXYSeries` for one or more series objects through the `XYChart` instance and triggering a redraw of the `JPanel` containing the chart. This works for all chart types including `XYChart`, `CategoryChart`, `BubbleChart` and `PieChart`, for which example source code can be found [here](https://github.com/knowm/XChart/tree/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/realtime). Examples demonstrate using the `SwingWrapper` with `repaintChart()` method as well as `XChartPanel` with `revalidate()` and `repaint()`. 
+
+The following sample code used to generate the above real-time chart can be found [here](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/standalone/readme/SimpleRealTime.java).
+
+```java
+public class SimpleRealTime {
+
+  public static void main(String[] args) throws Exception {
+
+    double phase = 0;
+    double[][] initdata = getSineData(phase);
+
+    // Create Chart
+    final XYChart chart = QuickChart.getChart("Simple XChart Real-time Demo", "Radians", "Sine", "sine", initdata[0], initdata[1]);
+
+    // Show it
+    final SwingWrapper<XYChart> sw = new SwingWrapper<XYChart>(chart);
+    sw.displayChart();
+
+    while (true) {
+
+      phase += 2 * Math.PI * 2 / 20.0;
+
+      Thread.sleep(100);
+
+      final double[][] data = getSineData(phase);
+
+      javax.swing.SwingUtilities.invokeLater(new Runnable() {
+
+        @Override
+        public void run() {
+
+          chart.updateXYSeries("sine", data[0], data[1], null);
+          sw.repaintChart();
+        }
+      });
+    }
+
+  }
+
+  private static double[][] getSineData(double phase) {
+
+    double[] xData = new double[100];
+    double[] yData = new double[100];
+    for (int i = 0; i < xData.length; i++) {
+      double radians = phase + (2 * Math.PI / xData.length * i);
+      xData[i] = radians;
+      yData[i] = Math.sin(radians);
+    }
+    return new double[][] { xData, yData };
+  }
+}
+```
+
+## Chart Customization
+
+All the styling options can be found in one of two possible places: 1) the Chart's `Styler` or 2) the series' `set` methods. With this chart customization design, all customization options can be quickly "discovered" using an IDE's built in "Content Assist". With centralized styling like this, there is no need to hunt around the entire charting API to find that one customization you're looking for - it's all right in one spot!
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Chart_Customization.png)
+ 
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Series_Customization.png)
+ 
+
+### Customizing Axis Tick Labels
+
+XChart automatically creates axis tick labels for chart types with axes. 
+
+Default axis tick placement can be altered with `chart.getStyler().setXAxisTickMarkSpacingHint(spacingHint);`. 
+
+Default axis label labels can be altered with one of:
+
+```java
+chart.getStyler().setDatePattern(datePattern)
+chart.getStyler().setXAxisDecimalPattern(pattern);
+chart.getStyler().setYAxisDecimalPattern(pattern);
+```
+
+
+You can also create custom axis tick labels with a callback function. In the following example taken from [DateChart09](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/date/DateChart09.java), the X-Axis tick labels are generated 
+via a custom lambda function which takes the numerical (double) tick label values and converts them to a `String`.
+
+
+```java
+// set custom X-Axis tick labels
+LocalDateTime startTime = LocalDateTime.of(2001, Month.JANUARY, 1, 0, 0, 0);
+DateTimeFormatter xTickFormatter = DateTimeFormatter.ofPattern("LLL");
+chart.getStyler().setxAxisTickLabelsFormattingFunction(x -> startTime.plusDays(x.longValue()).format(xTickFormatter));
+```
+
+In the following example taken from [DateChart06](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/date/DateChart06.java), the Y-Axis tick labels are converted 
+to the englich word reprentation of the numbers.
+
+```java
+chart.getStyler().setyAxisTickLabelsFormattingFunction(x -> NumberWordConverter.convert(x.intValue()));
+```
+
+### Multiple Axes
+
+XChart has multiple y axes feature. Y offset is calculated according to the Y-Axis the series configured. Max `y` value in this axis is calculated 
+according to the series on this axis only. 
+To set the y group: 
+
+```java
+series.setYAxisGroup(axisGroup);   
+```
+
+To manually change max/min of axis group: 
+
+```java
+((AxesChartStyler) chart.getStyler()).setYAxisMax(axisGroup, 200.0);
+```
+
+Axis can be drawn on the left (default) or on the right of the chart: 
+
+```java
+chart.getStyler().setYAxisGroupPosition(axisGroup, Styler.YAxisPosition.Right);
+```
+
+To set the Y axes titles:
+
+```java
+chart.setYAxisGroupTitle(0, "A");
+chart.setYAxisGroupTitle(1, "B");
+```
+
+### Zooming In
+
+For the `XYChart` chart type, zooming in is possible on an `XChartPanel` via select-dragging over a range on the X-Axis. Reverting out of the zoom can be accomplished by double-clicking on the chart or by clicking on the "reset" button, which can be posotioned as desired. 
+
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Zoom.png)
+
+
+The following example zoom style options show which are available:
+
+```java
+chart.getStyler().setZoomEnabled(true);
+chart.getStyler().setZoomResetButtomPosition(Styler.CardinalPosition.InsideS);
+chart.getStyler().setZoomResetByDoubleClick(false);
+chart.getStyler().setZoomResetByButton(true);
+chart.getStyler().setZoomSelectionColor(new Color(0,0 , 192, 128));
+```
+
+A working example can be found at [DateChart01](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/date/DateChart01.java).
+
+### Chart Annotations
+
+For all chart types, one or more chart annotations can be super-imposed on top of the chart. The following types of annotatins are available:
+
+- AnnotationLine
+- AnnotationImage
+- AnnotationText
+- AnnotationTextPanel
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_AnnotationLineImageText.png)
+
+A working example can be found at [LineChart10](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/line/LineChart10.java).
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_AnnotationTextPanel.png)
+
+A working example can be found at [ScatterChart04](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/scatter/ScatterChart04.java).
+
+### Tool Tips
+
+For all chart types, tool tips can be activated on an `XChartPanel` via 
+
+```java
+chart.getStyler().setToolTipsEnabled(true);
+```
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Tooltips.png)
+
+
+The following example tooltip options show which are available:
+
+```java
+chart.getStyler().setToolTipsEnabled(true);
+chart.getStyler(). setToolTipsAlwaysVisible(true);
+chart.getStyler().setToolTipFont( new Font("Verdana", Font.BOLD, 12));
+chart.getStyler().setToolTipHighlightColor(Color.CYAN);
+chart.getStyler().setToolTipBorderColor(Color.BLACK);
+chart.getStyler(). setToolTipBackgroundColor(Color.LIGHT_GRAY);
+chart.getStyler().setToolTipType(Styler.ToolTipType.xAndYLabels);
+```
+
+A working example can be found at [LineChart05](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/line/LineChart05.java).
+
+### Cursor
+
+For the `XYChart` chart type, it is possible to add an interactive cursor on an `XChartPanel` via
+
+```java
+chart.getStyler().setCursorEnabled(true);
+```
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Cursor.png)
+
+The following example cursor options show which are available:
+
+```java
+chart.getStyler().setCursorEnabled(true);
+chart.getStyler().setCursorColor(Color.GREEN);
+chart.getStyler().setCursorLineWidth(30f);
+chart.getStyler().setCursorFont(new Font("Verdana", Font.BOLD, 12));
+chart.getStyler().setCursorFontColor(Color.ORANGE);
+chart.getStyler().setCursorBackgroundColor(Color.BLUE);
+chart.getStyler().setCustomCursorXDataFormattingFunction(x -> "hello xvalue: " + x);
+chart.getStyler().setCustomCursorYDataFormattingFunction(y -> "hello yvalue divided by 2: " + y / 2);
+```
+
+A working example can be found at [LineChart09](https://github.com/knowm/XChart/blob/develop/xchart-demo/src/main/java/org/knowm/xchart/demo/charts/line/LineChart09.java).
+
+## Chart Themes
+
+XChart ships with three different themes: Default `XChart`, `GGPlot2` and `Matlab`. Using a different theme is as simple as setting the Chart's theme with the `theme` method of the `ChartBuilder`.
+
+    XYChart chart = new XYChartBuilder().width(800).height(600).theme(ChartTheme.Matlab).build();
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Themes.png)
+
+## What's Next?
+
+Now go ahead and [study some more examples](http://knowm.org/open-source/xchart/xchart-example-code/), [download the thing](http://knowm.org/open-source/xchart/xchart-change-log) and [provide feedback](https://github.com/knowm/XChart/issues).
+ 
+## Getting Started
+
+### Non-Maven
+
+Download Jar: http://knowm.org/open-source/xchart/xchart-change-log
+
+### Maven
+
+The XChart release artifacts are hosted on Maven Central.
+
+Add the XChart library as a dependency to your pom.xml file:
+
+```xml
+    <dependency>
+        <groupId>org.knowm.xchart</groupId>
+        <artifactId>xchart</artifactId>
+        <version>3.8.0</version>
+    </dependency>
+```
+
+For snapshots, add the following to your pom.xml file:
+
+```xml
+    <repository>
+      <id>sonatype-oss-snapshot</id>
+      <snapshots/>
+      <url>https://oss.sonatype.org/content/repositories/snapshots</url>
+    </repository>
+
+    <dependency>
+      <groupId>org.knowm.xchart</groupId>
+      <artifactId>xchart</artifactId>
+      <version>3.8.1-SNAPSHOT</version>
+    </dependency>
+```
+
+Snapshots can be manually downloaded from Sonatype: [https://oss.sonatype.org/content/groups/public/org/knowm/xchart/xchart/](https://oss.sonatype.org/content/groups/public/org/knowm/xchart/xchart/)
+
+### SBT
+
+To use XChart with the Scala Build Tool (SBT) add the following to your build.sbt
+
+```scala
+libraryDependencies += "org.knowm.xchart" % "xchart" % "3.8.0" exclude("de.erichseifert.vectorgraphics2d", "VectorGraphics2D") withSources()
+```
+
+## Building with Maven
+
+#### general
+
+    mvn clean package  
+    mvn javadoc:aggregate  
+
+#### Formatting
+
+    mvn com.coveo:fmt-maven-plugin:format
+    
+Formats your code using [google-java-format](https://github.com/google/google-java-format) which follows [Google's code styleguide](https://google.github.io/styleguide/javaguide.html).
+
+If you want your IDE to stick to the same format, check out the available configuration plugins:
+
+#### Eclipse
+
+Download [`google-java-format-eclipse-plugin_*.jar`](https://github.com/google/google-java-format/releases) and place in `/Applications/Eclipse Java.app/Contents/Eclipse/dropins`. Restart Eclipse. Select the plugin in `Preferences > Java > Code Style > Formatter > Formatter Implementation`. 
+
+#### IntelliJ
+
+In the plugins section in IntelliJ search for `google-java-format` and install the plugin. Restart IntelliJ.
+
+## Running Demo
+
+- Linux: execute command `java -cp xchart-demo-3.8.0.jar:xchart-3.8.0.jar org.knowm.xchart.demo.XChartDemo`.
+
+- Windows: In the cmd command window, execute the command `java -cp xchart-demo-3.8.0.jar;xchart-3.8.0.jar org.knowm.xchart.demo.XChartDemo`; In the PowerShell command window, execute the command `java -cp "xchart-demo-3.8.0.jar;xchart-3.8.0.jar" org.knowm.xchart.demo.XChartDemo`.
+
+E.g:
+```sh
+cd /path/to/xchart-demo/jar/
+java -cp xchart-demo-3.8.0.jar:xchart-3.8.0.jar org.knowm.xchart.demo.XChartDemo
+```
+
+![](https://raw.githubusercontent.com/knowm/XChart/develop/etc/XChart_Demo.png)
+
+## Bugs
+
+Please report any bugs or submit feature requests to [XChart's Github issue tracker](https://github.com/knowm/XChart/issues).  
+
+## Continuous Integration
+
+[![Build Status](https://travis-ci.org/knowm/XChart.png?branch=develop)](https://travis-ci.org/timmolter/XChart.png)  
+[Build History](https://travis-ci.org/knowm/XChart/builds)  
+

BIN
jars/xchart-3.8.1/xchart-3.8.1-custom.jar


+ 0 - 1
src/TypeAdapter/AbstractCpsObjectAdapter.java

@@ -41,7 +41,6 @@ public class AbstractCpsObjectAdapter
 			System.err.println("Unknown Class with Type:" + type);
 			return null;
 		}
-
 	}
 
 }

+ 2 - 2
src/addOns/Randomizer.java

@@ -45,8 +45,8 @@ import classes.GroupNode;
 import classes.HolonElement;
 import classes.HolonObject;
 import ui.controller.Control;
-import utility.Random;
-import utility.ImageImport;
+import util.ImageImport;
+import util.Random;
 
 public class Randomizer implements AddOn {
 	private Control  control;

+ 1 - 1
src/addOns/Utility/EmailNotification.java

@@ -16,7 +16,7 @@ import javax.swing.JTextField;
 
 import org.apache.commons.mail.*;
 
-import utility.ImageImport;
+import util.ImageImport;
 
 
 public class EmailNotification {

+ 1 - 1
src/addOns/Utility/HolonElementSketch.java

@@ -4,8 +4,8 @@ import classes.Constrain;
 import classes.Flexibility;
 import classes.HolonElement;
 import classes.HolonElement.Priority;
+import util.Random;
 import classes.HolonObject;
-import utility.Random;
 
 public class HolonElementSketch {
 	//HolonElement

+ 1 - 1
src/algorithm/binary/AcoAlgorithm.java

@@ -6,7 +6,7 @@ import java.util.ListIterator;
 
 import javax.swing.JFrame;
 import api.AlgorithmFrameworkFlex;
-import utility.StringFormat;
+import util.StringFormat;
 
 public class AcoAlgorithm extends AlgorithmFrameworkFlex{
 	

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

@@ -4,7 +4,7 @@ package algorithm.objectiveFunction;
 import ui.model.DecoratedHolonObject;
 import ui.model.DecoratedNetwork;
 import ui.model.DecoratedState;
-import utility.FloatLog;
+import util.FloatLog;
 
 import java.util.Locale;
 import algorithm.objectiveFunction.GraphMetrics.Graph;

+ 1 - 1
src/algorithm/topologie/AcoAlgorithm.java

@@ -8,7 +8,7 @@ import java.util.ListIterator;
 import algorithm.objectiveFunction.TopologieObjectiveFunction;
 import api.TopologieAlgorithmFramework;
 import ui.model.DecoratedState;
-import utility.Random;
+import util.Random;
 
 public class AcoAlgorithm extends TopologieAlgorithmFramework {
 

+ 1 - 1
src/algorithm/topologie/GaAlgorithm.java

@@ -9,7 +9,7 @@ import java.util.TreeSet;
 import algorithm.objectiveFunction.TopologieObjectiveFunction;
 import api.TopologieAlgorithmFramework;
 import ui.model.DecoratedState;
-import utility.Random;
+import util.Random;
 
 public class GaAlgorithm extends TopologieAlgorithmFramework {
 

+ 1 - 1
src/algorithm/topologie/PsoAlgorithm.java

@@ -9,7 +9,7 @@ import java.util.stream.Collectors;
 import algorithm.objectiveFunction.TopologieObjectiveFunction;
 import api.TopologieAlgorithmFramework;
 import ui.model.DecoratedState;
-import utility.Random;
+import util.Random;
 
 public class PsoAlgorithm extends TopologieAlgorithmFramework {
 

+ 2 - 2
src/api/AlgorithmFrameworkFlex.java

@@ -61,8 +61,8 @@ import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedSwitch.SwitchState;
 import ui.model.DecoratedNetwork;
 import ui.view.Console;
-import utility.ImageImport;
-import utility.StringFormat;
+import util.ImageImport;
+import util.StringFormat;
 
 public abstract class AlgorithmFrameworkFlex implements AddOn{
 	//Algo

+ 2 - 2
src/classes/HolonElement.java

@@ -51,9 +51,9 @@ public class HolonElement implements LocalMode, GraphEditable{
     public Holon holon = null;
     
     @Expose
-    private Priority priority;
+    private Priority priority = Priority.Low;
 
-	public enum Priority {
+	public static enum Priority {
     	Essential, High, Medium , Low
     }
 

+ 49 - 0
src/preferences/ColorPreference.java

@@ -0,0 +1,49 @@
+package preferences;
+
+import java.awt.Color;
+
+/**
+ * A Class to save all colors in Holeg.
+ * @author Tom
+ *
+ */
+public class ColorPreference {
+	
+	
+	public static class Element{
+		public static class Priority{
+			public static final Color Essential = new Color(201, 44, 74);
+			public static final Color High = new Color(255, 92, 26);
+			public static final Color Medium = new Color(255, 216, 57);
+			public static final Color Low = new Color(255, 255, 175);
+			public static final Color NoData = new Color(21, 8, 17);
+		}
+		public static final Color Active = new Color(255, 203, 35);
+		public static final Color Inactive = new Color(128, 154, 163);
+	}
+	public static class HolonObject{
+		public static final Color Producer = Color.lightGray;
+		public static final Color OverSupplied = new Color(166, 78, 229);
+		public static final Color Supplied = new Color(13, 175, 28);
+		public static final Color PartiallySupplied = Color.yellow;
+		public static final Color NotSupplied = new Color(230, 120, 100);
+		public static final Color NoEnergy = Color.white;
+	}
+	public static class Energy{
+		public static final Color Production = new Color(61, 133, 243);
+		public static final Color Consumption = new Color(255, 67, 60);
+	}
+	public static class Flexibility{
+		public static final Color InUse = new Color(182, 238, 166);
+		public static final Color OnCooldown = new Color(239, 215, 128);
+		public static final Color Offered = new Color(75, 170, 72);
+		public static final Color NotOffered = new Color(237, 106, 90);
+		public static final Color Unavailable = new Color(193, 193, 193);
+	}
+	
+	public static class Panel {
+		public static final Color Transparent = new Color(0,0,0,0);
+		public static final Color Background = new Color(250, 250, 250);
+		public static final Color Title = new Color(54, 73, 78);
+	}
+}

+ 1 - 1
src/ui/controller/CategoryController.java

@@ -9,7 +9,7 @@ import classes.HolonObject;
 import classes.HolonSwitch;
 import classes.Pair;
 import ui.model.Model;
-import utility.Event;
+import util.Event;
 
 /**
  * Controller for the Categories.

+ 19 - 7
src/ui/controller/Control.java

@@ -23,7 +23,7 @@ import ui.model.Model;
 import ui.model.Model.FairnessModel;
 import ui.view.CreateTemplatePopUp;
 import ui.view.GUI;
-import utility.Event;
+import util.Event;
 
 /**
  * The Class represents the controller in the model, controller view Pattern.
@@ -51,6 +51,11 @@ public class Control {
     private String otherDir = "";
     private String dimensionsFileName = "dimensions";
     private int rand;
+    
+    
+    
+    
+    public Event OnSelectionUpdate = new Event();
 
     
     public Event OnCategoryChanged = new Event();
@@ -257,21 +262,28 @@ public class Control {
     }
 
     /**
-     * deletes a selectedObject.
-     *
+     * remove a selectedObject.
+     * 
      * @param obj Cpsobject
      */
-    public void deleteSelectedObject(AbstractCanvasObject obj) {
-        objectController.deleteSelectedObject(obj);
+    public void removeSelectedObjectFromSelection(AbstractCanvasObject obj) {
+        objectController.removeSelectedObjectFromSelection(obj);
+        this.OnSelectionUpdate.broadcast();
     }
-
+    
+    public void clearSelection() {
+    	objectController.clearSelection();
+    	this.OnSelectionUpdate.broadcast();
+    }
+    
     /**
      * add an Object to selectedObject.
      *
      * @param obj AbstractCpsobject
      */
     public void addSelectedObject(AbstractCanvasObject obj) {
-        objectController.addSelectedObject(obj);
+        objectController.addSelectedObjectToSelection(obj);
+        this.OnSelectionUpdate.broadcast();
     }
 
 	/* Operations for Canvas */

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

@@ -1,6 +1,7 @@
 package ui.controller;
 
 import classes.*;
+import classes.HolonElement.Priority;
 
 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
@@ -521,6 +522,7 @@ public class LoadController {
     void initElements(HolonElement ele) {
         ele.flexList = new ArrayList<Flexibility>();
         ele.setGraphPoints(new LinkedList<>());
+        if(ele.getPriority() == null) ele.setPriority(Priority.Low);
         ele.reset();
     }
 

+ 15 - 3
src/ui/controller/ObjectController.java

@@ -120,20 +120,32 @@ public class ObjectController {
     }
 
     /**
-     * deletes a selectedObject.
+     * removes a selectedObject.
      *
      * @param obj Cpsobject
      */
-    public void deleteSelectedObject(AbstractCanvasObject obj) {
+    public void removeSelectedObjectFromSelection(AbstractCanvasObject obj) {
         model.getSelectedCpsObjects().remove(obj);
     }
 
+    
+    
+    /**
+     * removes a selectedObject.
+     *
+     * @param obj Cpsobject
+     */
+    public void clearSelection() {
+        model.getSelectedCpsObjects().clear();
+    }
+    
+    
     /**
      * add an Object to selectedObject.
      *
      * @param obj AbstractCpsobject
      */
-    public void addSelectedObject(AbstractCanvasObject obj) {
+    public void addSelectedObjectToSelection(AbstractCanvasObject obj) {
         model.getSelectedCpsObjects().add(obj);
     }
 

+ 120 - 44
src/ui/model/DecoratedGroupNode.java

@@ -1,12 +1,18 @@
 package ui.model;
 
 import java.util.ArrayList;
+import java.util.stream.Stream;
 
 import classes.Node;
+import jdk.jfr.Unsigned;
 import classes.GroupNode;
+import classes.HolonElement;
+import classes.Flexibility;
 import ui.model.DecoratedHolonObject.HolonObjectState;
+
 /**
  * For the @VisualRepresentationalState only.
+ * 
  * @author Tom
  *
  */
@@ -17,19 +23,18 @@ public class DecoratedGroupNode {
 	private ArrayList<Consumer> consumerList;
 	private ArrayList<Node> nodeList;
 	/**
-	 * Cables that only exist on that group node. From a object in that group node to a object in that group Node.
-	 * Not exit the group node (a layer down).
+	 * Cables that only exist on that group node. From a object in that group node
+	 * to a object in that group Node. Not exit the group node (a layer down).
 	 */
 	private ArrayList<DecoratedCable> internCableList;
 	/**
-	 * Cables that exit this group node (a Layer Up). From a object in this group node to a object in a upper layer.
+	 * Cables that exit this group node (a Layer Up). From a object in this group
+	 * node to a object in a upper layer.
 	 */
-	private ArrayList<ExitCable> exitCableList;	
+	private ArrayList<ExitCable> exitCableList;
 	private ArrayList<DecoratedSwitch> switchList;
 	private ArrayList<DecoratedGroupNode> groupNodeList;
 
-
-
 	public DecoratedGroupNode(GroupNode model) {
 		this.model = model;
 		this.supplierList = new ArrayList<Supplier>();
@@ -41,93 +46,164 @@ public class DecoratedGroupNode {
 		this.switchList = new ArrayList<DecoratedSwitch>();
 		this.groupNodeList = new ArrayList<DecoratedGroupNode>();
 	}
+
 	public GroupNode getModel() {
 		return model;
 	}
+
 	public ArrayList<Supplier> getSupplierList() {
 		return supplierList;
 	}
+
 	public ArrayList<Passiv> getPassivList() {
 		return passivList;
 	}
+
 	public ArrayList<Consumer> getConsumerList() {
 		return consumerList;
 	}
+
 	public ArrayList<Node> getNodeList() {
 		return nodeList;
 	}
+
 	public ArrayList<DecoratedCable> getInternCableList() {
 		return internCableList;
 	}
+
 	public ArrayList<ExitCable> getExitCableList() {
 		return exitCableList;
 	}
+
 	public ArrayList<DecoratedSwitch> getSwitchList() {
 		return switchList;
 	}
+
 	public ArrayList<DecoratedGroupNode> getGroupNodeList() {
 		return groupNodeList;
 	}
-	
-	
-	//Returns the amount of holons and count himself 
+
+	// Returns the amount of holons and count himself
 	public int getAmountOfGroupNodes() {
 		return 1 + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfGroupNodes()).reduce(0, Integer::sum);
 	}
-	
-	
-	//Gather Informations:
+
+	public Stream<Flexibility> getFlexibilitiesStream() {
+
+		Stream<Flexibility> flexInChildGorupNode = this.groupNodeList.stream()
+				.flatMap(groupNode -> groupNode.getFlexibilitiesStream());
+
+		Stream<Flexibility> flexInThisGorupNode = objectStream()
+				.flatMap(object -> object.getModel().getElements().stream().flatMap(ele -> ele.flexList.stream()));
+
+		return Stream.concat(flexInChildGorupNode, flexInThisGorupNode);
+	}
+
+	public Stream<DecoratedHolonObject> objectStream() {
+		return Stream.concat(Stream.concat(this.consumerList.stream(), this.supplierList.stream()),
+				this.passivList.stream());
+	}
+
+	// Gather Informations:
 	public int getAmountOfSupplier() {
-		return supplierList.size() + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfSupplier()).reduce(0, Integer::sum);
+		return supplierList.size()
+				+ groupNodeList.stream().map(groupNode -> groupNode.getAmountOfSupplier()).reduce(0, Integer::sum);
 	}
+
 	public int getAmountOfConsumer() {
-		return consumerList.size() + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfConsumer()).reduce(0,Integer::sum);
+		return consumerList.size()
+				+ groupNodeList.stream().map(groupNode -> groupNode.getAmountOfConsumer()).reduce(0, Integer::sum);
 	}
+
 	public int getAmountOfPassiv() {
-		return passivList.size() + groupNodeList.stream().map(groupNode -> groupNode.getAmountOfPassiv()).reduce(0, Integer::sum);
+		return passivList.size()
+				+ groupNodeList.stream().map(groupNode -> groupNode.getAmountOfPassiv()).reduce(0, Integer::sum);
 	}
-	
+
 	public int getAmountOfConsumerWithState(HolonObjectState state) {
-		return ((int) consumerList.stream().map(con -> con.getState()).filter(rightState -> (rightState == state)).count()) +  groupNodeList.stream().map(groupNode -> groupNode.getAmountOfConsumerWithState(state)).reduce(0, Integer::sum);
+		return ((int) consumerList.stream().map(con -> con.getState()).filter(rightState -> (rightState == state))
+				.count())
+				+ groupNodeList.stream().map(groupNode -> groupNode.getAmountOfConsumerWithState(state)).reduce(0,
+						Integer::sum);
 	}
-	
+
 	public int getAmountOfElemntsFromHolonObjects() {
-		return passivList.stream().map(object -> object.getModel().getElements().size()).reduce(0, Integer::sum)+
-				supplierList.stream().map(object -> object.getModel().getElements().size()).reduce(0, Integer::sum)+
-				consumerList.stream().map(object -> object.getModel().getElements().size()).reduce(0, Integer::sum)+
-				groupNodeList.stream().map(groupNode -> groupNode.getAmountOfElemntsFromHolonObjects()).reduce(0, Integer::sum);
+		return objectStream().map(object -> object.getModel().getElements().size()).reduce(0, Integer::sum)
+				+ groupNodeList.stream().map(groupNode -> groupNode.getAmountOfElemntsFromHolonObjects()).reduce(0,
+						Integer::sum);
+	}
+
+	public PriorityCounts getPriorityCounts() {
+		PriorityCounts priority = new PriorityCounts();
+		objectStream().forEach(object -> object.getModel().getElements().stream().forEach(ele -> priority.Count(ele)));
+		groupNodeList.stream().forEach(groupNode -> priority.Add(groupNode.getPriorityCounts()));
+		return priority;
+	}
+
+	public class PriorityCounts {
+		@Unsigned
+		public int low, medium, high, essential;
+
+		public void Add(PriorityCounts other) {
+			low += other.low;
+			medium += other.medium;
+			high += other.high;
+			essential += other.essential;
+		}
+
+		public void Count(HolonElement element) {
+			switch (element.getPriority()) {
+			case Essential:
+				essential++;
+				break;
+			case High:
+				high++;
+				break;
+			case Medium:
+				medium++;
+				break;
+			case Low:
+				low++;
+				break;
+			default:
+				break;
+
+			}
+		}
 	}
 
 	public int getAmountOfAktiveElemntsFromHolonObjects() {
-		return passivList.stream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0, Integer::sum)+
-				supplierList.stream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0, Integer::sum)+
-				consumerList.stream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0, Integer::sum)+
-				groupNodeList.stream().map(groupNode -> groupNode.getAmountOfAktiveElemntsFromHolonObjects()).reduce(0, Integer::sum);
+		return objectStream().map(object -> object.getModel().getNumberOfActiveElements()).reduce(0,
+						Integer::sum)
+				+ groupNodeList.stream().map(groupNode -> groupNode.getAmountOfAktiveElemntsFromHolonObjects())
+						.reduce(0, Integer::sum);
 	}
-	public float getConsumptionFromConsumer() {		
-		return consumerList.stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.f, Float::sum)+
-				groupNodeList.stream().map(groupNode -> groupNode.getConsumptionFromConsumer()).reduce(0.f, Float::sum);
+
+	public float getConsumptionFromConsumer() {
+		return consumerList.stream().map(con -> con.getEnergyNeededFromNetwork()).reduce(0.f, Float::sum)
+				+ groupNodeList.stream().map(groupNode -> groupNode.getConsumptionFromConsumer()).reduce(0.f,
+						Float::sum);
 	}
-	public float getProductionFromSupplier() {		
-		return supplierList.stream().map(sup -> sup.getEnergyToSupplyNetwork()).reduce(0.f, Float::sum)+
-				groupNodeList.stream().map(groupNode -> groupNode.getProductionFromSupplier()).reduce(0.f, Float::sum);
+
+	public float getProductionFromSupplier() {
+		return supplierList.stream().map(sup -> sup.getEnergyToSupplyNetwork()).reduce(0.f, Float::sum) + groupNodeList
+				.stream().map(groupNode -> groupNode.getProductionFromSupplier()).reduce(0.f, Float::sum);
 	}
-	
+
 	public float getAverageConsumption() {
-		return getConsumptionFromConsumer() / (float)getAmountOfGroupNodes();
+		return getConsumptionFromConsumer() / (float) getAmountOfGroupNodes();
 	}
+
 	public float getAverageProduction() {
-		return getProductionFromSupplier() / (float)getAmountOfGroupNodes();
+		return getProductionFromSupplier() / (float) getAmountOfGroupNodes();
 	}
-	
-	
+
 	public String toString() {
-		return 
-				"GroupNode" + model.getId() + " with [Supplier:" + getAmountOfSupplier() 
-				+ ", NotSupplied:" + getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED) 
-				+ ", PartiallySupplied:" + getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED) 
-				+ ", Supplied:" + getAmountOfConsumerWithState(HolonObjectState.SUPPLIED) 
-				+ ", OverSupplied:" + getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED) 
-				+ ", Passiv:"+ getAmountOfPassiv() + "]";
+		return "GroupNode" + model.getId() + " with [Supplier:" + getAmountOfSupplier() + ", NotSupplied:"
+				+ getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED) + ", PartiallySupplied:"
+				+ getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED) + ", Supplied:"
+				+ getAmountOfConsumerWithState(HolonObjectState.SUPPLIED) + ", OverSupplied:"
+				+ getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED) + ", Passiv:" + getAmountOfPassiv()
+				+ "]";
 	}
 }

+ 0 - 19
src/ui/model/Model.java

@@ -54,8 +54,6 @@ public class Model {
     private int canvasX = 3000;
     private int canvasY = 3000;
     private int curIteration = 0;
-    // ID of the Selected Object
-    private AbstractCanvasObject selectedCpsObject = null;
     private HolonElement selectedHolonElement;
     private Edge selectedEdge;
     private ArrayList<AbstractCanvasObject> selectedObjects = new ArrayList<>();
@@ -282,23 +280,6 @@ public class Model {
         this.selectedID = id;
     }
 
-    /**
-     * Returns the Selected Cps Object.
-     *
-     * @return selected Cps Object
-     */
-    public AbstractCanvasObject getSelectedCpsObject() {
-        return selectedCpsObject;
-    }
-
-    /**
-     * Set the Selected Objecs.
-     *
-     * @param selectedCpsObject Objects that are selected
-     */
-    public void setSelectedCpsObject(AbstractCanvasObject selectedCpsObject) {
-        this.selectedCpsObject = selectedCpsObject;
-    }
 
     /**
      * Returns all selected Objects on the Canvas.

+ 16 - 8
src/ui/model/VisualRepresentationalState.java

@@ -12,6 +12,7 @@ import classes.Edge;
 import classes.Node;
 import ui.model.ExitCable.ExitCableState;
 import classes.GroupNode;
+import classes.HolonObject;
 
 public class VisualRepresentationalState {
 	private ArrayList<Supplier> supplierList = new ArrayList<Supplier>();
@@ -26,6 +27,8 @@ public class VisualRepresentationalState {
 	//ForFastAccessIndividualGroupNodes:
 	private HashMap<GroupNode, DecoratedGroupNode> createdGroupNodes;
 	
+	public HashMap<HolonObject, DecoratedHolonObject> createdHolonObjects;
+	
 	public VisualRepresentationalState(DecoratedState stateFromThisTimestep, MinimumModel minimumModel) {
 		reassignObjects(stateFromThisTimestep, minimumModel);
 	}
@@ -62,6 +65,7 @@ public class VisualRepresentationalState {
 		HashMap<Edge, ArrayList<GroupNode>> inGroupEdges = minimumModel.getInGroupEdges();
 		
 		createdGroupNodes =  new HashMap<GroupNode, DecoratedGroupNode>();
+		createdHolonObjects = new HashMap<HolonObject, DecoratedHolonObject>();
 		
 		ArrayList<IntermediateCalculationCable> exitCables = new ArrayList<IntermediateCalculationCable>();
 		//createThem
@@ -71,28 +75,32 @@ public class VisualRepresentationalState {
 		//unrolling Networks
 		for(DecoratedNetwork net : stateFromThisTimestep.getNetworkList()) {
 			for(Consumer con : net.getConsumerList()) {
-				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, con.getModel(), consumerList, con, createdGroupNodes);
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, con.getModel(), consumerList, con);
 				if(groupNodeFromObject != null) {
 					addToGroupNode(con, groupNodeFromObject.getConsumerList());
 				}
+				this.createdHolonObjects.put(con.getModel(), con);
 			}
 			for(Consumer con : net.getConsumerSelfSuppliedList()) {
-				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, con.getModel(), consumerList, con, createdGroupNodes);
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, con.getModel(), consumerList, con);
 				if(groupNodeFromObject != null) {
 					addToGroupNode(con, groupNodeFromObject.getConsumerList());
 				}
+				this.createdHolonObjects.put(con.getModel(), con);
 			}
 			for(Supplier sup : net.getSupplierList()) {
-				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, sup.getModel(), supplierList, sup, createdGroupNodes);
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, sup.getModel(), supplierList, sup);
 				if(groupNodeFromObject != null) {
 					addToGroupNode(sup, groupNodeFromObject.getSupplierList());
 				}
+				this.createdHolonObjects.put(sup.getModel(), sup);
 			}
 			for(Passiv pas : net.getPassivNoEnergyList()) {
-				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, pas.getModel(), passivList, pas, createdGroupNodes);
+				DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, pas.getModel(), passivList, pas);
 				if(groupNodeFromObject != null) {
 					addToGroupNode(pas, groupNodeFromObject.getPassivList());
 				}
+				this.createdHolonObjects.put(pas.getModel(), pas);
 			}
 			for(DecoratedCable cable : net.getDecoratedCableList()) {
 				addCable(cable, inGroupEdges, inGroupObjects,createdGroupNodes, exitCables);
@@ -102,19 +110,19 @@ public class VisualRepresentationalState {
 			addCable(cable, inGroupEdges, inGroupObjects, createdGroupNodes, exitCables);
 		}
 		for(Node node : minimumModel.getNodeList()) {
-			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, node, nodeList ,node, createdGroupNodes);
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, node, nodeList ,node);
 			if(groupNodeFromObject != null) {
 				addToGroupNode(node, groupNodeFromObject.getNodeList());
 			}
 		}
 		for(DecoratedSwitch dSwitch: stateFromThisTimestep.getDecoratedSwitches()) {
-			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, dSwitch.getModel(), switchList, dSwitch, createdGroupNodes);
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, dSwitch.getModel(), switchList, dSwitch);
 			if(groupNodeFromObject != null) {
 				addToGroupNode(dSwitch, groupNodeFromObject.getSwitchList());
 			}
 		}
 		for(DecoratedGroupNode dGroupNode: createdGroupNodes.values()) {
-			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, dGroupNode.getModel(), groupNodeList, dGroupNode, createdGroupNodes);
+			DecoratedGroupNode groupNodeFromObject = addObject(inGroupObjects, dGroupNode.getModel(), groupNodeList, dGroupNode);
 			if(groupNodeFromObject != null) {
 				addToGroupNode(dGroupNode, groupNodeFromObject.getGroupNodeList());
 			}
@@ -318,7 +326,7 @@ public class VisualRepresentationalState {
 	
 
 	//Generics
-	private <ModelOfObject, DecoratedObject> DecoratedGroupNode addObject(HashMap<ModelOfObject, GroupNode> inGroupObjects, ModelOfObject modelOfObject, ArrayList<DecoratedObject> listToAdd, DecoratedObject object, HashMap<GroupNode, DecoratedGroupNode> createdGroupNodes) {
+	private <ModelOfObject, DecoratedObject> DecoratedGroupNode addObject(HashMap<ModelOfObject, GroupNode> inGroupObjects, ModelOfObject modelOfObject, ArrayList<DecoratedObject> listToAdd, DecoratedObject object) {
 		if(inGroupObjects.containsKey(modelOfObject)) {
 			return  createdGroupNodes.get(inGroupObjects.get(modelOfObject));
 		}

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

@@ -2,7 +2,7 @@ package ui.view;
 
 import javax.swing.*;
 
-import utility.ImageImport;
+import util.ImageImport;
 
 import java.awt.*;
 

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

@@ -419,17 +419,6 @@ public abstract class AbstractCanvas extends JPanel {
 		        cellEditor.cancelCellEditing();
 		    }
 		}
-		
-		JTable propertys = model.getTableProperties();
-		cellEditor = propertys.getCellEditor();
-		if (cellEditor != null) {
-		    if (cellEditor.getCellEditorValue() != null) {
-		    	/** TODO: Maybe try to save current Data */
-		        cellEditor.stopCellEditing();
-		    } else {
-		        cellEditor.cancelCellEditing();
-		    }
-		}
 	}
 
 	/**

+ 1 - 1
src/ui/view/AddElementPopUp.java

@@ -3,7 +3,7 @@ package ui.view;
 import classes.AbstractCanvasObject;
 import classes.HolonElement;
 import classes.HolonObject;
-import utility.ImageImport;
+import util.ImageImport;
 
 import javax.swing.*;
 import javax.swing.border.EmptyBorder;

+ 1 - 1
src/ui/view/AddObjectPopUp.java

@@ -36,7 +36,7 @@ import classes.HolonElement;
 import classes.HolonObject;
 import classes.Pair;
 import ui.controller.Control;
-import utility.ImageImport;
+import util.ImageImport;
 
 /**
  * Popup for adding a Holon Object to a Category.

+ 1 - 1
src/ui/view/AddOnWindow.java

@@ -27,7 +27,7 @@ import javax.tools.ToolProvider;
 
 import api.AddOn;
 import ui.controller.Control;
-import utility.ImageImport;
+import util.ImageImport;
 
 public class AddOnWindow extends JFrame{
 	private AddOn actual;

+ 1 - 1
src/ui/view/BackgroundPopUp.java

@@ -3,7 +3,7 @@ package ui.view;
 import classes.GroupNode;
 import ui.controller.Control;
 import ui.model.Model;
-import utility.ImageImport;
+import util.ImageImport;
 
 import javax.swing.*;
 import javax.swing.filechooser.FileNameExtensionFilter;

+ 1 - 1
src/ui/view/CanvasResizePopUp.java

@@ -2,7 +2,7 @@ package ui.view;
 
 import ui.controller.Control;
 import ui.model.Model;
-import utility.ImageImport;
+import util.ImageImport;
 
 import javax.swing.*;
 import java.awt.*;

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

@@ -11,7 +11,7 @@ import javax.swing.JTextArea;
 import javax.swing.JToolBar;
 import javax.swing.text.DefaultCaret;
 
-import utility.ImageImport;
+import util.ImageImport;
 /**
  * Little new swing object to print data to a console.
  * @author tom

+ 1 - 1
src/ui/view/CreateTemplatePopUp.java

@@ -25,7 +25,7 @@ import classes.HolonObject;
 import classes.Pair;
 import ui.controller.Control;
 import ui.model.Model;
-import utility.ImageImport;
+import util.ImageImport;
 
 /**
  * PopUp for creating Holon Object Template.

+ 751 - 751
src/ui/view/FlexWindow.java

@@ -1,751 +1,751 @@
-package ui.view;
-
-import java.awt.BorderLayout;
-import java.awt.Color;
-import java.awt.Component;
-import java.awt.FlowLayout;
-import java.awt.GridBagConstraints;
-import java.awt.GridBagLayout;
-import java.awt.Insets;
-import java.awt.Rectangle;
-import java.awt.Dialog.ModalityType;
-import java.awt.Dimension;
-import java.awt.event.ItemEvent;
-import java.awt.event.MouseAdapter;
-import java.awt.event.MouseEvent;
-import java.awt.image.BufferedImage;
-import java.math.RoundingMode;
-import java.text.NumberFormat;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-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 classes.AbstractCanvasObject;
-import classes.Constrain;
-import classes.GroupNode;
-import classes.Flexibility;
-import classes.HolonElement;
-import classes.HolonElement.Priority;
-import classes.HolonObject;
-import ui.controller.Control;
-import ui.controller.FlexManager;
-import ui.controller.FlexManager.FlexState;
-import ui.controller.FlexManager.FlexWrapper;
-import ui.model.Model;
-import utility.ImageImport;
-
-
-public class FlexWindow extends JFrame {
-	private JPanel nothingSelectedPanel;
-	private JPanel selectedPanel;
-	
-	
-	private JTabbedPane contentPanel = new JTabbedPane();
-	private JScrollPane usageViewPanel;
-	
-	private Control controller;
-	private Model model;
-	
-	public boolean isClosed = false;
-	
-	//Flexibility Intermediate
-	private Flexibility intermediateFlex = new Flexibility(null);
-	private boolean offered = true, onConstrain = true, offConstrain =false;
-	
-	
-	
-	//JTree
-	private DefaultMutableTreeNode listOfAllSelectedHolonObjects;
-	private JTree stateTree;
-	private DefaultTreeModel treeModel;
-	private FlexManager flexmanager;
-	
-	//Tabs
-	String gridTabString = "Grid";
-	String orderTabString = "Order";
-	
-	//FlexToFlexWrapper()
-	
-	
-	
-	public FlexWindow(JFrame parentFrame, ui.controller.Control  controller){
-		this.intermediateFlex.name = "name";
-		this.controller = controller;
-		this.model = controller.getModel();
-		//InitWindow
-		createMenuBar();
-		initWindowPanel(parentFrame);
-		this.addWindowListener(new java.awt.event.WindowAdapter() {
-		    @Override
-		    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
-		    	isClosed = true;
-		    }
-		});
-		updateSelectedPanel();
-		//this.pack();
-	}
-
-
-
-	private void initWindowPanel(JFrame parentFrame) {
-		this.setBounds(0, 0, 400, parentFrame.getHeight()>20?parentFrame.getHeight()- 20:parentFrame.getHeight());
-		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png", 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() {
-		flexmanager = controller.getSimManager().getActualFlexManager();
-		//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++){
-			
-			
-			
-			
-			List<FlexWrapper> listOfFlexWithState = flexmanager.getAllFlexWrapperWithState(titles[i]);
-			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()?"-":"+");
-			});
-			
-		}
-		//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<FlexWrapper> flexWrapperList) {
-		listPanel.setBackground(Color.white);
-		
-		Insets insets = new Insets(2,2,2,2);
-		
-		//String[] flexesString = flexWrapperList.stream().map(flexWrapper -> flexWrapper.getFlex().name).toArray(String[]::new);
-		for(int i = 0; i < flexWrapperList.size(); i++) {
-			FlexWrapper actual = flexWrapperList.get(i);
-			GridBagConstraints c = new GridBagConstraints();
-			c.gridx = Math.floorMod(i, 5);
-			c.weightx = 0.0;	
-			c.insets = insets;
-			JButton labelButton = new JButton(actual.getFlex().name);
-			labelButton.setPreferredSize(new Dimension(70,70));
-			labelButton.setBorder(BorderFactory.createLineBorder(Color.black));
-			listPanel.add(labelButton, c);
-			labelButton.addActionListener(clicked ->{
-				actual.order();
-				controller.calculateStateAndVisualForCurrentTimeStep();
-				controller.updateCanvas();
-			});
-			labelButton.setToolTipText(createToolTipp(actual));
-		}
-		//AddSpacer
-		JLabel spacer = new JLabel();
-		GridBagConstraints c = new GridBagConstraints();
-		c.gridx = 5;
-		c.gridy = 0;
-		c.fill = GridBagConstraints.VERTICAL;
-		c.weightx = 1;
-		c.weighty = 0;
-	
-		listPanel.add(spacer, c);
-		
-	}
-
-
-	private String createToolTipp(FlexWrapper actual) {
-		String tooltipString = "<html>" +
-	"<b>" + actual.getFlex().name + "( </b>" + actual.getFlex().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.getFlex().getDuration()  + "<br>"
-	+ "Cooldown: " + actual.getFlex().getCooldown() + "<br>"
-	//+ "Speed: " + actual.getFlex().speed + "<br>"
-	+ "Cost: " + actual.getFlex().cost + "<br>"
-	+ "BrigtMir: " + actual.getFlex().bringtmir() + "<br>"
-	+ "Constrains: " + actual.getFlex().constrainList.stream().map(constrain -> constrain.getName()).collect(Collectors.joining( "," )) + "<br>"
-	+ "</html>";
-		
-		return tooltipString;
-	}
-
-
-
-	public void update() {
-		updateSelectedPanel();
-		createUsageViewPanel();
-		contentPanel.setComponentAt(contentPanel.indexOfTab(orderTabString), usageViewPanel);
-		contentPanel.revalidate();
-	}
-
-	
-	
-	
-	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) {
-											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;
-											ElementInfo eleInfo = (ElementInfo) treeNodeUserObject;
-											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))
-									return;
-								createAddDialog(((ElementInfo) treeNodeUserObject).ele);
-			   	        });
-			         	    
-		                    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() {
-		//UpdateFlexManager
-		flexmanager = controller.getSimManager().getActualFlexManager();
-		
-		listOfAllSelectedHolonObjects.removeAllChildren();
-		//Init with HolonObjects
-		for(AbstractCanvasObject aCps: model.getObjectsOnCanvas()) {
-			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(aCps.getName() + " ID:" + aCps.getId());
-			if(aCps instanceof HolonObject) expandTreeHolonObject((HolonObject)aCps, newObjectChild);
-			if(aCps instanceof GroupNode)expandTreeUpperNode((GroupNode)aCps, 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) {
-		for(AbstractCanvasObject aCps: groupNode.getNodes()) {
-			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(aCps.getName() + " ID:" + aCps.getId());
-			if(aCps instanceof HolonObject) expandTreeHolonObject((HolonObject)aCps, newObjectChild);
-			if(aCps instanceof GroupNode)expandTreeUpperNode((GroupNode)aCps, newObjectChild);
-			root.add(newObjectChild);
-		}
-		
-	}
-
-
-
-	private void expandTreeHolonObject(HolonObject hObject, DefaultMutableTreeNode root) {
-		for(HolonElement hElement: hObject.getElements()) {
-			DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(new ElementInfo(hElement));
-			expandTreeFlex(hElement, newChild);
-			root.add(newChild);
-		}
-	}
-	private void expandTreeFlex(HolonElement hElement, DefaultMutableTreeNode root) {
-		for(Flexibility flex: hElement.flexList) {
-			FlexWrapper flexWrapper = this.flexmanager.getFlexWrapperFromFlexibility(flex);
-			String flexState = "";
-			if(flexWrapper != null) {
-				Color color = this.FlexStateToColor(flexWrapper.getState());
-				flexState = "<font bgcolor='#" + Integer.toHexString(color.getRGB()).substring(2) + "'>" + flexWrapper.getState().name() + "</font>";
-			}
-			DefaultMutableTreeNode newChild = new DefaultMutableTreeNode("<html>"+ flexState + " <b>" + flex.name+ "</b>" + "</html>");
-			root.add(newChild);
-		}
-	}
-	
-	
-	private void createDeleteDialog() {
-		
-		List<HolonObject> list= createListOfHolonObjects(model.getObjectsOnCanvas());
-		
-		//String test = list.stream().map(Object::toString).collect(Collectors.joining(","));
-		Object[] allFlexes = list.stream().flatMap(hObject -> hObject.getElements().stream()).flatMap(hElement -> hElement.flexList.stream()).toArray(size -> new Flexibility[size]);
-		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);
-			controller.getSimManager().calculateStateForTimeStep(model.getCurIteration(), true);
-			updateSelectedPanel();
-		}
-	}
-	
-	
-	
-	private List<HolonObject> createListOfHolonObjects(List<AbstractCanvasObject> objectsOnCanvas) {
-		List<HolonObject> list = new ArrayList<HolonObject>();
-		for(AbstractCanvasObject aCps :  objectsOnCanvas) {
-			if(aCps instanceof HolonObject) list.add((HolonObject) aCps);
-			else if (aCps instanceof GroupNode) list.addAll(createListOfHolonObjects(((GroupNode)aCps).getNodes()));
-		}
-		return list;
-	}
-
-
-
-	//Add Element
-	private void createAddDialog(HolonElement element){
-		if(model.getObjectsOnCanvas().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);
-		
-		
-
-		//Erstelle HolonObject AuswahlBox
-		HolonObject[] holonObjects = createListOfHolonObjects(model.getObjectsOnCanvas()).stream().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].getElements().stream().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()).getElements().stream().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 moreThenZeroIntegerFormater = new NumberFormatter(format);
-		moreThenZeroIntegerFormater.setMinimum(1);
-		moreThenZeroIntegerFormater.setCommitsOnValidEdit(true);
-		
-		JFormattedTextField durationTextField = new  JFormattedTextField(moreThenZeroIntegerFormater);
-		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(moreThenZeroIntegerFormater);
-		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 -> {
-			//createFlexButton.requestFocus();
-			//createFlexButton.grabFocus();
-			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());
-			
-			ele.flexList.add(toCreateFlex);
-			//save checkboxes
-			this.offered=offeredCheckBox.isSelected();
-			this.onConstrain = onConstrainCheckBox.isSelected();
-			this.offConstrain = offConstrainCheckBox.isSelected();
-			
-			
-			//if(!model.getSelectedCpsObjects().contains(holonObjectSelector.getSelectedItem()))model.getSelectedCpsObjects().add((AbstractCpsObject)holonObjectSelector.getSelectedItem());
-			controller.getSimManager().calculateStateForTimeStep(model.getCurIteration(), true);
-			
-			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();
-		}
-	}
-	
-	public Color FlexStateToColor(FlexState state) {
-		switch(state) {
-		case IN_USE:
-			return new Color(173,247,182);
-		case NOT_OFFERED:
-			return new Color(252,245,199);
-		case OFFERED:
-			return new Color(160,206,217);
-		case ON_COOLDOWN:
-			return new Color(255,238,147);
-		case UNAVAILABLE:
-		default:
-			return new Color(255,192,159);
-		}
-	}
-	
-}
+package ui.view;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.FlowLayout;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.Rectangle;
+import java.awt.Dialog.ModalityType;
+import java.awt.Dimension;
+import java.awt.event.ItemEvent;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.awt.image.BufferedImage;
+import java.math.RoundingMode;
+import java.text.NumberFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+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 classes.AbstractCanvasObject;
+import classes.Constrain;
+import classes.GroupNode;
+import classes.Flexibility;
+import classes.HolonElement;
+import classes.HolonElement.Priority;
+import classes.HolonObject;
+import ui.controller.Control;
+import ui.controller.FlexManager;
+import ui.controller.FlexManager.FlexState;
+import ui.controller.FlexManager.FlexWrapper;
+import ui.model.Model;
+import utility.ImageImport;
+
+
+public class FlexWindow extends JFrame {
+	private JPanel nothingSelectedPanel;
+	private JPanel selectedPanel;
+	
+	
+	private JTabbedPane contentPanel = new JTabbedPane();
+	private JScrollPane usageViewPanel;
+	
+	private Control controller;
+	private Model model;
+	
+	public boolean isClosed = false;
+	
+	//Flexibility Intermediate
+	private Flexibility intermediateFlex = new Flexibility(null);
+	private boolean offered = true, onConstrain = true, offConstrain =false;
+	
+	
+	
+	//JTree
+	private DefaultMutableTreeNode listOfAllSelectedHolonObjects;
+	private JTree stateTree;
+	private DefaultTreeModel treeModel;
+	private FlexManager flexmanager;
+	
+	//Tabs
+	String gridTabString = "Grid";
+	String orderTabString = "Order";
+	
+	//FlexToFlexWrapper()
+	
+	
+	
+	public FlexWindow(JFrame parentFrame, ui.controller.Control  controller){
+		this.intermediateFlex.name = "name";
+		this.controller = controller;
+		this.model = controller.getModel();
+		//InitWindow
+		createMenuBar();
+		initWindowPanel(parentFrame);
+		this.addWindowListener(new java.awt.event.WindowAdapter() {
+		    @Override
+		    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
+		    	isClosed = true;
+		    }
+		});
+		updateSelectedPanel();
+		//this.pack();
+	}
+
+
+
+	private void initWindowPanel(JFrame parentFrame) {
+		this.setBounds(0, 0, 400, parentFrame.getHeight()>20?parentFrame.getHeight()- 20:parentFrame.getHeight());
+		this.setIconImage(ImageImport.loadImage("/Images/Holeg.png", 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() {
+		flexmanager = controller.getSimManager().getActualFlexManager();
+		//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++){
+			
+			
+			
+			
+			List<FlexWrapper> listOfFlexWithState = flexmanager.getAllFlexWrapperWithState(titles[i]);
+			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()?"-":"+");
+			});
+			
+		}
+		//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<FlexWrapper> flexWrapperList) {
+		listPanel.setBackground(Color.white);
+		
+		Insets insets = new Insets(2,2,2,2);
+		
+		//String[] flexesString = flexWrapperList.stream().map(flexWrapper -> flexWrapper.getFlex().name).toArray(String[]::new);
+		for(int i = 0; i < flexWrapperList.size(); i++) {
+			FlexWrapper actual = flexWrapperList.get(i);
+			GridBagConstraints c = new GridBagConstraints();
+			c.gridx = Math.floorMod(i, 5);
+			c.weightx = 0.0;	
+			c.insets = insets;
+			JButton labelButton = new JButton(actual.getFlex().name);
+			labelButton.setPreferredSize(new Dimension(70,70));
+			labelButton.setBorder(BorderFactory.createLineBorder(Color.black));
+			listPanel.add(labelButton, c);
+			labelButton.addActionListener(clicked ->{
+				actual.order();
+				controller.calculateStateAndVisualForCurrentTimeStep();
+				controller.updateCanvas();
+			});
+			labelButton.setToolTipText(createToolTipp(actual));
+		}
+		//AddSpacer
+		JLabel spacer = new JLabel();
+		GridBagConstraints c = new GridBagConstraints();
+		c.gridx = 5;
+		c.gridy = 0;
+		c.fill = GridBagConstraints.VERTICAL;
+		c.weightx = 1;
+		c.weighty = 0;
+	
+		listPanel.add(spacer, c);
+		
+	}
+
+
+	private String createToolTipp(FlexWrapper actual) {
+		String tooltipString = "<html>" +
+	"<b>" + actual.getFlex().name + "( </b>" + actual.getFlex().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.getFlex().getDuration()  + "<br>"
+	+ "Cooldown: " + actual.getFlex().getCooldown() + "<br>"
+	//+ "Speed: " + actual.getFlex().speed + "<br>"
+	+ "Cost: " + actual.getFlex().cost + "<br>"
+	+ "BrigtMir: " + actual.getFlex().bringtmir() + "<br>"
+	+ "Constrains: " + actual.getFlex().constrainList.stream().map(constrain -> constrain.getName()).collect(Collectors.joining( "," )) + "<br>"
+	+ "</html>";
+		
+		return tooltipString;
+	}
+
+
+
+	public void update() {
+		updateSelectedPanel();
+		createUsageViewPanel();
+		contentPanel.setComponentAt(contentPanel.indexOfTab(orderTabString), usageViewPanel);
+		contentPanel.revalidate();
+	}
+
+	
+	
+	
+	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) {
+											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;
+											ElementInfo eleInfo = (ElementInfo) treeNodeUserObject;
+											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))
+									return;
+								createAddDialog(((ElementInfo) treeNodeUserObject).ele);
+			   	        });
+			         	    
+		                    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() {
+		//UpdateFlexManager
+		flexmanager = controller.getSimManager().getActualFlexManager();
+		
+		listOfAllSelectedHolonObjects.removeAllChildren();
+		//Init with HolonObjects
+		for(AbstractCanvasObject aCps: model.getObjectsOnCanvas()) {
+			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(aCps.getName() + " ID:" + aCps.getId());
+			if(aCps instanceof HolonObject) expandTreeHolonObject((HolonObject)aCps, newObjectChild);
+			if(aCps instanceof GroupNode)expandTreeUpperNode((GroupNode)aCps, 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) {
+		for(AbstractCanvasObject aCps: groupNode.getNodes()) {
+			DefaultMutableTreeNode newObjectChild = new DefaultMutableTreeNode(aCps.getName() + " ID:" + aCps.getId());
+			if(aCps instanceof HolonObject) expandTreeHolonObject((HolonObject)aCps, newObjectChild);
+			if(aCps instanceof GroupNode)expandTreeUpperNode((GroupNode)aCps, newObjectChild);
+			root.add(newObjectChild);
+		}
+		
+	}
+
+
+
+	private void expandTreeHolonObject(HolonObject hObject, DefaultMutableTreeNode root) {
+		for(HolonElement hElement: hObject.getElements()) {
+			DefaultMutableTreeNode newChild = new DefaultMutableTreeNode(new ElementInfo(hElement));
+			expandTreeFlex(hElement, newChild);
+			root.add(newChild);
+		}
+	}
+	private void expandTreeFlex(HolonElement hElement, DefaultMutableTreeNode root) {
+		for(Flexibility flex: hElement.flexList) {
+			FlexWrapper flexWrapper = this.flexmanager.getFlexWrapperFromFlexibility(flex);
+			String flexState = "";
+			if(flexWrapper != null) {
+				Color color = this.FlexStateToColor(flexWrapper.getState());
+				flexState = "<font bgcolor='#" + Integer.toHexString(color.getRGB()).substring(2) + "'>" + flexWrapper.getState().name() + "</font>";
+			}
+			DefaultMutableTreeNode newChild = new DefaultMutableTreeNode("<html>"+ flexState + " <b>" + flex.name+ "</b>" + "</html>");
+			root.add(newChild);
+		}
+	}
+	
+	
+	private void createDeleteDialog() {
+		
+		List<HolonObject> list= createListOfHolonObjects(model.getObjectsOnCanvas());
+		
+		//String test = list.stream().map(Object::toString).collect(Collectors.joining(","));
+		Object[] allFlexes = list.stream().flatMap(hObject -> hObject.getElements().stream()).flatMap(hElement -> hElement.flexList.stream()).toArray(size -> new Flexibility[size]);
+		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);
+			controller.getSimManager().calculateStateForTimeStep(model.getCurIteration(), true);
+			updateSelectedPanel();
+		}
+	}
+	
+	
+	
+	private List<HolonObject> createListOfHolonObjects(List<AbstractCanvasObject> objectsOnCanvas) {
+		List<HolonObject> list = new ArrayList<HolonObject>();
+		for(AbstractCanvasObject aCps :  objectsOnCanvas) {
+			if(aCps instanceof HolonObject) list.add((HolonObject) aCps);
+			else if (aCps instanceof GroupNode) list.addAll(createListOfHolonObjects(((GroupNode)aCps).getNodes()));
+		}
+		return list;
+	}
+
+
+
+	//Add Element
+	private void createAddDialog(HolonElement element){
+		if(model.getObjectsOnCanvas().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);
+		
+		
+
+		//Erstelle HolonObject AuswahlBox
+		HolonObject[] holonObjects = createListOfHolonObjects(model.getObjectsOnCanvas()).stream().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].getElements().stream().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()).getElements().stream().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 moreThenZeroIntegerFormater = new NumberFormatter(format);
+		moreThenZeroIntegerFormater.setMinimum(1);
+		moreThenZeroIntegerFormater.setCommitsOnValidEdit(true);
+		
+		JFormattedTextField durationTextField = new  JFormattedTextField(moreThenZeroIntegerFormater);
+		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(moreThenZeroIntegerFormater);
+		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 -> {
+			//createFlexButton.requestFocus();
+			//createFlexButton.grabFocus();
+			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());
+			
+			ele.flexList.add(toCreateFlex);
+			//save checkboxes
+			this.offered=offeredCheckBox.isSelected();
+			this.onConstrain = onConstrainCheckBox.isSelected();
+			this.offConstrain = offConstrainCheckBox.isSelected();
+			
+			
+			//if(!model.getSelectedCpsObjects().contains(holonObjectSelector.getSelectedItem()))model.getSelectedCpsObjects().add((AbstractCpsObject)holonObjectSelector.getSelectedItem());
+			controller.getSimManager().calculateStateForTimeStep(model.getCurIteration(), true);
+			
+			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();
+		}
+	}
+	
+	public Color FlexStateToColor(FlexState state) {
+		switch(state) {
+		case IN_USE:
+			return new Color(173,247,182);
+		case NOT_OFFERED:
+			return new Color(252,245,199);
+		case OFFERED:
+			return new Color(160,206,217);
+		case ON_COOLDOWN:
+			return new Color(255,238,147);
+		case UNAVAILABLE:
+		default:
+			return new Color(255,192,159);
+		}
+	}
+	
+}

+ 18 - 161
src/ui/view/GUI.java

@@ -94,6 +94,8 @@ import ui.model.Model.FairnessModel;
 import ui.view.CreateNewDialog.Option;
 import ui.view.outliner.Outliner;
 import utility.ImageImport;
+import util.Event;
+import util.ImageImport;
 
 /**
  * Graphical User Interface.
@@ -104,6 +106,10 @@ public class GUI{
 	
 	static final Color PALE_RED=new Color(255, 192, 192);
 	
+	
+	
+	
+	
 	/**
 	 * Menu on the Top containing File, Edit View Help etc
 	 */
@@ -114,6 +120,9 @@ public class GUI{
 	private final JMenu mnNewMenuView = new JMenu("View");
 	private final JMenu menuWindow = new JMenu("Window");
 	
+	
+	private final HolonInformationPanel informationPanel;
+	
 	/** Help Menu containing helpful Informations and the AboutUs Popup */
 	private final JMenu mnHelp = new JMenu("Help");
 	
@@ -193,31 +202,7 @@ public class GUI{
 	// Model for single or multi selection
 	private final JPanel scrollElements = new JPanel();
 	private final JScrollPane tableHolonElementScrollPane = new JScrollPane();
-	// In this section are all the properties that correspond to the clicked
-	// HolonObject, such as connections, name, Type, etc.
-	// Table for Properties --> Cell with (0,1) is editable by CpsObjt and
-	// Cell(3,1) is editable by Edges
-	private final JTable tableProperties = new JTable() {
-
-		@Override
-		public TableCellRenderer getCellRenderer(int row, int column) {
-			if (getValueAt(row, column) instanceof Boolean) {
-				return super.getDefaultRenderer(Boolean.class);
-			} else {
-				return super.getCellRenderer(row, column);
-			}
-		}
-
-		@Override
-		public TableCellEditor getCellEditor(int row, int column) {
-			if (getValueAt(row, column) instanceof Boolean) {
-				return super.getDefaultEditor(Boolean.class);
-			} else {
-				return super.getCellEditor(row, column);
-			}
-		}
 
-	};
 	//Prechoosed local Periods
 	private String[] comboContext = {
 	         "", "5", "10", "20" ,"100", "1000"
@@ -230,7 +215,6 @@ public class GUI{
 	private final JScrollPane scrollProperties = new JScrollPane();
 	// In this section is the graph for the selected HolonElement of the clicked
 	// HolonObject
-	private final JTable tableGraph = new JTable();
 	private final DefaultTableModel tableModelGraph = new DefaultTableModel();
 	private final JScrollPane scrollGraph = new JScrollPane();
 	private final Model model;
@@ -305,10 +289,6 @@ public class GUI{
 	private int yBTis;
 	private int xBThis;
 	// Coord for the Edit-Modus in the PropertieTable
-	private int yProThis;
-	private int xProThis;
-	private int yProThisOneClick;
-	private int xProThisOneClick;
 	private AbstractCanvasObject temp = null;
 	private String warningText = "Warning";
 	private String saveBeforeNew = "Do you want to save your current data?";
@@ -330,11 +310,11 @@ public class GUI{
 	 */
 	GUI(Control control) {
 		this.controller = control;
+		this.informationPanel = new HolonInformationPanel(control);
 		this.model = control.getModel();
 		control.setGui(this);
 		this.unitGraph = new UnitGraph(model, control);
 		this.canvas = new MyCanvas(model, control, unitGraph);
-		model.setTableProperties(tableProperties);
 		initialize();
 		updateCategories(model.getCategories());
 		updCon = new UpdateController(model, controller);
@@ -453,7 +433,7 @@ public class GUI{
 			public void actionPerformed(ActionEvent e) {
 				chooseTabTemp();
 
-				model.getSelectedCpsObjects().clear();
+				controller.clearSelection();
 
 				// Uppernode Canvas?
 				JScrollPane scrollPane = getScrollPaneFromTabbedPane();
@@ -541,7 +521,7 @@ public class GUI{
 					controller.calculateStateAndVisualForCurrentTimeStep();
 				}
 
-				model.getSelectedCpsObjects().clear();
+				controller.clearSelection();
 				hideScrollGraph();
 			}
 		});
@@ -975,17 +955,11 @@ public class GUI{
 		panelHolonEl.add(toolBarHolonEl);
 
 		// Set up of the Properties section
-		tableProperties.setModel(model.getPropertyTable());
-		tableProperties.setFillsViewportHeight(true);
-		tableProperties.setCellSelectionEnabled(true);
-		tableProperties.setColumnSelectionAllowed(true);
-		scrollProperties.setViewportView(tableProperties);
-
+		scrollProperties.setViewportView(this.informationPanel);
+		scrollProperties.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
+		scrollProperties.getVerticalScrollBar().setUnitIncrement(16);
+		
 		// Set up of the Graph section
-		tableGraph.setModel(tableModelGraph);
-		tableGraph.setFillsViewportHeight(true);
-		tableGraph.setCellSelectionEnabled(true);
-		tableGraph.setColumnSelectionAllowed(true);
 		scrollGraph.setViewportView(unitGraph);
 		graphLabel.setLayout(new BorderLayout(0, 10));
 		graphLabel.add(maxGraph, BorderLayout.NORTH);
@@ -1388,124 +1362,7 @@ public class GUI{
 					} catch (Exception e) {
 					}
 				});
-		/***********************
-		 * HolonElement Properties Actions
-		 **********************/
-
-		/*
-		 * Update of the mouse coord for Edit-Mode
-		 */
-		tableProperties.addMouseListener(new MouseAdapter() {
-			public void mousePressed(MouseEvent e) {
-				if (e.getClickCount() == 2) {
-					yProThis = e.getY();
-					xProThis = e.getX();
-				}
-				yProThisOneClick = e.getY();
-				xProThisOneClick = e.getX();
-			}
-		});
-
-		/*
-		 * Update any change in the Property table
-		 */
-		tableProperties.addPropertyChangeListener(propertyChangeEvent -> {
-			try {
-				Object temp;
-				Object btemp;
-				int selValueY = (int) Math.floor(yProThis / 16);
-				int selValueX = (int) Math.floor(xProThis
-						/ (tableProperties.getWidth() / 2));
-				int selValueYBool = (int) Math.floor(yProThisOneClick / 16);
-				int selValueXBool = (int) Math.floor(xProThisOneClick
-						/ (tableProperties.getWidth() / 2));
-				if (updCon.getActualCps() != null) {
-					temp = model.getPropertyTable().getValueAt(selValueY,
-							selValueX);
-					btemp = model.getPropertyTable().getValueAt(selValueYBool,
-							selValueXBool);
-					// Case: Switch selected
-
-				if (updCon.getActualCps() instanceof HolonSwitch) {
-					if (selValueY == 0 && selValueX != 0) {
-						updCon.getActualCps().setName(temp.toString());
-					}
-					if (selValueYBool == 2) {
-						Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
-						((HolonSwitch) updCon.getActualCps())
-								.setManualMode(bbTemp);
-						if (bbTemp) {
-							model.getPropertyTable()
-									.setCellEditable(3, 1, true);
-						} else {
-							model.getPropertyTable().setCellEditable(3, 1,
-									false);
-						}
-					} else if (selValueYBool == 3) {
-						if (((HolonSwitch) updCon.getActualCps())
-								.getManualMode()) {
-							model.getPropertyTable()
-									.setCellEditable(3, 1, true);
-							Boolean bTemp = Boolean.parseBoolean(btemp
-									.toString());
-							((HolonSwitch) updCon.getActualCps())
-									.setManualState(bTemp);
-						}
-					}
-				} // Case: UpperNode selected
-				else if (updCon.getActualCps() instanceof GroupNode
-						&& selValueX != 0) {
-					// Name edition through double click
-					updCon.getActualCps().setName(temp.toString());
-					// Update of name on the tab in the tab section
-					for (int index = 4; index < tabbedPaneOriginal
-							.getTabCount(); index++) {
-						tabTemp = tabbedPaneOriginal;
-						JScrollPane scrollPane = getScrollPaneFromTabbedPane();
-
-						GroupNodeCanvas unc = ((GroupNodeCanvas) scrollPane
-								.getViewport().getComponent(0));
-
-						if (unc.upperNode.getId() == updCon.getActualCps()
-								.getId()) {
-							tabbedPaneOriginal.setTitleAt(index,
-									unc.upperNode.getName());
-							tabbedPaneOriginal.updateUI();
-							if (!initSplit) {
-								tabbedPaneSplit.setTitleAt(index,
-										unc.upperNode.getName());
-								tabbedPaneSplit.updateUI();
-							}
-						}
-					}
-				} // Case: HolonObject is selected
-				else if (updCon.getActualCps() instanceof HolonObject
-						&& selValueX != 0) {
-					// Name edition through double click
-					updCon.getActualCps().setName(temp.toString());
-				}
-			} // Case: Edge is selected
-			else {
-				temp = model.getPropertyTable()
-						.getValueAt(selValueY, selValueX);
-				btemp = model.getPropertyTable().getValueAt(selValueYBool,
-						selValueXBool);
-				// Edit modus for capacity by double clicking
-				if (selValueY == 2) {
-					Float ftemp;
-					if (Float.parseFloat(temp.toString()) >= 0.0) {
-						ftemp = Float.parseFloat(temp.toString());
-					} else {
-						ftemp = model.getSelectedEdge().getCapacity();
-					}
-					model.getSelectedEdge().setCapacity(ftemp);
-				}
-			}
-			canvas.repaint();
-		} catch (Exception e) {
-		}
-	})	;
-
+	
 		/***********************
 		 * HolonElement Graph Actions
 		 **********************/
@@ -1957,7 +1814,7 @@ public class GUI{
 				}
 				if (e.isControlDown() && temp != null) {
 					if (model.getSelectedCpsObjects().contains(temp)) {
-						controller.deleteSelectedObject(temp);
+						controller.removeSelectedObjectFromSelection(temp);
 					} else {
 						controller.addSelectedObject(temp);
 					}

+ 6 - 6
src/ui/view/GroupNodeCanvas.java

@@ -45,10 +45,10 @@ import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedSwitch;
 import ui.model.ExitCable;
 import ui.model.DecoratedSwitch.SwitchState;
+import util.ImageImport;
 import ui.model.Model;
 import ui.model.Passiv;
 import ui.model.Supplier;
-import utility.ImageImport;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
@@ -239,7 +239,7 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                 }
             }
             toolTip = false;
-            model.getSelectedCpsObjects().clear();
+            controller.clearSelection();
             tempCps = null;
             repaint();
         });
@@ -643,7 +643,7 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                     dragging = true;
                     if (e.isControlDown() && tempCps != null) {
                         if (model.getSelectedCpsObjects().contains(tempCps)) {
-                            controller.deleteSelectedObject(tempCps);
+                            controller.removeSelectedObjectFromSelection(tempCps);
                         } else {
                             controller.addSelectedObject(tempCps);
                             if(tempCps instanceof GroupNode)
@@ -701,7 +701,7 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
                 controller.setSelecteEdge(edgeHighlight);
                 controller.setSelectedObjectID(0);
                 if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
-                    model.getSelectedCpsObjects().clear();
+                    controller.clearSelection();
                 }
                 updCon.deleteRows(model.getMultiTable());
                 updCon.deleteRows(model.getSingleTable());
@@ -766,7 +766,7 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         }
 
         if (!e.isControlDown() && !dragged && tempCps != null && MouseEvent.BUTTON3 != e.getButton()) {
-            model.getSelectedCpsObjects().clear();
+            controller.clearSelection();
             controller.addSelectedObject(tempCps);
             if(tempCps instanceof GroupNode)
 				controller.getObjectsInDepth();
@@ -796,7 +796,7 @@ public class GroupNodeCanvas extends AbstractCanvas implements MouseListener, Mo
         x = e.getX();
         y = e.getY();
         if (!model.getSelectedCpsObjects().contains(tempCps) && !doMark) {
-            model.getSelectedCpsObjects().clear();
+            controller.clearSelection();
             if (tempCps != null) {
                 controller.addSelectedObject(tempCps);
             }

+ 427 - 0
src/ui/view/HolonInformationPanel.java

@@ -0,0 +1,427 @@
+package ui.view;
+
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.Component;
+import java.awt.Font;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.GridLayout;
+import java.awt.Insets;
+import java.awt.event.MouseAdapter;
+import java.awt.event.MouseEvent;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import javax.swing.BorderFactory;
+import javax.swing.BoxLayout;
+import javax.swing.JFrame;
+import javax.swing.JLabel;
+import javax.swing.JLayeredPane;
+import javax.swing.JPanel;
+import javax.swing.JTextField;
+import javax.swing.OverlayLayout;
+import javax.swing.SwingUtilities;
+import javax.swing.border.EmptyBorder;
+
+import org.knowm.xchart.CategoryChart;
+import org.knowm.xchart.CategoryChartBuilder;
+import org.knowm.xchart.PieChart;
+import org.knowm.xchart.PieChartBuilder;
+import org.knowm.xchart.PieSeries.PieSeriesRenderStyle;
+import org.knowm.xchart.XChartPanel;
+import org.knowm.xchart.style.CategoryStyler;
+import org.knowm.xchart.style.PieStyler;
+import org.knowm.xchart.style.PieStyler.LabelType;
+
+import classes.AbstractCanvasObject;
+import classes.Flexibility;
+import classes.GroupNode;
+import classes.HolonElement;
+import classes.HolonObject;
+import preferences.ColorPreference;
+import ui.controller.Control;
+import ui.controller.FlexManager;
+import ui.controller.FlexManager.FlexWrapper;
+import ui.model.Consumer;
+import ui.model.DecoratedGroupNode;
+import ui.model.DecoratedGroupNode.PriorityCounts;
+import ui.model.DecoratedHolonObject;
+import ui.model.DecoratedHolonObject.HolonObjectState;
+import ui.model.Model;
+import ui.model.Passiv;
+import ui.model.Supplier;
+import util.StringFormat;
+
+public class HolonInformationPanel extends JPanel {
+
+	private final int defaultWidth = 50;
+	private final int defaultHeight = 200;
+
+	private PieChart supplyChart = createSupplyStateChart();
+	private PieChart priorityChart = createPriorityChart();
+	private PieChart flexibilityChart = createFlexibilityChart();
+	private PieChart energyChart = createProductionChart();
+	private PieChart activeChart = createActiveChart();
+
+	private XChartPanel<PieChart> panelHolonObject;
+	private XChartPanel<PieChart> panelPriority;
+	private XChartPanel<PieChart> panelFlexibility;
+	private XChartPanel<PieChart> panelEnergy;
+	private XChartPanel<PieChart> panelActive;
+
+	// TODO is this needed to be fields
+	private JPanel graphPanel = new JPanel(new GridLayout(0, 2));
+	private JPanel titlePanel = new JPanel(new BorderLayout(0, 0));
+
+	private Control control;
+	private JTextField titleTextField;
+	private JLabel differenceEnergyLabelAmount;
+
+	public static void main(String[] args) {
+		HolonInformationPanel exampleChart = new HolonInformationPanel(new Control(new Model()));
+		JFrame frame = new JFrame();
+		frame.setContentPane(exampleChart);
+
+		frame.pack();
+		frame.setBounds(0, 0, 540, 600);
+		frame.setLocationRelativeTo(null);
+		frame.setVisible(true);
+	}
+
+	public void updateCharts() {
+		DecoratedGroupNode decoratedGroupNode;
+		switch (control.getModel().getSelectedCpsObjects().size()) {
+		case 0:
+			return;
+		case 1:
+			titleTextField.setText(control.getModel().getSelectedCpsObjects().get(0).getName());
+			decoratedGroupNode = multiSelectionToDecoratedGroupNode();
+			break;
+		default:
+			titleTextField.setText(getMultiSelectionName());
+			decoratedGroupNode = multiSelectionToDecoratedGroupNode();
+			break;
+		}
+
+		// UPDATE SUPPLY STATE
+		int producerAmount = decoratedGroupNode.getAmountOfSupplier();
+		int overSuppliedAmount = decoratedGroupNode.getAmountOfConsumerWithState(HolonObjectState.OVER_SUPPLIED);
+		int suppliedAmount = decoratedGroupNode.getAmountOfConsumerWithState(HolonObjectState.SUPPLIED);
+		int partiallySuppliedAmount = decoratedGroupNode
+				.getAmountOfConsumerWithState(HolonObjectState.PARTIALLY_SUPPLIED);
+		int notSuppliedAmount = decoratedGroupNode.getAmountOfConsumerWithState(HolonObjectState.NOT_SUPPLIED);
+		int noEnergyAmount = decoratedGroupNode.getAmountOfPassiv();
+
+		supplyChart.updatePieSeries("Producer", producerAmount);
+		supplyChart.updatePieSeries("Over supplied", overSuppliedAmount);
+		supplyChart.updatePieSeries("Supplied", suppliedAmount);
+		supplyChart.updatePieSeries("Partial supplied", partiallySuppliedAmount);
+		supplyChart.updatePieSeries("Not supplied", notSuppliedAmount);
+		supplyChart.updatePieSeries("No energy", noEnergyAmount);
+		panelHolonObject.updateToolTips();
+
+		// UPDATE PRIORITYS
+		PriorityCounts priorityCounts = decoratedGroupNode.getPriorityCounts();
+
+		priorityChart.updatePieSeries("Essential", priorityCounts.essential);
+		priorityChart.updatePieSeries("High", priorityCounts.high);
+		priorityChart.updatePieSeries("Medium", priorityCounts.medium);
+		priorityChart.updatePieSeries("Low", priorityCounts.low);
+		boolean hasPriority = priorityCounts.essential + priorityCounts.high + priorityCounts.medium
+				+ priorityCounts.low > 0;
+		priorityChart.updatePieSeries("No Data", hasPriority ? 0 : 1);
+		panelPriority.updateToolTips();
+
+		// UPDATE PRODUCTION
+		float production = decoratedGroupNode.getProductionFromSupplier();
+		float consumption = decoratedGroupNode.getConsumptionFromConsumer();
+		float difference = Math.abs(production - consumption);
+		energyChart.updatePieSeries("Production", production);
+		energyChart.updatePieSeries("Consumption", consumption);
+		differenceEnergyLabelAmount.setText(StringFormat.doubleFixedPlaces(1, difference));
+		panelEnergy.updateToolTips();
+
+		// UPDATE FLEXIBILITIES
+		int inUse = 0;
+		int offered = 0;
+		int onCooldown = 0;
+		int notOffered = 0;
+		int unavailable = 0;
+		FlexManager manager = control.getSimManager().getActualFlexManager();
+		Stream<FlexWrapper> flexWrapperStream = decoratedGroupNode.getFlexibilitiesStream()
+				.map(flex -> manager.getFlexWrapperFromFlexibility(flex));
+		List<FlexWrapper> wrapperList = flexWrapperStream.collect(Collectors.toList());
+		for (FlexWrapper wrapper : wrapperList) {
+			switch (wrapper.getState()) {
+			case IN_USE:
+				inUse++;
+				break;
+			case NOT_OFFERED:
+				notOffered++;
+				break;
+			case OFFERED:
+				offered++;
+				break;
+			case ON_COOLDOWN:
+				onCooldown++;
+				break;
+			case UNAVAILABLE:
+				unavailable++;
+				break;
+			default:
+				break;
+
+			}
+		}
+		flexibilityChart.updatePieSeries("Offered", offered);
+		flexibilityChart.updatePieSeries("In use", inUse);
+		flexibilityChart.updatePieSeries("On cooldown", onCooldown);
+		flexibilityChart.updatePieSeries("Not offered", notOffered);
+		flexibilityChart.updatePieSeries("Unavailable", unavailable);
+		boolean hasFlex = offered + inUse + onCooldown + notOffered + unavailable > 0;
+		flexibilityChart.updatePieSeries("No Data", hasFlex ? 0 : 1);
+		panelFlexibility.updateToolTips();
+
+		// UPDATE ActiveInActive
+		int activeAmount = decoratedGroupNode.getAmountOfAktiveElemntsFromHolonObjects();
+		int inactiveAmounts = decoratedGroupNode.getAmountOfElemntsFromHolonObjects() - activeAmount;
+		activeChart.updatePieSeries("Active", activeAmount);
+		activeChart.updatePieSeries("Inactive", inactiveAmounts);
+		panelActive.updateToolTips();
+
+		this.revalidate();
+		this.repaint();
+	}
+
+	private String getMultiSelectionName() {
+		String name =  control.getModel().getSelectedCpsObjects().stream().map(AbstractCanvasObject::getName)
+				.collect(Collectors.joining(", "));
+		if(name.length() > 25) {
+			name = name.substring(0, 25);
+			name += "...";
+		}
+		return name;
+	}
+
+
+	private DecoratedGroupNode multiSelectionToDecoratedGroupNode() {
+		// TODO Create DecoratedGroupNode
+		DecoratedGroupNode temp = new DecoratedGroupNode(new GroupNode("Temp"));
+
+		// TODO get consumer, supplier, passiv
+		// GroupNodes
+		HashMap<GroupNode, DecoratedGroupNode> accessMapGroupNode = control.getSimManager()
+				.getActualVisualRepresentationalState().getCreatedGroupNodes();
+		List<DecoratedGroupNode> groupNodeList = control.getModel().getSelectedCpsObjects().stream()
+				.filter(object -> object instanceof GroupNode).map(object -> accessMapGroupNode.get(object))
+				.collect(Collectors.toList());
+
+		temp.getGroupNodeList().addAll(groupNodeList);
+
+		// HolonObjects
+		HashMap<HolonObject, DecoratedHolonObject> accessMapHolonObject = control.getSimManager()
+				.getActualVisualRepresentationalState().createdHolonObjects;
+		List<DecoratedHolonObject> holonObjectList = control.getModel().getSelectedCpsObjects().stream()
+				.filter(object -> object instanceof HolonObject).map(object -> accessMapHolonObject.get(object))
+				.collect(Collectors.toList());
+
+		for (DecoratedHolonObject object : holonObjectList) {
+			switch (object.getState()) {
+			case NO_ENERGY:
+				temp.getPassivList().add((Passiv) object);
+				break;
+			case PRODUCER:
+				temp.getSupplierList().add((Supplier) object);
+				break;
+			default:
+				temp.getConsumerList().add((Consumer) object);
+				break;
+			}
+		}
+		return temp;
+	}
+
+	public HolonInformationPanel(Control control) {
+		control.OnSelectionUpdate.addListener(() -> updateCharts());
+		this.control = control;
+		this.setLayout(new BorderLayout());
+		initGraphPanel();
+		initTitlePanel();
+		this.setBackground(ColorPreference.Panel.Background);
+		this.add(titlePanel, BorderLayout.PAGE_START);
+		this.add(graphPanel, BorderLayout.CENTER);
+	}
+
+	public void initGraphPanel() {
+		graphPanel.setBackground(ColorPreference.Panel.Background);
+		panelHolonObject = new XChartPanel<PieChart>(supplyChart);
+		panelHolonObject.setBackground(ColorPreference.Panel.Background);
+		graphPanel.add(panelHolonObject);
+		panelPriority = new XChartPanel<PieChart>(priorityChart);
+		panelPriority.setBackground(ColorPreference.Panel.Background);
+		graphPanel.add(panelPriority);
+		panelFlexibility = new XChartPanel<PieChart>(flexibilityChart);
+		panelFlexibility.setBackground(ColorPreference.Panel.Background);
+		graphPanel.add(panelFlexibility);
+		Component panel = initEnergyChart();
+		graphPanel.add(panel);
+		panelActive = new XChartPanel<PieChart>(activeChart);
+		panelActive.setBackground(ColorPreference.Panel.Background);
+		panelActive.setLayout(new GridBagLayout());
+		graphPanel.add(panelActive);
+		graphPanel.setBorder(BorderFactory.createLineBorder(Color.lightGray));
+	}
+
+	private JLayeredPane initEnergyChart() {
+		JLayeredPane panel = new JLayeredPane();
+		JPanel panelMiddle = new JPanel(new GridBagLayout());
+		panelEnergy = new XChartPanel<PieChart>(energyChart);
+		panelEnergy.setBackground(ColorPreference.Panel.Background);
+		GridBagConstraints c = new GridBagConstraints();
+		c.gridx = 0;
+		c.gridy = 0;
+		c.insets = new Insets(15, 0, 0, 0); // top padding
+		JLabel difference = new JLabel("Difference:");
+		difference.setHorizontalAlignment(JLabel.CENTER);
+		difference.setAlignmentX(Component.CENTER_ALIGNMENT);
+		difference.setForeground(ColorPreference.Panel.Title);
+		difference.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 10));
+		panelMiddle.add(difference, c);
+		differenceEnergyLabelAmount = new JLabel("");
+		differenceEnergyLabelAmount.setHorizontalAlignment(JLabel.CENTER);
+		differenceEnergyLabelAmount.setForeground(Color.red);
+		differenceEnergyLabelAmount.setAlignmentX(Component.CENTER_ALIGNMENT);
+		differenceEnergyLabelAmount.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 12));
+		c.insets = new Insets(0, 0, 0, 0);
+		c.gridy = 1;
+		panelMiddle.add(differenceEnergyLabelAmount, c);
+		panel.setLayout(new OverlayLayout(panel));
+		panelEnergy.setOpaque(false);
+		panelMiddle.setOpaque(false);
+		panel.add(panelMiddle, Integer.valueOf(0));
+		panel.add(panelEnergy, Integer.valueOf(1));
+		return panel;
+	}
+
+	public void initTitlePanel() {
+		titleTextField = new JTextField("");
+		titleTextField.setFont(new Font("Arial", Font.BOLD, 24));
+		titleTextField.setForeground(ColorPreference.Panel.Title);
+		titleTextField.setBackground(ColorPreference.Panel.Background);
+		titleTextField.setBackground(null);
+		titleTextField.setBorder(null);
+		titlePanel.setBackground(ColorPreference.Panel.Background);
+		titlePanel.setBorder(new EmptyBorder(5, 5, 2, 0));
+		titlePanel.add(titleTextField, BorderLayout.CENTER);
+	}
+
+	public void setDefaultPieChartSettings(PieChart chart) {
+		PieStyler styler = chart.getStyler();
+		styler.setChartTitleVisible(true);
+		styler.setDefaultSeriesRenderStyle(PieSeriesRenderStyle.Donut);
+		styler.setLabelsFont(new java.awt.Font("Arial", java.awt.Font.PLAIN, 14));
+		styler.setLabelType(LabelType.Percentage);
+		styler.setLabelsFontColor(Color.black);
+		styler.setLabelsFontColorAutomaticEnabled(false);
+		styler.setLabelsDistance(0.8);
+		styler.setChartFontColor(ColorPreference.Panel.Title);
+		styler.setToolTipsEnabled(true);
+		styler.setPlotContentSize(0.9);
+		styler.setPlotBackgroundColor(ColorPreference.Panel.Transparent);
+		styler.setPlotBorderColor(ColorPreference.Panel.Transparent);
+		styler.setLegendVisible(false);
+		styler.setChartBackgroundColor(ColorPreference.Panel.Transparent);
+	}
+
+	public PieChart createSupplyStateChart() {
+		PieChart chart = new PieChartBuilder().width(defaultWidth).height(defaultHeight).title("Holon Objects").build();
+		setDefaultPieChartSettings(chart);
+		Color[] sliceColors = new Color[] { ColorPreference.HolonObject.Producer,
+				ColorPreference.HolonObject.OverSupplied, ColorPreference.HolonObject.Supplied,
+				ColorPreference.HolonObject.PartiallySupplied, ColorPreference.HolonObject.NotSupplied,
+				ColorPreference.HolonObject.NoEnergy };
+		chart.getStyler().setSeriesColors(sliceColors);
+
+		// Series
+		chart.addSeries("Producer", 0);
+		chart.addSeries("Over supplied", 0);
+		chart.addSeries("Supplied", 0);
+		chart.addSeries("Partial supplied", 0);
+		chart.addSeries("Not supplied", 0);
+		chart.addSeries("No energy", 0);
+		return chart;
+	}
+
+	public PieChart createPriorityChart() {
+		// Create Chart
+		PieChart chart = new PieChartBuilder().width(defaultWidth).height(defaultHeight).title("Priotities").build();
+		setDefaultPieChartSettings(chart);
+		// Customize Chart
+		Color[] sliceColors = new Color[] { ColorPreference.Element.Priority.Essential,
+				ColorPreference.Element.Priority.High, ColorPreference.Element.Priority.Medium,
+				ColorPreference.Element.Priority.Low, ColorPreference.Element.Priority.NoData };
+		chart.getStyler().setSeriesColors(sliceColors);
+		// Series
+		chart.addSeries("Essential", 0);
+		chart.addSeries("High", 0);
+		chart.addSeries("Medium", 0);
+		chart.addSeries("Low", 0);
+		chart.addSeries("No Data", 0);
+		return chart;
+	}
+
+	public PieChart createFlexibilityChart() {
+		// IN_USE, ON_COOLDOWN, OFFERED, NOT_OFFERED, UNAVAILABLE
+		// Create Chart
+		PieChart chart = new PieChartBuilder().width(defaultWidth).height(defaultHeight).title("Flexibilities").build();
+		setDefaultPieChartSettings(chart);
+		// Customize Chart
+		Color[] sliceColors = new Color[] { ColorPreference.Flexibility.Offered, ColorPreference.Flexibility.InUse,
+				ColorPreference.Flexibility.OnCooldown, ColorPreference.Flexibility.NotOffered,
+				ColorPreference.Flexibility.Unavailable, ColorPreference.Element.Priority.NoData };
+		chart.getStyler().setSeriesColors(sliceColors);
+		// Series
+		chart.addSeries("Offered", 0);
+		chart.addSeries("In use", 0);
+		chart.addSeries("On cooldown", 0);
+		chart.addSeries("Not offered", 0);
+		chart.addSeries("Unavailable", 0);
+		chart.addSeries("No Data", 0);
+		return chart;
+	}
+
+	public PieChart createProductionChart() {
+		// Create Chart
+		PieChart chart = new PieChartBuilder().width(defaultWidth).height(defaultHeight)
+				.title("Production vs. Consumption").build();
+		setDefaultPieChartSettings(chart);
+
+		// Customize Chart
+		// Customize Chart
+		Color[] barColors = new Color[] { ColorPreference.Energy.Production, ColorPreference.Energy.Consumption };
+		chart.getStyler().setSeriesColors(barColors);
+		// Series
+		chart.addSeries("Production", 0);
+		chart.addSeries("Consumption", 0);
+		return chart;
+	}
+
+	public PieChart createActiveChart() {
+		// Create Chart
+		PieChart chart = new PieChartBuilder().width(defaultWidth).height(defaultHeight).title("Active").build();
+		setDefaultPieChartSettings(chart);
+		// Customize Chart
+		// Customize Chart
+		Color[] barColors = new Color[] { ColorPreference.Element.Active, ColorPreference.Element.Inactive };
+		chart.getStyler().setSeriesColors(barColors);
+		// Series
+		chart.addSeries("Active", 0);
+		chart.addSeries("Inactive", 0);
+		return chart;
+	}
+}

+ 16 - 16
src/ui/view/MyCanvas.java

@@ -33,6 +33,7 @@ import classes.HolonObject;
 import classes.HolonSwitch;
 import classes.Node;
 import classes.Position;
+import preferences.ColorPreference;
 import ui.controller.Control;
 import ui.controller.UpdateController;
 import ui.model.Consumer;
@@ -43,11 +44,11 @@ import ui.model.DecoratedHolonObject.HolonObjectState;
 import ui.model.DecoratedSwitch;
 import ui.model.ExitCable;
 import ui.model.DecoratedSwitch.SwitchState;
+import util.ImageImport;
 import ui.model.Model;
 import ui.model.Passiv;
 import ui.model.Supplier;
 import ui.model.VisualRepresentationalState;
-import utility.ImageImport;
 
 /**
  * This Class is the Canvas. All Objects will be visualized here
@@ -144,7 +145,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 						controller.addUpperNode("GroupNode", null, animCps);
 						controller.calculateStateAndVisualForCurrentTimeStep();
 						triggerUpdateController();
-						model.getSelectedCpsObjects().clear();
+						controller.clearSelection();
 						repaint();
 					}
 				});
@@ -177,7 +178,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 					animT = new javax.swing.Timer(
 							animDelay,
 							actionEvent1 -> {
-								model.getSelectedCpsObjects().clear();
+								controller.clearSelection();
 								if (animDuration - animDelay >= 0) {
 									for (int i = 0; i < animCps.size(); i++) {
 										Position pos = animCps.get(i).getPosition();
@@ -249,7 +250,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 				}
 				toolTip = false;
 			}
-			model.getSelectedCpsObjects().clear();
+			controller.clearSelection();
 			tempCps = null;
 			repaint();
 		});
@@ -307,20 +308,20 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 	 *            Graphics
 	 */
 	
-	private Color getStateColor(HolonObjectState state) {
+	public static Color getStateColor(HolonObjectState state) {
 		switch(state) {
 		case NOT_SUPPLIED:
-			return new Color(230, 120, 100);
+			return ColorPreference.HolonObject.NotSupplied;
 		case NO_ENERGY:
-			return Color.white;
+			return ColorPreference.HolonObject.NoEnergy;
 		case OVER_SUPPLIED:
-			return new Color(166, 78, 229);
+			return ColorPreference.HolonObject.OverSupplied;
 		case PARTIALLY_SUPPLIED:
-			return Color.yellow;
+			return ColorPreference.HolonObject.PartiallySupplied;
 		case PRODUCER:
-			return Color.lightGray;
+			return ColorPreference.HolonObject.Producer;
 		case SUPPLIED:
-			return new Color(13, 175, 28);
+			return ColorPreference.HolonObject.Supplied;
 		default:
 			return Color.BLACK;
 		}
@@ -640,7 +641,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 
 				if (e.isControlDown() && tempCps != null) {
 					if (model.getSelectedCpsObjects().contains(tempCps)) {
-						controller.deleteSelectedObject(tempCps);
+						controller.removeSelectedObjectFromSelection(tempCps);
 							//TODO: RemoveDepth
 					} else {
 						controller.addSelectedObject(tempCps);
@@ -668,7 +669,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 			controller.setSelecteEdge(edgeHighlight);
 			controller.setSelectedObjectID(0);
 			if (!e.isControlDown() && e.getButton() != MouseEvent.BUTTON3) {
-				model.getSelectedCpsObjects().clear();
+				controller.clearSelection();
 			}
 		}
 
@@ -727,9 +728,8 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 
 		if (!e.isControlDown() && !dragged && tempCps != null
 				&& MouseEvent.BUTTON3 != e.getButton()) {
-			model.getSelectedCpsObjects().clear();
+			controller.clearSelection();
 			controller.addSelectedObject(tempCps);
-			model.setSelectedCpsObject(tempCps);
 			if(tempCps instanceof GroupNode)
 				controller.getObjectsInDepth();
 		}
@@ -762,7 +762,7 @@ public class MyCanvas extends AbstractCanvas implements MouseListener,
 		y = e.getY();
 		
 		if (!model.getSelectedCpsObjects().contains(tempCps) && !doMark) {
-			model.getSelectedCpsObjects().clear();
+			controller.clearSelection();
 			if (tempCps != null) {
 				controller.addSelectedObject(tempCps);
 			}

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

@@ -34,7 +34,7 @@ import javax.swing.event.ChangeListener;
 import javax.swing.plaf.basic.BasicSliderUI;
 
 import ui.controller.Control;
-import utility.ImageImport;
+import util.ImageImport;
 /**
  * This Class represents a Panel where the User can start and stop the
  * Simulation. He Can also reset the Simulation and click through every

+ 1 - 0
src/ui/view/outliner/Outliner.java

@@ -14,6 +14,7 @@ import ui.controller.Control;
 import ui.model.Consumer;
 import ui.model.DecoratedCable;
 import ui.model.DecoratedHolonObject.HolonObjectState;
+import util.ImageImport;
 import ui.model.DecoratedNetwork;
 import ui.model.DecoratedState;
 import ui.model.DecoratedSwitch;

+ 4 - 1
src/utility/Action.java → src/util/Action.java

@@ -1,4 +1,4 @@
-package utility;
+package util;
 
 import java.util.HashSet;
 import java.util.Set;
@@ -10,6 +10,9 @@ public class Action<T> {
     public void addListener(Consumer<T> listener) {
         listeners.add(listener);
     }
+    public void removeListener(Consumer<T> listener) {
+        listeners.remove(listener);
+    }
 
     public void broadcast(T argument) {
         listeners.forEach(x -> x.accept(argument));

+ 4 - 1
src/utility/Event.java → src/util/Event.java

@@ -1,4 +1,4 @@
-package utility;
+package util;
 import java.util.HashSet;
 import java.util.Set;
 
@@ -7,6 +7,9 @@ public class Event {
     public void addListener(Runnable listener) {
         listeners.add(listener);
     }
+    public void removeListener(Runnable listener) {
+        listeners.remove(listener);
+    }
 
     public void broadcast() {
         listeners.forEach(x -> x.run());

+ 1 - 1
src/utility/FloatLog.java → src/util/FloatLog.java

@@ -1,4 +1,4 @@
-package utility;
+package util;
 
 import java.util.HashMap;
 import java.util.stream.Collectors;

+ 127 - 127
src/utility/ImageImport.java → src/util/ImageImport.java

@@ -1,128 +1,128 @@
-package utility;
-
-import java.awt.Image;
-import java.awt.image.BufferedImage;
-import java.awt.image.ColorModel;
-import java.awt.image.WritableRaster;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.HashMap;
-import javax.imageio.ImageIO;
-
-/**
- * 
- * @author TU-Darmstadt BP Gruppe 7 WS17/18 Centralized resource loading methods
- *         for improved performance and easier troubleshooting.
- */
-public class ImageImport {
-	/*
-	 * Save nothing: Reload every image whenever requested. Save external: Only save
-	 * 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 ImageImport xmp = new ImageImport();// Used to load resources from the JAR.
-
-	static {
-		imgStorage = new HashMap<String, Image>();
-	}
-
-	/**
-	 * The rawest function replacing the old method without any default parameters.
-	 * Currently not used in HOLEG at all(aside form calls from the convenience
-	 * methods).
-	 * 
-	 * @param url   Path to the image to be loaded.
-	 * @param w     Width the loaded image should be scaled to.
-	 * @param h     Height the loaded image should be scaled to.
-	 * @param hints Hints for the scaling algorithm to be used. Same as the
-	 *              parameter in the getScaledInstance function of Image.
-	 * @return A loaded and scaled image from the requested path.
-	 */
-	static Image loadImage(String url, int w, int h, int hints) {
-		String key = url + "?" + w + "?" + h + "?" + hints;
-		if (imgStorage.containsKey(key))
-			return (imgStorage.get(key));
-		else {
-			Image img = loadImage(url).getScaledInstance(w, h, hints);
-			imgStorage.put(key, img);
-			return img;
-		}
-	}
-
-	/**
-	 * Loads an image from the given path and scales it using the smooth algorithm.
-	 * 
-	 * @param url Path to the image to be loaded.
-	 * @param w   Width the loaded image should be scaled to.
-	 * @param h   Height the loaded image should be scaled to.
-	 * @return A loaded and (smoothly) scaled image from the requested path.
-	 */
-	public static Image loadImage(String url, int w, int h) {
-		return loadImage(url, w, h, Image.SCALE_SMOOTH);
-	}
-
-	/**
-	 * Loads an image from the given path and scales it using the smooth algorithm.
-	 * 
-	 * @param url Path to the image to be loaded.
-	 * @param w   Width the loaded image should be scaled to.
-	 * @param h   Height the loaded image should be scaled to.
-	 * @return An image loaded from the requested path.
-	 */
-	public static Image loadImage(String url) {
-		if (imgStorage.containsKey(url))
-			return imgStorage.get(url);
-		else {
-			Image img;
-			try {
-				img = ImageIO.read(loadStream(url));
-			} catch (IOException e) {
-				System.err.println(e);
-				return null;
-			}
-			imgStorage.put(url, img);
-			return img;
-		}
-	}
-
-	/**
-	 * Loads any resource with a given path, regardless of whether it is inside the
-	 * jar or an external resource. Every loadImage() function uses this as a basis.
-	 * 
-	 * @param url The path (and file name) of the requested resource.
-	 * @return An InputStream from the requested resource.
-	 * @throws FileNotFoundException
-	 */
-	public static InputStream loadStream(String url) throws FileNotFoundException {
-		InputStream o = xmp.getClass().getResourceAsStream(url);
-		if (o != null)
-			return o;
-		else {
-			boolean rootSymbol = false; // Whether url starts with a / or \
-			switch (url.charAt(0)) { // So we can make sure to construct res/path correctly.
-			case '/':
-			case '\\':
-				rootSymbol = true;
-			}
-			File f = new File(url);
-			if (!f.exists()) {
-				url = "res" + (rootSymbol ? "" : "/") + url;
-			}
-			f = new File(url);// Possible bug with duplicate names.
-			if (!f.exists()) {
-				url = "res/Images/image_not_found.png";
-			}
-			return new FileInputStream(url);
-
-		}
-	}
-
-	// Nobody needs an instance of this. I do, because I use it to load images from
-	// inside the JAR.
-	private ImageImport() {
-	}
+package util;
+
+import java.awt.Image;
+import java.awt.image.BufferedImage;
+import java.awt.image.ColorModel;
+import java.awt.image.WritableRaster;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import javax.imageio.ImageIO;
+
+/**
+ * 
+ * @author TU-Darmstadt BP Gruppe 7 WS17/18 Centralized resource loading methods
+ *         for improved performance and easier troubleshooting.
+ */
+public class ImageImport {
+	/*
+	 * Save nothing: Reload every image whenever requested. Save external: Only save
+	 * 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 ImageImport xmp = new ImageImport();// Used to load resources from the JAR.
+
+	static {
+		imgStorage = new HashMap<String, Image>();
+	}
+
+	/**
+	 * The rawest function replacing the old method without any default parameters.
+	 * Currently not used in HOLEG at all(aside form calls from the convenience
+	 * methods).
+	 * 
+	 * @param url   Path to the image to be loaded.
+	 * @param w     Width the loaded image should be scaled to.
+	 * @param h     Height the loaded image should be scaled to.
+	 * @param hints Hints for the scaling algorithm to be used. Same as the
+	 *              parameter in the getScaledInstance function of Image.
+	 * @return A loaded and scaled image from the requested path.
+	 */
+	static Image loadImage(String url, int w, int h, int hints) {
+		String key = url + "?" + w + "?" + h + "?" + hints;
+		if (imgStorage.containsKey(key))
+			return (imgStorage.get(key));
+		else {
+			Image img = loadImage(url).getScaledInstance(w, h, hints);
+			imgStorage.put(key, img);
+			return img;
+		}
+	}
+
+	/**
+	 * Loads an image from the given path and scales it using the smooth algorithm.
+	 * 
+	 * @param url Path to the image to be loaded.
+	 * @param w   Width the loaded image should be scaled to.
+	 * @param h   Height the loaded image should be scaled to.
+	 * @return A loaded and (smoothly) scaled image from the requested path.
+	 */
+	public static Image loadImage(String url, int w, int h) {
+		return loadImage(url, w, h, Image.SCALE_SMOOTH);
+	}
+
+	/**
+	 * Loads an image from the given path and scales it using the smooth algorithm.
+	 * 
+	 * @param url Path to the image to be loaded.
+	 * @param w   Width the loaded image should be scaled to.
+	 * @param h   Height the loaded image should be scaled to.
+	 * @return An image loaded from the requested path.
+	 */
+	public static Image loadImage(String url) {
+		if (imgStorage.containsKey(url))
+			return imgStorage.get(url);
+		else {
+			Image img;
+			try {
+				img = ImageIO.read(loadStream(url));
+			} catch (IOException e) {
+				System.err.println(e);
+				return null;
+			}
+			imgStorage.put(url, img);
+			return img;
+		}
+	}
+
+	/**
+	 * Loads any resource with a given path, regardless of whether it is inside the
+	 * jar or an external resource. Every loadImage() function uses this as a basis.
+	 * 
+	 * @param url The path (and file name) of the requested resource.
+	 * @return An InputStream from the requested resource.
+	 * @throws FileNotFoundException
+	 */
+	public static InputStream loadStream(String url) throws FileNotFoundException {
+		InputStream o = xmp.getClass().getResourceAsStream(url);
+		if (o != null)
+			return o;
+		else {
+			boolean rootSymbol = false; // Whether url starts with a / or \
+			switch (url.charAt(0)) { // So we can make sure to construct res/path correctly.
+			case '/':
+			case '\\':
+				rootSymbol = true;
+			}
+			File f = new File(url);
+			if (!f.exists()) {
+				url = "res" + (rootSymbol ? "" : "/") + url;
+			}
+			f = new File(url);// Possible bug with duplicate names.
+			if (!f.exists()) {
+				url = "res/Images/image_not_found.png";
+			}
+			return new FileInputStream(url);
+
+		}
+	}
+
+	// Nobody needs an instance of this. I do, because I use it to load images from
+	// inside the JAR.
+	private ImageImport() {
+	}
 }

+ 1 - 1
src/utility/Random.java → src/util/Random.java

@@ -1,4 +1,4 @@
-package utility;
+package util;
 
 
 

+ 1 - 1
src/utility/StringFormat.java → src/util/StringFormat.java

@@ -1,4 +1,4 @@
-package utility;
+package util;
 
 import java.math.RoundingMode;
 import java.text.DecimalFormat;

+ 2 - 2
tests/tests/PraktikumHolonsTestObjectController.java

@@ -125,13 +125,13 @@ public class PraktikumHolonsTestObjectController {
 
 		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
 			int size = model.getSelectedCpsObjects().size();
-			controller.addSelectedObject(cps);
+			controller.addSelectedObjectToSelection(cps);
 			assertTrue("Size does not Match", model.getSelectedCpsObjects().size() == size + 1);
 		}
 		for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
 			System.out.println(model.getSelectedCpsObjects().size());
 			int size = model.getSelectedCpsObjects().size();
-			controller.deleteSelectedObject(cps);
+			controller.removeSelectedObjectFromSelection(cps);
 			assertTrue("Size does not Match", model.getSelectedCpsObjects().size() == size - 1);
 			assertTrue("Object was not unselected", !model.getSelectedCpsObjects().contains(cps));