GUI.java 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221
  1. package ui.view;
  2. import classes.*;
  3. import com.google.gson.JsonNull;
  4. import com.google.gson.JsonObject;
  5. import com.google.gson.JsonParseException;
  6. import interfaces.CategoryListener;
  7. import interfaces.GraphEditable;
  8. import interfaces.LocalMode;
  9. import org.apache.commons.compress.archivers.ArchiveException;
  10. import ui.controller.Control;
  11. import ui.controller.SimulationManager;
  12. import ui.controller.UpdateController;
  13. import ui.model.DecoratedState;
  14. import ui.model.Model;
  15. import ui.model.Model.FairnessModel;
  16. import ui.view.NewPopUp.Option;
  17. import utility.Util;
  18. import javax.swing.*;
  19. import javax.swing.border.Border;
  20. import javax.swing.border.LineBorder;
  21. import javax.swing.event.AncestorEvent;
  22. import javax.swing.event.AncestorListener;
  23. import javax.swing.filechooser.FileNameExtensionFilter;
  24. import javax.swing.plaf.ColorUIResource;
  25. import javax.swing.table.DefaultTableModel;
  26. import javax.swing.table.JTableHeader;
  27. import javax.swing.table.TableCellEditor;
  28. import javax.swing.table.TableCellRenderer;
  29. import javax.swing.tree.DefaultMutableTreeNode;
  30. import javax.swing.tree.DefaultTreeModel;
  31. import javax.swing.tree.TreeCellRenderer;
  32. import java.awt.*;
  33. import java.awt.datatransfer.UnsupportedFlavorException;
  34. import java.awt.event.*;
  35. import java.io.File;
  36. import java.io.IOException;
  37. import java.net.URI;
  38. import java.net.URISyntaxException;
  39. import java.util.ArrayList;
  40. import java.util.Collections;
  41. import java.util.List;
  42. import java.util.ListIterator;
  43. import java.util.Objects;
  44. import java.util.Timer;
  45. import java.util.TimerTask;
  46. import java.util.stream.Collectors;
  47. /**
  48. * Graphical User Interface.
  49. *
  50. * @author Gruppe14
  51. */
  52. public class GUI implements CategoryListener {
  53. static final Color PALE_RED=new Color(255, 192, 192);
  54. /**
  55. * Menu on the Top containing File, Edit View Help etc
  56. */
  57. private final JMenuBar menuBar = new JMenuBar();
  58. private final JMenu mnNewMenu = new JMenu("File");
  59. private final JMenu mnNewMenuEdit = new JMenu("Edit");
  60. private final JMenu mnNewMenuOptions = new JMenu("Options");
  61. private final JMenu mnNewMenuView = new JMenu("View");
  62. private final JMenu menuWindow = new JMenu("Window");
  63. /** Help Menu containing helpful Informations and the AboutUs Popup */
  64. private final JMenu mnHelp = new JMenu("Help");
  65. /**
  66. * Help -> Introduction
  67. * A small Introduction of the Application, SmartGrids and Holons
  68. */
  69. private final JMenuItem mntmIntroduction = new JMenuItem("Introduction");
  70. /**
  71. * Help -> UserManual
  72. */
  73. private final JMenuItem mntmUserManual = new JMenuItem("User Manual");
  74. /** Help -> Algorithm Help Menu */
  75. private final JMenuItem mntmAlgorithmHelp = new JMenuItem("Algorithm Introduction");
  76. /** Help -> CodeDocumentation */
  77. private final JMenuItem mntmCodeDoc = new JMenuItem("Code Documentation");
  78. /** Help -> AboutUs */
  79. private final JMenuItem mntmAboutUs = new JMenuItem("About Us");
  80. private final JCheckBoxMenuItem consoleLogCheckBox = new JCheckBoxMenuItem(
  81. "Show program console log");
  82. private final JCheckBoxMenuItem useFlexibleDevicesCheckBox = new JCheckBoxMenuItem(
  83. "Automatically use flexible devices");
  84. /** checked if supplyBars should be shown */
  85. private final JCheckBoxMenuItem showSupplyBarsCheckBox = new JCheckBoxMenuItem(
  86. "Show supply bars.");
  87. private final JCheckBoxMenuItem showTooltipsCheckBox = new JCheckBoxMenuItem(
  88. "Show tooltips.");
  89. /** menu for the different fairness Models */
  90. private final JMenu mnFairnessModel = new JMenu("Fairness Model");
  91. /** press to supply minimum demand first */
  92. private final JMenuItem mntmFairMinFirst = new JMenuItem(
  93. "Minimum demand first");
  94. /** press to give everyone the same energy */
  95. private final JMenuItem mntmFairAlleEqual = new JMenuItem(
  96. "Equal supply for everyone");
  97. private final JMenuItem mntmOpen = new JMenuItem("Open");
  98. private final JMenuItem mntmNew = new JMenuItem("New");
  99. private final JMenuItem mntmSave = new JMenuItem("Save");
  100. private final JMenuItem mntmCanvasSize = new JMenuItem("Set View Size");
  101. private final JMenuItem mntmBackground = new JMenuItem("Background Image");
  102. private final JMenuItem mntmSplitView = new JMenuItem("Split View");
  103. private final JSplitPane splitPane = new JSplitPane();
  104. private final JSplitPane splitPane1 = new JSplitPane();
  105. // the tabbed canvas containing the different sub-net tabs of the grid (Main
  106. // Grid + Nodes of Nodes)
  107. private final JLabel lblHint = new JLabel("To connect two Objects use SHIFT + Left Mouse Button");
  108. private final JPanel myPanel = new JPanel(new BorderLayout());
  109. private final JTabbedPane tabbedPaneInnerOriginal = new JTabbedPane(
  110. JTabbedPane.TOP);
  111. // the main canvas where we can see the grid currently displayed
  112. private final JScrollPane canvasSP = new JScrollPane();
  113. private final JScrollPane scrollPane1 = new JScrollPane();
  114. // private final JScrollPane holonSP = new JScrollPane();
  115. // the original tabbed Pane (containing tabs for view, statistics, holon,
  116. // flexibility)
  117. private final JTabbedPane tabbedPaneOriginal = new JTabbedPane(
  118. JTabbedPane.TOP);
  119. // the same tabbed Pane that appears once the view is split
  120. private final JTabbedPane tabbedPaneSplit = new JTabbedPane(JTabbedPane.TOP);
  121. private final JPopupMenu popmenuEdit = new JPopupMenu();
  122. private final JMenuItem editItem = new JMenuItem("Edit Object");
  123. private final StatisticPanel statSplitPane;
  124. private final JScrollPane statScrollPane;
  125. private final JLabel maxGraph = new JLabel("100%");
  126. private final JLabel medGraph = new JLabel("50%");
  127. private final JLabel minGraph = new JLabel("0%");
  128. private final JLabel elementGraph = new JLabel("None ");
  129. private final ArrayList<HolonElement> selectedElements = new ArrayList<>();
  130. private final JTree tree = new JTree();
  131. /******************************************
  132. ************* Right Container*************
  133. ******************************************
  134. * Right Container: here comes the information about the HolonObject, such
  135. * as HolonElements Information, Properties and Consumption/Production
  136. * graph.
  137. **/
  138. private final JSplitPane splitHolonElPro = new JSplitPane(
  139. JSplitPane.VERTICAL_SPLIT);
  140. private final JSplitPane splitGraphHolonEl = new JSplitPane(
  141. JSplitPane.VERTICAL_SPLIT);
  142. private final int distanceBetweenElementsAndGraph = 350;
  143. // Model for single or multi selection
  144. private final JPanel scrollElements = new JPanel();
  145. private final JScrollPane tableHolonElementScrollPane = new JScrollPane();
  146. // In this section are all the properties that correspond to the clicked
  147. // HolonObject, such as connections, name, Type, etc.
  148. // Table for Properties --> Cell with (0,1) is editable by CpsObjt and
  149. // Cell(3,1) is editable by Edges
  150. private final JTable tableProperties = new JTable() {
  151. private static final long serialVersionUID = 1L;
  152. @Override
  153. public TableCellRenderer getCellRenderer(int row, int column) {
  154. if (getValueAt(row, column) instanceof Boolean) {
  155. return super.getDefaultRenderer(Boolean.class);
  156. } else {
  157. return super.getCellRenderer(row, column);
  158. }
  159. }
  160. @Override
  161. public TableCellEditor getCellEditor(int row, int column) {
  162. if (getValueAt(row, column) instanceof Boolean) {
  163. return super.getDefaultEditor(Boolean.class);
  164. } else {
  165. return super.getCellEditor(row, column);
  166. }
  167. }
  168. };
  169. //Prechoosed local Periods
  170. private String[] comboContext = {
  171. "", "5", "10", "20" ,"100", "1000"
  172. };
  173. private JComboBox<String> localPeriodInput = new JComboBox<String>(comboContext);
  174. JButton resetButton = new JButton("", new ImageIcon(Util.loadImage("/Images/resetIcon3.png")));
  175. ImageIcon localPeriodButtonImage = new ImageIcon(GrayFilter.createDisabledImage(Util.loadImage("/Images/Graph.png")));
  176. private JButton localPeriodButton = new JButton("", localPeriodButtonImage);
  177. private final JPanel graphLabel = new JPanel();
  178. private final JScrollPane scrollProperties = new JScrollPane();
  179. // In this section is the graph for the selected HolonElement of the clicked
  180. // HolonObject
  181. private final JTable tableGraph = new JTable();
  182. private final DefaultTableModel tableModelGraph = new DefaultTableModel();
  183. private final JScrollPane scrollGraph = new JScrollPane();
  184. private final Model model;
  185. private final Control controller;
  186. // In this section are all the Holonelements that correspond to the clicked
  187. // HolonObject with consumption/production, name and amount.
  188. private final JPanel panel = new JPanel();
  189. private final JPanel panelHolonEl = new JPanel();
  190. // Buttons
  191. private final JButton btnAdd = new JButton("New");
  192. private final JPopupMenu btnAddPopUp = new JPopupMenu("New");
  193. private final JMenuItem mItemNew = new JMenuItem("New..");
  194. private final JMenuItem mItemCategory = new JMenuItem("Category");
  195. private final JMenuItem mItemObject = new JMenuItem("Object");
  196. private final JMenuItem mItemSwitch = new JMenuItem("Switch");
  197. private final JMenuItem mItemBattery = new JMenuItem("Battery");
  198. private final JButton btnDel = new JButton("Delete");
  199. private final JButton btnAddHolEL = new JButton("New Element");
  200. private final JButton btnDelHolEL = new JButton("Delete Element");
  201. private final JButton resetGraphBtn = new JButton("Reset");
  202. private final JToolBar toolBar = new JToolBar();
  203. private final JToolBar toolBarHolonEl = new JToolBar();
  204. private final JToolBar toolBarGraph = new JToolBar();
  205. // Languages
  206. private final JMenuItem englishBtn = new JMenuItem("EN");
  207. private final JMenuItem spanishBtn = new JMenuItem("ES");
  208. private final JMenuItem germanBtn = new JMenuItem("DE");
  209. private final JMenuItem czechBtn = new JMenuItem("CZ");
  210. private final JMenuItem chineseBtn = new JMenuItem("ZH");
  211. private final MyCanvas canvas;
  212. private final HolonCanvas holonCanvas;
  213. private final UnitGraph unitGraph;
  214. /** Textfield to show the period of an element */
  215. private final JTextField unitGraphLocalPeriod = new JTextField(6);
  216. private final JSplitPane splitPane3 = new JSplitPane();
  217. private final JSlider sizeSlider = new JSlider();
  218. private final JLabel lblImageSize = new JLabel(Languages.getLanguage()[94]);
  219. private final JMenuItem mntmUndo = new JMenuItem("Undo");
  220. private final JMenuItem mntmRedo = new JMenuItem("Redo");
  221. private final JMenuItem mntmEditEdges = new JMenuItem("Edge Properties");
  222. private final JMenuItem mntmFindReplace = new JMenuItem("Find/ Replace");
  223. private final JMenuItem mntmAlignAll = new JMenuItem("Align All");
  224. private final JMenuItem mntmEditShowedInformation = new JMenuItem(
  225. "Edit showed Information");
  226. private final JMenuItem mntmResetCategory = new JMenuItem(
  227. "Reset Categories");
  228. private final JMenu mnLanguage = new JMenu("Language");
  229. private final String[] columnNamesMulti = { "Object", "Nr.", "Device",
  230. "Energy", "Flexibility active", "Quantity", "Activated" };
  231. private final String[] columnNamesSingle = { "Nr.", "Device", "Energy",
  232. "Flexibility active", "Quantity", "Activated" };
  233. private final ArrayList<PropertyTable> tables = new ArrayList<>();
  234. private final String[] comboBoxCat = { "Category", "Object", "Switch", "Battery" };
  235. private final UpdateController updCon;
  236. private final JSplitPane splitPane_1 = new JSplitPane();
  237. private final JSlider holonBodySizeSlider = new JSlider();
  238. private final JLabel lblHolonBodySize = new JLabel("HolonBody SIze");
  239. private final JLabel lblSelectedElement = new JLabel("Selected Element: ");
  240. // for doubleclick
  241. private boolean click = false;
  242. private JFrame holegJFrame;
  243. private JTabbedPane tabTemp; // tabbedPaneOriginal or tabbedPaneSplit
  244. private JSplitPane tempSplit;
  245. private boolean initSplit = true;
  246. private String catOfObjToBeEdited;
  247. private GroupNodeCanvas unc;
  248. private JPanel contentPane;
  249. private String holonEleNamesDisplayed = "None ";
  250. // Pop up Windows
  251. private AddObjectPopUp addObjectPopUP;
  252. private AboutUsPopUp aboutUsPopUp;
  253. private AddElementPopUp addElementPopUp;
  254. // variables
  255. private boolean dragging = false;
  256. private String actualObjectClicked;
  257. private Image img = null;
  258. private AbstractCanvasObject tempCps = null;
  259. private int yValueElements = 0;
  260. // Time Stuff
  261. private TimePanel timePanel;
  262. public TimePanel getTimePanel() {
  263. return timePanel;
  264. }
  265. // Coord for all Cells with text
  266. private int yThis;
  267. private int xThis;
  268. // Coord for all Cells with boolean values (checkbox)
  269. private int yBTis;
  270. private int xBThis;
  271. // Coord for the Edit-Modus in the PropertieTable
  272. private int yProThis;
  273. private int xProThis;
  274. private int yProThisOneClick;
  275. private int xProThisOneClick;
  276. private AbstractCanvasObject temp = null;
  277. private String warningText = "Warning";
  278. private String saveBeforeNew = "Do you want to save your current data?";
  279. private String eraseCategory = "Do you really want to delete the Category ";
  280. private String selectObjBeforeErase = "Please select a Category or an Object in the left library in order to delete something.";
  281. private List<Outliner> outlinerList = new ArrayList<Outliner>();
  282. private List<FlexWindow> flexList = new ArrayList<FlexWindow>();
  283. private JMenuItem removeItem = new JMenuItem("Remove");
  284. /**
  285. * Create the application.
  286. *
  287. * @param control
  288. * the Controller
  289. */
  290. GUI(Control control) {
  291. this.controller = control;
  292. this.model = control.getModel();
  293. control.setGui(this);
  294. statSplitPane = new StatisticPanel(controller);
  295. model.addGraphListener(statSplitPane);
  296. model.setStatPanel(statSplitPane);
  297. statScrollPane = new JScrollPane(statSplitPane);
  298. this.unitGraph = new UnitGraph(model, control);
  299. this.canvas = new MyCanvas(model, control, unitGraph);
  300. this.holonCanvas = new HolonCanvas(model, control);
  301. control.initListener(this);
  302. model.setTableProperties(tableProperties);
  303. initialize();
  304. updateCategories(model.getCategories());
  305. updCon = new UpdateController(model, controller);
  306. }
  307. /**
  308. * Initialize the contents of the frame.
  309. */
  310. @SuppressWarnings({ "serial", "unchecked" })
  311. private void initialize() {
  312. holegJFrame = new JFrame();
  313. holegJFrame.setTitle("HOLEG Simulator");
  314. // try to restore old position/dimensions
  315. ArrayList<Integer> savedWindowDim = controller
  316. .loadSavedWindowDimensionsIfExistent();
  317. if (savedWindowDim.size() == 4) {
  318. holegJFrame.setBounds(savedWindowDim.get(0),
  319. savedWindowDim.get(1), savedWindowDim.get(2),
  320. savedWindowDim.get(3));
  321. }
  322. // if the upper part of the window is showing, the windows can still be
  323. // moved,
  324. // but if it is not, we need to move it to somewhere else
  325. if (savedWindowDim.size() != 4 || !isUpperPanelInsideBounds()) {
  326. holegJFrame.setBounds(100, 100, 1000, 800);
  327. holegJFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
  328. }
  329. holegJFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  330. holegJFrame.addWindowListener(new java.awt.event.WindowAdapter() {
  331. @Override
  332. public void windowClosing(java.awt.event.WindowEvent windowEvent) {
  333. if (JOptionPane.showConfirmDialog(holegJFrame,
  334. Languages.getLanguage()[88],
  335. "HOLEG",
  336. JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) {
  337. controller.deleteDirectory(new File(System
  338. .getProperty("user.home")
  339. + "/.config/HolonGUI/Autosave"));
  340. // try to save the position and size of the window, such
  341. // that (if possible)
  342. // it can be opened in the same position the next time
  343. try {
  344. controller.savePosAndSizeOfWindow(
  345. holegJFrame.getX(),
  346. holegJFrame.getY(),
  347. holegJFrame.getWidth(),
  348. holegJFrame.getHeight());
  349. } catch (Exception e) {
  350. e.printStackTrace();
  351. }
  352. System.exit(1);
  353. }
  354. System.exit(0);
  355. }
  356. });
  357. contentPane = (JPanel) holegJFrame.getContentPane();
  358. int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
  359. InputMap inputMap = contentPane.getInputMap(condition);
  360. ActionMap actionMap = contentPane.getActionMap();
  361. String cntrlZDown = "controlZ";
  362. inputMap.put(KeyStroke.getKeyStroke("control Z"), cntrlZDown);
  363. actionMap.put(cntrlZDown, new AbstractAction() {
  364. private static final long serialVersionUID = 1L;
  365. @Override
  366. public void actionPerformed(ActionEvent e) {
  367. try {
  368. controller.loadAutoSave(controller.getUndoSave());
  369. closeInvalidUpperNodeTabs();
  370. controller.calculateStateAndVisualForCurrentTimeStep();
  371. canvas.repaint();
  372. unitGraph.update(model.getObjectsOnCanvas());
  373. updateUpperNodes();
  374. } catch (IOException eex) {
  375. eex.printStackTrace();
  376. }
  377. }
  378. });
  379. String cntrlYDown = "controlY";
  380. inputMap.put(KeyStroke.getKeyStroke("control Y"), cntrlYDown);
  381. actionMap.put(cntrlYDown, new AbstractAction() {
  382. private static final long serialVersionUID = 1L;
  383. @Override
  384. public void actionPerformed(ActionEvent e) {
  385. try {
  386. controller.loadAutoSave(controller.getRedoSave());
  387. closeInvalidUpperNodeTabs();
  388. controller.calculateStateAndVisualForCurrentTimeStep();
  389. canvas.repaint();
  390. unitGraph.update(model.getObjectsOnCanvas());
  391. updateUpperNodes();
  392. } catch (IOException ex) {
  393. ex.printStackTrace();
  394. }
  395. }
  396. });
  397. String cntrlADown = "controlA";
  398. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  399. AbstractAction controlA = new AbstractAction() {
  400. private static final long serialVersionUID = 1L;
  401. @Override
  402. public void actionPerformed(ActionEvent e) {
  403. chooseTabTemp();
  404. model.getSelectedCpsObjects().clear();
  405. // Uppernode Canvas?
  406. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  407. Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
  408. .getComponent(0);
  409. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  410. GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  411. for (AbstractCanvasObject cps : uNC.upperNode.getNodes()) {
  412. controller.addSelectedObject(cps);
  413. }
  414. uNC.repaint();
  415. // or Canvas?
  416. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  417. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  418. controller.addSelectedObject(cps);
  419. }
  420. canvas.repaint();
  421. }
  422. controller.getObjectsInDepth();
  423. }
  424. };
  425. actionMap.put(cntrlADown, controlA);
  426. String delDown = "delete";
  427. inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0, false),
  428. delDown);
  429. actionMap.put(delDown, new AbstractAction() {
  430. private static final long serialVersionUID = 1L;
  431. @Override
  432. public void actionPerformed(ActionEvent e) {
  433. chooseTabTemp();
  434. // Uppernode Canvas?
  435. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  436. Component canvasOrUpperNodeCanvas = scrollPane.getViewport()
  437. .getComponent(0);
  438. // check whether a producer was deleted (this triggers a
  439. // complete re-evaluation of the net)
  440. boolean wasProducerDeleted = true;
  441. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  442. GroupNodeCanvas uNC = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  443. for (AbstractCanvasObject cps : model.getSelectedCpsObjects()) {
  444. controller.removeTrackingObj(cps);
  445. if (uNC.upperNode.getNodes().contains(cps)) {
  446. controller.delObjUpperNode(cps, uNC.upperNode);
  447. unc.setToolTip(false);
  448. // remove UpperNodeTab if UpperNode deleted
  449. removeUpperNodeTab(cps);
  450. }
  451. }
  452. uNC.repaint();
  453. // or Canvas?
  454. } else if (canvasOrUpperNodeCanvas instanceof MyCanvas) {
  455. boolean save = false;
  456. // Edge Deleting
  457. Edge edgeHighlight = model.getSelectedEdge();
  458. if (edgeHighlight != null) {
  459. controller.removeEdgesOnCanvas(edgeHighlight);
  460. // Look for a CPSNode with no Connections and delete
  461. // them
  462. if (edgeHighlight.getA().getClass() == Node.class
  463. && edgeHighlight.getA().getConnections().size() == 0) {
  464. controller.delCanvasObject(edgeHighlight.getA(),
  465. false);
  466. }
  467. if (edgeHighlight.getB().getClass() == Node.class
  468. && edgeHighlight.getB().getConnections().size() == 0) { // Look
  469. // on
  470. // the
  471. // other
  472. // end
  473. // of
  474. // the
  475. // cable
  476. controller.delCanvasObject(edgeHighlight.getB(),
  477. false);
  478. }
  479. ((MyCanvas) canvasOrUpperNodeCanvas).edgeHighlight = null;
  480. }
  481. for (int j = 0; j < model.getSelectedCpsObjects().size(); j++) {
  482. AbstractCanvasObject cps = model.getSelectedCpsObjects()
  483. .get(j);
  484. controller.removeTrackingObj(cps);
  485. if (j < model.getSelectedCpsObjects().size() - 1)
  486. save = true;
  487. controller.delCanvasObject(cps, save);
  488. canvas.setToolTip(false);
  489. // remove UpperNodeTab if UpperNode deleted
  490. removeUpperNodeTab(cps);
  491. }
  492. canvas.repaint();
  493. }
  494. // recalculate net if a producer was deleted
  495. if (wasProducerDeleted) {
  496. controller.resetSimulation();
  497. controller.calculateStateAndVisualForCurrentTimeStep();
  498. }
  499. model.getSelectedCpsObjects().clear();
  500. hideScrollGraph();
  501. }
  502. });
  503. String cntrlFDown = "controlF";
  504. inputMap.put(KeyStroke.getKeyStroke("control F"), cntrlFDown);
  505. actionMap.put(cntrlFDown, new AbstractAction() {
  506. private static final long serialVersionUID = 1L;
  507. @Override
  508. public void actionPerformed(ActionEvent e) {
  509. SearchPopUp dialog = new SearchPopUp(controller, canvas,
  510. holegJFrame);
  511. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  512. dialog.setVisible(true);
  513. }
  514. });
  515. String cntrlCDown = "controlC";
  516. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  517. AbstractAction controlC = new AbstractAction() {
  518. private static final long serialVersionUID = 1L;
  519. @Override
  520. public void actionPerformed(ActionEvent e) {
  521. chooseTabTemp();
  522. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  523. if (!model.getSelectedCpsObjects().isEmpty()) {
  524. if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas)
  525. controller.copy(((GroupNodeCanvas) scrollPane
  526. .getViewport().getComponent(0)).upperNode);
  527. else
  528. controller.copy(null);
  529. if (!model.getClipboradObjects().isEmpty()) {
  530. canvas.itemPaste.setEnabled(true);
  531. }
  532. }
  533. }
  534. };
  535. actionMap.put(cntrlCDown, controlC);
  536. String cntrlVDown = "controlV";
  537. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  538. AbstractAction controlV = new AbstractAction() {
  539. private static final long serialVersionUID = 1L;
  540. @Override
  541. public void actionPerformed(ActionEvent e) {
  542. try {
  543. tabTemp = null;
  544. if (tabbedPaneOriginal.getMousePosition() != null) {
  545. tabTemp = tabbedPaneOriginal;
  546. } else {
  547. if (!initSplit) {
  548. tabTemp = tabbedPaneSplit;
  549. }
  550. }
  551. if(tabTemp == null)return;
  552. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  553. Component canvasOrUpperNodeCanvas = scrollPane
  554. .getViewport().getComponent(0);
  555. if (tabTemp != null
  556. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  557. controller
  558. .paste(((GroupNodeCanvas) canvasOrUpperNodeCanvas).upperNode,
  559. canvasOrUpperNodeCanvas
  560. .getMousePosition());
  561. unitGraph.update(model.getSelectedCpsObjects());
  562. controller.calculateStateAndVisualForCurrentTimeStep();
  563. scrollPane.getViewport().getComponent(0).repaint();
  564. } else {
  565. controller.paste(null, canvas.getMousePosition());
  566. unitGraph.update(model.getSelectedCpsObjects());
  567. controller.calculateStateAndVisualForCurrentTimeStep();
  568. canvas.repaint();
  569. }
  570. } catch (HeadlessException | JsonParseException
  571. | UnsupportedFlavorException | IOException e1) {
  572. JLabel message = new JLabel(
  573. "The Clipboard information cannot be pasted into Application.");
  574. JOptionPane.showMessageDialog(holegJFrame, message,
  575. "", JOptionPane.ERROR_MESSAGE);
  576. }
  577. }
  578. };
  579. actionMap.put(cntrlVDown, controlV);
  580. String cntrlXDown = "controlX";
  581. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  582. AbstractAction controlX = new AbstractAction() {
  583. private static final long serialVersionUID = 1L;
  584. @Override
  585. public void actionPerformed(ActionEvent e) {
  586. chooseTabTemp();
  587. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  588. if (!model.getSelectedCpsObjects().isEmpty()) {
  589. if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
  590. controller.cut(((GroupNodeCanvas) scrollPane
  591. .getViewport().getComponent(0)).upperNode);
  592. controller.calculateStateAndVisualForCurrentTimeStep();
  593. scrollPane.getViewport().getComponent(0).repaint();
  594. } else {
  595. controller.cut(null);
  596. controller.calculateStateAndVisualForCurrentTimeStep();
  597. canvas.repaint();
  598. }
  599. if (!model.getClipboradObjects().isEmpty()) {
  600. canvas.itemPaste.setEnabled(true);
  601. }
  602. }
  603. }
  604. };
  605. actionMap.put(cntrlXDown, controlX);
  606. holegJFrame.setJMenuBar(menuBar);
  607. holegJFrame.setIconImage(Util.loadImage(
  608. "/Images/Holeg.png", 30, 30));
  609. menuBar.add(mnNewMenu);
  610. mnNewMenu.add(mntmNew);
  611. mnNewMenu.add(mntmOpen);
  612. mnNewMenu.add(mntmSave);
  613. menuBar.add(mnNewMenuEdit);
  614. mnNewMenuEdit.add(mntmUndo);
  615. mnNewMenuEdit.add(mntmRedo);
  616. mnLanguage.add(englishBtn);
  617. englishBtn.setIcon(new ImageIcon(new ImageIcon(
  618. "res/Button_Images/FlagEN.png").getImage().getScaledInstance(
  619. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  620. mnLanguage.add(spanishBtn);
  621. spanishBtn.setIcon(new ImageIcon(new ImageIcon(
  622. "res/Button_Images/FlagES.png").getImage().getScaledInstance(
  623. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  624. mnLanguage.add(germanBtn);
  625. germanBtn.setIcon(new ImageIcon(new ImageIcon(
  626. "res/Button_Images/FlagDE.png").getImage().getScaledInstance(
  627. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  628. // mnLanguage.add(czechBtn);
  629. // czechBtn.setIcon(new ImageIcon(new
  630. // ImageIcon("res/Button_Images/FlagCZ.png").getImage().getScaledInstance(20,
  631. // 20, java.awt.Image.SCALE_SMOOTH)));
  632. mnLanguage.add(chineseBtn);
  633. chineseBtn.setIcon(new ImageIcon(new ImageIcon(
  634. "res/Button_Images/FlagZH.png").getImage().getScaledInstance(
  635. 20, 20, java.awt.Image.SCALE_SMOOTH)));
  636. mntmFindReplace.addActionListener(actionEvent -> {
  637. try {
  638. SearchPopUp dialog = new SearchPopUp(controller, canvas,
  639. holegJFrame);
  640. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  641. dialog.setVisible(true);
  642. controller.getObjectsInDepth();
  643. } catch (Exception ex) {
  644. ex.printStackTrace();
  645. }
  646. });
  647. mnNewMenuEdit.add(mntmFindReplace);
  648. mntmEditShowedInformation
  649. .addActionListener(actionEvent -> {
  650. try {
  651. DisplayedInformationPopUp dialog = new DisplayedInformationPopUp(
  652. canvas, contentPane, controller,
  653. holegJFrame);
  654. dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  655. dialog.setVisible(true);
  656. } catch (Exception ex) {
  657. ex.printStackTrace();
  658. }
  659. });
  660. mnNewMenuEdit.add(mntmEditShowedInformation);
  661. mnNewMenuEdit.add(mntmEditEdges);
  662. mntmEditEdges.addActionListener(actionEvent -> {
  663. EditEdgesPopUp edgePopUp = new EditEdgesPopUp(holegJFrame);
  664. edgePopUp.setCanvas(canvas);
  665. edgePopUp.setController(controller);
  666. edgePopUp.setVisible(true);
  667. });
  668. //Edit -> Align All
  669. mnNewMenuEdit.add(mntmAlignAll);
  670. mntmAlignAll.addActionListener(actionEvent -> {
  671. // getScrollPaneFromTabbedPane().getViewport().getComponent(0) is always the active canvas
  672. AbstractCanvas activeCanvas = ((AbstractCanvas) getScrollPaneFromTabbedPane().getViewport().getComponent(0));
  673. if (activeCanvas != null) {
  674. activeCanvas.tryToAlignObjects();
  675. activeCanvas.repaint();
  676. }
  677. });
  678. menuBar.add(mnNewMenuOptions);
  679. mnNewMenuOptions.add(mntmResetCategory);
  680. mntmResetCategory.addActionListener(actionEvent -> {
  681. ArrayList<Category> cat = model.getCategories();
  682. try {
  683. while (!cat.isEmpty()) {
  684. controller.deleteCategory(cat.get(0).getName());
  685. }
  686. controller.resetCategorys();
  687. } catch (Exception e2) {
  688. System.out.println(e2.getMessage());
  689. }
  690. tree.repaint();
  691. });
  692. mnNewMenuOptions.add(useFlexibleDevicesCheckBox);
  693. useFlexibleDevicesCheckBox.setSelected(true);
  694. useFlexibleDevicesCheckBox
  695. .addActionListener(actionEvent -> model
  696. .setUseFlexibleDevices(useFlexibleDevicesCheckBox
  697. .isSelected()));
  698. /**
  699. * Add Fairness Model Option to the option Menu
  700. */
  701. mnNewMenuOptions.add(mnFairnessModel);
  702. mnFairnessModel.add(mntmFairMinFirst);
  703. mntmFairMinFirst.setForeground(Color.BLUE);
  704. mntmFairMinFirst
  705. .setToolTipText("HolonObjects with the smallest mininum Demand will be partially supplied first.\n"
  706. + "After that as many HolonObjects as possible will get fully supplied.");
  707. mntmFairMinFirst
  708. .addActionListener(arg0 -> {
  709. controller.setFairnessModel(FairnessModel.MininumDemandFirst);
  710. mntmFairMinFirst.setForeground(Color.BLUE);
  711. mntmFairAlleEqual.setForeground(mnFairnessModel
  712. .getForeground());
  713. controller.calculateStateAndVisualForCurrentTimeStep();
  714. // Update UpperNodes
  715. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  716. .getViewport().getComponent(0);
  717. if (canvasOrUpperNodeCanvas != null
  718. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  719. ((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  720. }
  721. });
  722. mnFairnessModel.add(mntmFairAlleEqual);
  723. mntmFairAlleEqual
  724. .setToolTipText("HolonObjects will all get the same amount of energy.");
  725. mntmFairAlleEqual.addActionListener(arg0 -> {
  726. controller.setFairnessModel(FairnessModel.AllEqual);
  727. mntmFairAlleEqual.setForeground(Color.BLUE);
  728. mntmFairMinFirst.setForeground(mnFairnessModel.getForeground());
  729. controller.calculateStateAndVisualForCurrentTimeStep();
  730. // Update UpperNodes
  731. Component canvasOrUpperNodeCanvas = getScrollPaneFromTabbedPane()
  732. .getViewport().getComponent(0);
  733. if (canvasOrUpperNodeCanvas != null
  734. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  735. ((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  736. }
  737. });
  738. menuBar.add(mnNewMenuView);
  739. mnNewMenuView.add(mntmCanvasSize);
  740. mntmCanvasSize.addActionListener(actionEvent -> {
  741. CanvasResizePopUp popUp = new CanvasResizePopUp(model, controller,
  742. canvas, tabbedPaneOriginal, tabbedPaneSplit,
  743. holegJFrame);
  744. popUp.setVisible(true);
  745. });
  746. mnNewMenuView.add(splitPane3);
  747. sizeSlider.setMinimum(15);
  748. sizeSlider.setMaximum(115);
  749. sizeSlider
  750. .addChangeListener(changeEvent -> {
  751. controller.setScale(sizeSlider.getValue());
  752. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  753. if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
  754. scrollPane.getViewport().getComponent(0).repaint();
  755. } else {
  756. canvas.repaint();
  757. }
  758. if (!initSplit
  759. && scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
  760. scrollPane.getViewport().getComponent(0).repaint();
  761. } else {
  762. canvas.repaint();
  763. }
  764. });
  765. mnNewMenuView.add(mntmCanvasSize);
  766. mnNewMenuView.add(mntmSplitView);
  767. /*
  768. * Adds Checkbox to turn supply bars on/off
  769. */
  770. mnNewMenuView.add(showSupplyBarsCheckBox);
  771. showSupplyBarsCheckBox.setSelected(true);
  772. showSupplyBarsCheckBox.addActionListener(arg0 -> {
  773. controller.setShowSupplyBars(showSupplyBarsCheckBox.isSelected());
  774. canvas.repaint();
  775. // Update UpperNodes
  776. JScrollPane spane = getScrollPaneFromTabbedPane();
  777. if(spane != null){
  778. Component canvasOrUpperNodeCanvas = spane.getViewport().getComponent(0);
  779. if (canvasOrUpperNodeCanvas != null
  780. && canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  781. ((GroupNodeCanvas) canvasOrUpperNodeCanvas).repaint();
  782. }
  783. }
  784. });
  785. mnNewMenuView.add(showTooltipsCheckBox);
  786. showTooltipsCheckBox.setSelected(true);
  787. showTooltipsCheckBox.addActionListener(arg0 -> {
  788. showHint(showTooltipsCheckBox.isSelected());
  789. });
  790. initWindowMenu();
  791. // Split View
  792. mntmSplitView
  793. .addActionListener(actionEvent -> {
  794. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  795. // add outer tabs
  796. // (inner tabs are added by tabbedPaneSplit
  797. // changelistener)
  798. tabbedPaneSplit.addTab(
  799. tabbedPaneOriginal.getTitleAt(i), null);
  800. }
  801. if (tabbedPaneOriginal.getSelectedComponent() == statScrollPane) {
  802. tabbedPaneOriginal.setComponentAt(0, null);
  803. tabbedPaneSplit.setComponentAt(0, canvasSP);
  804. tabbedPaneSplit.setSelectedIndex(0);
  805. } else {
  806. tabbedPaneOriginal.setComponentAt(1, null);
  807. tabbedPaneSplit.setComponentAt(1, statScrollPane);
  808. tabbedPaneSplit.setSelectedIndex(1);
  809. }
  810. tempSplit = new JSplitPane();
  811. tempSplit.setBorder(null);
  812. tempSplit.setRightComponent(tabbedPaneSplit);
  813. tempSplit.setLeftComponent(tabbedPaneOriginal);
  814. tempSplit.setDividerLocation(tabbedPaneOriginal
  815. .getWidth() / 2);
  816. tempSplit.setResizeWeight(0.9);
  817. initSplit = false;
  818. contentPane.updateUI();
  819. });
  820. mnNewMenuView.add(mntmBackground);
  821. mntmBackground
  822. .addActionListener(actionEvent -> {
  823. tabTemp = tabbedPaneOriginal;
  824. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  825. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  826. BackgroundPopUp backgroundDialog = new BackgroundPopUp(
  827. model, controller, canvas, null,
  828. holegJFrame);
  829. backgroundDialog
  830. .setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  831. backgroundDialog.setVisible(true);
  832. } else if (scrollPane.getViewport().getComponent(0) instanceof GroupNodeCanvas) {
  833. GroupNodeCanvas uNodeCanvas = (GroupNodeCanvas) (scrollPane
  834. .getViewport().getComponent(0));
  835. BackgroundPopUp backgroundDialog = new BackgroundPopUp(
  836. model, controller, null, uNodeCanvas.upperNode,
  837. holegJFrame);
  838. backgroundDialog
  839. .setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
  840. backgroundDialog.setVisible(true);
  841. uNodeCanvas.repaint();
  842. }
  843. });
  844. splitPane3.setRightComponent(sizeSlider);
  845. splitPane3.setLeftComponent(lblImageSize);
  846. mnNewMenuView.add(splitPane_1);
  847. holonBodySizeSlider.setValue(100);
  848. holonBodySizeSlider.setMinimum(1);
  849. holonBodySizeSlider.addChangeListener(changeEvent -> {
  850. controller.setHolonBodyScale(holonBodySizeSlider.getValue());
  851. tree.setRowHeight(50);
  852. canvas.repaint();
  853. });
  854. splitPane_1.setRightComponent(holonBodySizeSlider);
  855. splitPane_1.setLeftComponent(lblHolonBodySize);
  856. /**
  857. * add Help Menu and its items
  858. */
  859. menuBar.add(mnHelp);
  860. mnHelp.add(mntmIntroduction);
  861. mnHelp.add(mntmUserManual);
  862. mnHelp.add(mntmAlgorithmHelp);
  863. mnHelp.add(mntmCodeDoc);
  864. mnHelp.add(mntmAboutUs);
  865. tabbedPaneOriginal.addChangeListener(changeEvent -> {
  866. if (tabbedPaneOriginal.getSelectedComponent() == null) {
  867. Component tempC = tabbedPaneSplit.getSelectedComponent();
  868. tabbedPaneSplit.setComponentAt(
  869. tabbedPaneOriginal.getSelectedIndex(), null);
  870. tabbedPaneOriginal.setComponentAt(
  871. tabbedPaneOriginal.getSelectedIndex(), tempC);
  872. tempC = tabbedPaneOriginal.getComponentAt((tabbedPaneOriginal
  873. .getSelectedIndex() + 1)
  874. % (tabbedPaneOriginal.getTabCount()));
  875. tabbedPaneOriginal.setComponentAt(
  876. (tabbedPaneOriginal.getSelectedIndex() + 1)
  877. % (tabbedPaneOriginal.getTabCount()), null);
  878. tabbedPaneSplit.setComponentAt(
  879. (tabbedPaneOriginal.getSelectedIndex() + 1)
  880. % (tabbedPaneOriginal.getTabCount()), tempC);
  881. tabbedPaneSplit.setSelectedIndex((tabbedPaneOriginal
  882. .getSelectedIndex() + 1)
  883. % (tabbedPaneOriginal.getTabCount()));
  884. contentPane.updateUI();
  885. }
  886. });
  887. tabbedPaneSplit.addChangeListener(changeEvent -> {
  888. if (tabbedPaneSplit.getSelectedComponent() == null && !initSplit) {
  889. Component tempC = tabbedPaneOriginal
  890. .getComponentAt(tabbedPaneSplit.getSelectedIndex());
  891. tabbedPaneOriginal.setComponentAt(
  892. tabbedPaneSplit.getSelectedIndex(), null);
  893. tabbedPaneSplit.setComponentAt(
  894. tabbedPaneSplit.getSelectedIndex(), tempC);
  895. for (int i = 0; i < tabbedPaneOriginal.getTabCount(); i++) {
  896. if (tabbedPaneSplit.getComponentAt(i) != null
  897. && tabbedPaneSplit.getComponentAt(i) != tempC) {
  898. tempC = tabbedPaneSplit.getComponentAt(i);
  899. tabbedPaneSplit.setComponentAt(i, null);
  900. tabbedPaneOriginal.setComponentAt(i, tempC);
  901. break;
  902. }
  903. }
  904. if (tabbedPaneOriginal.getSelectedIndex() == tabbedPaneSplit
  905. .getSelectedIndex()) {
  906. tabbedPaneOriginal.setSelectedIndex((tabbedPaneSplit
  907. .getSelectedIndex() + 1)
  908. % tabbedPaneOriginal.getTabCount());
  909. }
  910. contentPane.updateUI();
  911. }
  912. });
  913. mnNewMenuOptions.add(mnLanguage);
  914. canvas.setBackground(Color.WHITE);
  915. canvas.setPreferredSize(new Dimension(model.getCanvasX(), model
  916. .getCanvasY()));
  917. holonCanvas.setBackground(Color.WHITE);
  918. holonCanvas.setPreferredSize(new Dimension(model.getCanvasX(), model
  919. .getCanvasY()));
  920. /********************
  921. * RIGHT CONTAINER (INFORMATION)
  922. **********************/
  923. // Set up of the HolonElements section
  924. // Two different Models: Multi for multi-selection mode and Single for
  925. // single-selection mode (CPS-Object)
  926. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  927. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  928. model.getTableHolonElement().setBorder(null);
  929. model.getTableHolonElement().setFillsViewportHeight(true);
  930. model.getTableHolonElement().setCellSelectionEnabled(true);
  931. model.getTableHolonElement().setColumnSelectionAllowed(true);
  932. /*
  933. * Register Clicks on ColumNames for sorting:
  934. */
  935. model.getTableHolonElement().getTableHeader()
  936. .addMouseListener(new MouseAdapter() {
  937. public void mouseClicked(MouseEvent e) {
  938. //TODO: sort
  939. //clicked column
  940. int col = model.getTableHolonElement().columnAtPoint(
  941. e.getPoint());
  942. //insert column into UpdateController
  943. updCon.setSortBy(col);
  944. //refresh HolonElementTable
  945. updCon.refreshTableHolonElement(model.getMultiTable(), model.getSingleTable());
  946. }
  947. @Override
  948. public void mouseExited(MouseEvent e) {
  949. /**
  950. * Stop Editing, if mouse exits the Table
  951. */
  952. JTable holElem = model.getTableHolonElement();
  953. JTableHeader holElemHead = holElem.getTableHeader();
  954. if(e.getX()<=0 || e.getX()>=holElemHead.getWidth()
  955. || e.getY() <= 0){
  956. CellEditor cellEditor = holElem.getCellEditor();
  957. if (cellEditor != null) {
  958. if (cellEditor.getCellEditorValue() != null) {
  959. /** TODO: Maybe try to save current Data */
  960. cellEditor.stopCellEditing();
  961. } else {
  962. cellEditor.cancelCellEditing();
  963. }
  964. }
  965. }
  966. }
  967. });
  968. model.getTableHolonElement().getTableHeader().setReorderingAllowed(false);
  969. tableHolonElementScrollPane.setViewportView(model
  970. .getTableHolonElement());
  971. scrollElements.setLayout(new BorderLayout(0, 0));
  972. scrollElements.add(panelHolonEl, BorderLayout.NORTH);
  973. scrollElements.add(tableHolonElementScrollPane);
  974. panelHolonEl.setLayout(new BoxLayout(panelHolonEl, BoxLayout.X_AXIS));
  975. toolBarHolonEl.add(btnAddHolEL);
  976. toolBarHolonEl.add(btnDelHolEL);
  977. toolBarHolonEl.setFloatable(false);
  978. panelHolonEl.add(toolBarHolonEl);
  979. // Set up of the Properties section
  980. tableProperties.setModel(model.getPropertyTable());
  981. tableProperties.setFillsViewportHeight(true);
  982. tableProperties.setCellSelectionEnabled(true);
  983. tableProperties.setColumnSelectionAllowed(true);
  984. scrollProperties.setViewportView(tableProperties);
  985. // Set up of the Graph section
  986. tableGraph.setModel(tableModelGraph);
  987. tableGraph.setFillsViewportHeight(true);
  988. tableGraph.setCellSelectionEnabled(true);
  989. tableGraph.setColumnSelectionAllowed(true);
  990. scrollGraph.setViewportView(unitGraph);
  991. graphLabel.setLayout(new BorderLayout(0, 10));
  992. graphLabel.add(maxGraph, BorderLayout.NORTH);
  993. graphLabel.add(medGraph, BorderLayout.CENTER);
  994. graphLabel.add(minGraph, BorderLayout.SOUTH);
  995. toolBarGraph.setFloatable(false);
  996. toolBarGraph.setAlignmentY(Component.RIGHT_ALIGNMENT);
  997. localPeriodButton.setToolTipText("Toggle Local/Global Mode");
  998. toolBarGraph.add(localPeriodButton);
  999. //ComboBox
  1000. localPeriodInput.setEditable(true);
  1001. localPeriodInput.setVisible(false);
  1002. localPeriodInput.setMaximumSize(new Dimension(20,23));
  1003. localPeriodInput.addItemListener(aListener->{
  1004. if(aListener.getStateChange() == ItemEvent.DESELECTED) {
  1005. validateInput(localPeriodInput.getEditor().getItem().toString(), true);
  1006. }
  1007. });
  1008. toolBarGraph.add(localPeriodInput);
  1009. //localPeriodButtonFunction
  1010. localPeriodButton.addActionListener(actionEvent->{
  1011. boolean newState= !localPeriodInput.isVisible();
  1012. changeLocalPeriodButtonAppeareance(newState);
  1013. unitGraph.setUseLocalPeriod(newState);
  1014. });
  1015. toolBarGraph.add(Box.createHorizontalGlue());
  1016. resetButton.setToolTipText("Reset");
  1017. resetButton.addActionListener(actionEvent -> unitGraph.reset());
  1018. toolBarGraph.add(resetButton);
  1019. scrollGraph.setRowHeaderView(graphLabel);
  1020. scrollGraph.setColumnHeaderView(toolBarGraph);
  1021. tables.add(model.getSingleTable());
  1022. tables.add(model.getMultiTable());
  1023. /***********************
  1024. * HolonElement Table Actions
  1025. **********************/
  1026. /*
  1027. * Add HolonElement to given HolonObject
  1028. */
  1029. btnAddHolEL.addActionListener(actionEvent -> {
  1030. if (model.getSelectedCpsObjects().size() == 1) {
  1031. AbstractCanvasObject tempCpsObject = updCon.getActualCps();
  1032. if (tempCpsObject != null
  1033. && tempCpsObject.getClass() == HolonObject.class
  1034. && tempCpsObject.getId() != 0) {
  1035. addElementPopUp = new AddElementPopUp(holegJFrame, model);//TODO: I didn't even check
  1036. addElementPopUp.setActualCps(updCon.getActualCps());
  1037. addElementPopUp.setVisible(true);
  1038. HolonElement ele = addElementPopUp.getElement();
  1039. if (ele != null) {
  1040. controller.addElementCanvasObject(
  1041. tempCpsObject.getId(), ele.getEleName(),
  1042. ele.getAmount(), ele.getEnergyPerElement(),
  1043. ele.getId());
  1044. }
  1045. controller.calculateStateAndVisualForTimeStep(model
  1046. .getCurIteration());
  1047. triggerUpdateController(null);
  1048. contentPane.updateUI();
  1049. }
  1050. }else
  1051. {
  1052. JOptionPane.showMessageDialog(contentPane, "No object selected.\nPlease select a object first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
  1053. }
  1054. });
  1055. /*
  1056. * Delete the chosen HolonElement of the selected HolonObject,
  1057. * Multi-Selection for CpsObjects as well as for HolonElements possible
  1058. */
  1059. btnDelHolEL.addActionListener(actionEvent -> {
  1060. // For Single Selection of CpsObject
  1061. if (model.getSelectedCpsObjects().size() == 1) {
  1062. if (updCon.getActualCps().getClass() == HolonObject.class) {
  1063. HolonObject obj = (HolonObject) updCon.getActualCps();
  1064. if(selectedElements.isEmpty())
  1065. {
  1066. JOptionPane.showMessageDialog(contentPane, "No element selectet.\nPlease select a element in the list first." , "Message" , JOptionPane.INFORMATION_MESSAGE);
  1067. }
  1068. for (HolonElement e : selectedElements) {
  1069. controller.deleteElementCanvas(obj.getId(),
  1070. e.getId());
  1071. controller.calculateStateAndVisualForTimeStep(model
  1072. .getCurIteration());
  1073. triggerUpdateController(null);
  1074. contentPane.updateUI();
  1075. // Names displayed in graph are not updated
  1076. }
  1077. model.getEleToDelete().clear();
  1078. selectedElements.clear();
  1079. }
  1080. // For MultiSelection of CpsObject
  1081. } else if (model.getSelectedCpsObjects().size() > 1) {
  1082. for (Integer i : model.getEleToDelete().keySet()) {
  1083. for (HolonElement e : model.getEleToDelete().get(i)) {
  1084. controller.deleteElementCanvas(i, e.getId());
  1085. }
  1086. }
  1087. triggerUpdateController(null);
  1088. model.getEleToDelete().clear();
  1089. selectedElements.clear();
  1090. }else
  1091. {
  1092. JOptionPane.showMessageDialog(contentPane, "No object selectet.\nPlease select a object first." , "No object selectet" , JOptionPane.INFORMATION_MESSAGE);
  1093. }
  1094. triggerUpdateController(null);
  1095. elementGraph.setText(Languages.getLanguage()[25]);
  1096. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1097. }) ;
  1098. /*
  1099. * Communication between HolonElement Table and displayed Graph and
  1100. * Properties, as well as selection of different HolonElements
  1101. */
  1102. model.getTableHolonElement().addMouseListener(new MouseAdapter() {
  1103. public void mousePressed(MouseEvent e) {
  1104. HolonObject obj = null;
  1105. if (model.getSelectedCpsObjects().size() == 1
  1106. && model.getSelectedCpsObjects().get(0) instanceof HolonObject) {
  1107. obj = (HolonObject) updCon.getActualCps();
  1108. }
  1109. yValueElements = e.getY();
  1110. HolonElement ele;
  1111. // Search for current clicked HolonElement
  1112. if (model.getSelectedCpsObjects().size() == 1) {
  1113. ele = updCon.getActualHolonElement(obj, yValueElements, 0,
  1114. tables);
  1115. } else {
  1116. ele = updCon.getActualHolonElement(null, yValueElements, 0,
  1117. tables);
  1118. }
  1119. // Multi-Selection of HolonElements through control button +
  1120. // mouse click
  1121. if (ele != null) {
  1122. // make energy-consumption graph visible
  1123. showScrollGraph();
  1124. if (e.isControlDown()) {
  1125. if (!selectedElements.contains(ele)) {
  1126. selectedElements.add(ele);
  1127. if (!holonEleNamesDisplayed.equals(Languages
  1128. .getLanguage()[25])) {
  1129. holonEleNamesDisplayed = holonEleNamesDisplayed
  1130. + "; " + ele.getEleName() + " ";
  1131. } else {
  1132. holonEleNamesDisplayed = ele.getEleName() + " ";
  1133. }
  1134. updateUnitGraph((GraphEditable)selectedElements.get(selectedElements.size()-1));
  1135. }
  1136. updCon.getActualHolonElement(null, yValueElements, 2,
  1137. tables);
  1138. }
  1139. // if no control-button pressed but a HolonElement chosen
  1140. else {
  1141. selectedElements.clear();
  1142. selectedElements.add(ele);
  1143. updCon.getActualHolonElement(null, yValueElements, 1,
  1144. tables);
  1145. holonEleNamesDisplayed = ele.getEleName() + " ";
  1146. updateUnitGraph((GraphEditable)selectedElements.get(selectedElements.size()-1));
  1147. }
  1148. } else {
  1149. elementGraph.setText(Languages.getLanguage()[25]);
  1150. hideScrollGraph();
  1151. }
  1152. // if any HolonElement is double-clicked --> Edit-Mode started
  1153. // for selected HolonElement
  1154. if (e.getClickCount() == 2) {
  1155. yThis = e.getY();
  1156. xThis = e.getX();
  1157. }
  1158. // for single click and empty slot
  1159. if (e.getClickCount() == 1 && ele == null) {
  1160. selectedElements.clear();
  1161. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1162. }
  1163. elementGraph.setText(holonEleNamesDisplayed);
  1164. yBTis = e.getY();
  1165. xBThis = e.getX();
  1166. }
  1167. @Override
  1168. public void mouseExited(MouseEvent e) {
  1169. /**
  1170. * Stop Editing, if mouse exits the Table
  1171. */
  1172. JTable holElem = model.getTableHolonElement();
  1173. if(e.getX()<=0 || e.getX()>=holElem.getWidth()
  1174. /*|| e.getY() <= 0*/|| e.getY()>= holElem.getHeight()){
  1175. CellEditor cellEditor = holElem.getCellEditor();
  1176. if (cellEditor != null) {
  1177. if (cellEditor.getCellEditorValue() != null) {
  1178. /** TODO: Maybe try to save current Data */
  1179. cellEditor.stopCellEditing();
  1180. } else {
  1181. cellEditor.cancelCellEditing();
  1182. }
  1183. }
  1184. }
  1185. }
  1186. });
  1187. /*
  1188. * Triggered every time a change is made
  1189. */
  1190. model.getTableHolonElement()
  1191. .addPropertyChangeListener(propertyChangeEvent -> {
  1192. try {
  1193. int yMouse = yThis;
  1194. int yBMouse = yBTis;
  1195. int selectedValueY = (int) Math.floor(yMouse / 16);
  1196. int selectedValueBY = (int) Math.floor(yBMouse / 16);
  1197. // ------------------ multi-selection mode
  1198. // ------------------
  1199. if (model.getSelectedCpsObjects().size() > 1) {
  1200. int selectedValueX = (int) Math
  1201. .floor(xThis
  1202. / (model.getTableHolonElement()
  1203. .getWidth() / 8));
  1204. int selectedValueBX = (int) Math
  1205. .floor(xBThis
  1206. / (model.getTableHolonElement()
  1207. .getWidth() / 8));
  1208. if (updCon.getHolonObj(yMouse,
  1209. model.getMultiTable()) != null) {
  1210. // For active column (boolean with a checkbox)
  1211. if (selectedValueBX == 6) {
  1212. System.out.println("selectedValueBX == 6");
  1213. HolonElement eleBTemp = updCon
  1214. .getActualHolonElement(null,
  1215. yBMouse, 0, tables);
  1216. String newBStuff = model
  1217. .getMultiTable()
  1218. .getValueAt(selectedValueBY,
  1219. selectedValueBX).toString();
  1220. Boolean bTemp = Boolean
  1221. .parseBoolean(newBStuff);
  1222. eleBTemp.setActive(bTemp);
  1223. }
  1224. // For activeFlex column (boolean with a
  1225. // checkbox)
  1226. else if (selectedValueBX == 7) {
  1227. System.out.println("selectedValueBX == 7");
  1228. HolonElement eleBTemp = updCon
  1229. .getActualHolonElement(null,
  1230. yBMouse, 0, tables);
  1231. String newBStuff = model
  1232. .getMultiTable()
  1233. .getValueAt(selectedValueBY,
  1234. selectedValueBX).toString();
  1235. Boolean bTemp = Boolean
  1236. .parseBoolean(newBStuff);
  1237. eleBTemp.setActive(bTemp);
  1238. } else {
  1239. // Update of HolonElement
  1240. HolonElement eleTemp = updCon
  1241. .getActualHolonElement(null,
  1242. yMouse, 0, tables);
  1243. String newStuff = model
  1244. .getMultiTable()
  1245. .getValueAt(selectedValueY,
  1246. selectedValueX).toString();
  1247. // Name update
  1248. if (selectedValueX == 2) {
  1249. eleTemp.setEleName(newStuff);
  1250. }
  1251. // Energy Update
  1252. else if (selectedValueX == 3) {
  1253. System.out.println("selectedValueX == 3");
  1254. Float ftemp = Float
  1255. .parseFloat(newStuff);
  1256. eleTemp.setEnergyPerElement(ftemp);
  1257. }
  1258. // Flexibility
  1259. else if (selectedValueX == 4) {
  1260. Float ftemp = Float
  1261. .parseFloat(newStuff);
  1262. //TODO and here
  1263. }
  1264. // Amount of Elements update
  1265. else if (selectedValueX == 5) {
  1266. Integer iTemp = Integer
  1267. .parseInt(newStuff);
  1268. eleTemp.setAmount(iTemp);
  1269. }
  1270. else if (selectedValueX == 6) {
  1271. System.out.println("Test");
  1272. }
  1273. }
  1274. }
  1275. } // ------------------ single-selection mode
  1276. // ------------------
  1277. else if (model.getSelectedCpsObjects().size() == 1) {
  1278. int selectedValueX = (int) Math
  1279. .floor(xThis
  1280. / (model.getTableHolonElement()
  1281. .getWidth() / 7));
  1282. int selectedValueBX = (int) Math
  1283. .floor(xBThis
  1284. / (model.getTableHolonElement()
  1285. .getWidth() / 7));
  1286. if (updCon.getActualCps() != null
  1287. && updCon.getActualCps().getClass() == HolonObject.class) {
  1288. HolonElement eleTemp;
  1289. // For active column (boolean with a checkbox)
  1290. if (selectedValueBX == 5) {
  1291. eleTemp = updCon.getActualHolonElement(
  1292. (HolonObject) updCon.getActualCps(),
  1293. yBMouse, 0, tables);
  1294. String newBStuff = model
  1295. .getSingleTable()
  1296. .getValueAt(selectedValueBY,
  1297. selectedValueBX).toString();
  1298. Boolean bTemp = Boolean
  1299. .parseBoolean(newBStuff);
  1300. eleTemp.setActive(bTemp);
  1301. } // For activeFlex column (boolean with a
  1302. // checkbox)
  1303. else if (selectedValueBX == 6) {
  1304. eleTemp = updCon.getActualHolonElement(
  1305. (HolonObject) updCon.getActualCps(),
  1306. yBMouse, 0, tables);
  1307. String newBStuff = model
  1308. .getSingleTable()
  1309. .getValueAt(selectedValueBY,
  1310. selectedValueBX -1).toString();
  1311. Boolean bTemp = Boolean
  1312. .parseBoolean(newBStuff);
  1313. eleTemp.setActive(bTemp);
  1314. //TODO: delete Boolean bTemp = Boolean.parseBoolean(newBStuff);
  1315. } else {
  1316. // Update of HolonElement
  1317. eleTemp = updCon.getActualHolonElement(
  1318. (HolonObject) updCon.getActualCps(),
  1319. yMouse, 0, tables);
  1320. String newStuff = model
  1321. .getSingleTable()
  1322. .getValueAt(selectedValueY,
  1323. selectedValueX).toString();
  1324. // Name update
  1325. if (selectedValueX == 1) {
  1326. eleTemp.setEleName(newStuff);
  1327. } // Energy Update
  1328. else if (selectedValueX == 2) {
  1329. Float ftemp = Float
  1330. .parseFloat(newStuff);
  1331. eleTemp.setEnergyPerElement(ftemp);
  1332. } // Flexibility
  1333. else if (selectedValueX == 3) {
  1334. Float ftemp = Float
  1335. .parseFloat(newStuff);
  1336. //TODO ---
  1337. // if this is a flexible device and the
  1338. // flexibly available energy was
  1339. // changed,
  1340. // set used energy to 0, so that it can
  1341. // be computed anew
  1342. }
  1343. // Amount of Elements update
  1344. else if (selectedValueX == 4) {
  1345. Integer iTemp = Integer
  1346. .parseInt(newStuff);
  1347. eleTemp.setAmount(iTemp);
  1348. }
  1349. }
  1350. // set all cells anew, if anything was changed
  1351. updateElementTableAfterChange(eleTemp,
  1352. selectedValueBY);
  1353. }
  1354. }
  1355. controller.calculateStateAndVisualForTimeStep(model
  1356. .getCurIteration());
  1357. model.getSingleTable().fireTableDataChanged();
  1358. triggerUpdateController(null);
  1359. contentPane.updateUI();
  1360. unitGraph.repaint();
  1361. // trigger update of table after UnitGraph was painted
  1362. SwingUtilities.invokeLater(() -> {
  1363. triggerUpdateController(null);
  1364. });
  1365. } catch (Exception e) {
  1366. }
  1367. });
  1368. /***********************
  1369. * HolonElement Properties Actions
  1370. **********************/
  1371. /*
  1372. * Update of the mouse coord for Edit-Mode
  1373. */
  1374. tableProperties.addMouseListener(new MouseAdapter() {
  1375. public void mousePressed(MouseEvent e) {
  1376. if (e.getClickCount() == 2) {
  1377. yProThis = e.getY();
  1378. xProThis = e.getX();
  1379. }
  1380. yProThisOneClick = e.getY();
  1381. xProThisOneClick = e.getX();
  1382. }
  1383. });
  1384. /*
  1385. * Update any change in the Property table
  1386. */
  1387. tableProperties.addPropertyChangeListener(propertyChangeEvent -> {
  1388. try {
  1389. Object temp;
  1390. Object btemp;
  1391. int selValueY = (int) Math.floor(yProThis / 16);
  1392. int selValueX = (int) Math.floor(xProThis
  1393. / (tableProperties.getWidth() / 2));
  1394. int selValueYBool = (int) Math.floor(yProThisOneClick / 16);
  1395. int selValueXBool = (int) Math.floor(xProThisOneClick
  1396. / (tableProperties.getWidth() / 2));
  1397. if (updCon.getActualCps() != null) {
  1398. temp = model.getPropertyTable().getValueAt(selValueY,
  1399. selValueX);
  1400. btemp = model.getPropertyTable().getValueAt(selValueYBool,
  1401. selValueXBool);
  1402. // Case: Switch selected
  1403. if (updCon.getActualCps() instanceof HolonSwitch) {
  1404. if (selValueY == 0 && selValueX != 0) {
  1405. updCon.getActualCps().setName(temp.toString());
  1406. }
  1407. if (selValueYBool == 2) {
  1408. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1409. ((HolonSwitch) updCon.getActualCps())
  1410. .setManualMode(bbTemp);
  1411. if (bbTemp) {
  1412. model.getPropertyTable()
  1413. .setCellEditable(3, 1, true);
  1414. } else {
  1415. model.getPropertyTable().setCellEditable(3, 1,
  1416. false);
  1417. }
  1418. } else if (selValueYBool == 3) {
  1419. if (((HolonSwitch) updCon.getActualCps())
  1420. .getManualMode()) {
  1421. model.getPropertyTable()
  1422. .setCellEditable(3, 1, true);
  1423. Boolean bTemp = Boolean.parseBoolean(btemp
  1424. .toString());
  1425. ((HolonSwitch) updCon.getActualCps())
  1426. .setManualState(bTemp);
  1427. }
  1428. }
  1429. } // Case: UpperNode selected
  1430. else if (updCon.getActualCps() instanceof GroupNode
  1431. && selValueX != 0) {
  1432. // Name edition through double click
  1433. updCon.getActualCps().setName(temp.toString());
  1434. // Update of name on the tab in the tab section
  1435. for (int index = 4; index < tabbedPaneOriginal
  1436. .getTabCount(); index++) {
  1437. tabTemp = tabbedPaneOriginal;
  1438. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1439. GroupNodeCanvas unc = ((GroupNodeCanvas) scrollPane
  1440. .getViewport().getComponent(0));
  1441. if (unc.upperNode.getId() == updCon.getActualCps()
  1442. .getId()) {
  1443. tabbedPaneOriginal.setTitleAt(index,
  1444. unc.upperNode.getName());
  1445. tabbedPaneOriginal.updateUI();
  1446. if (!initSplit) {
  1447. tabbedPaneSplit.setTitleAt(index,
  1448. unc.upperNode.getName());
  1449. tabbedPaneSplit.updateUI();
  1450. }
  1451. }
  1452. }
  1453. } // Case: HolonObject is selected
  1454. else if (updCon.getActualCps() instanceof HolonObject
  1455. && selValueX != 0) {
  1456. // Name edition through double click
  1457. updCon.getActualCps().setName(temp.toString());
  1458. }
  1459. } // Case: Edge is selected
  1460. else {
  1461. temp = model.getPropertyTable()
  1462. .getValueAt(selValueY, selValueX);
  1463. btemp = model.getPropertyTable().getValueAt(selValueYBool,
  1464. selValueXBool);
  1465. // Edit modus for capacity by double clicking
  1466. if (selValueY == 2) {
  1467. Float ftemp;
  1468. if (Float.parseFloat(temp.toString()) >= 0.0) {
  1469. ftemp = Float.parseFloat(temp.toString());
  1470. } else {
  1471. ftemp = model.getSelectedEdge().getCapacity();
  1472. }
  1473. model.getSelectedEdge().setCapacity(ftemp);
  1474. }
  1475. // Status edition through a check box
  1476. if (selValueYBool == 3) {
  1477. Boolean bbTemp = Boolean.parseBoolean(btemp.toString());
  1478. }
  1479. }
  1480. canvas.repaint();
  1481. } catch (Exception e) {
  1482. }
  1483. }) ;
  1484. /***********************
  1485. * HolonElement Graph Actions
  1486. **********************/
  1487. /*
  1488. * Update Local Period of an Element Graph
  1489. */
  1490. unitGraphLocalPeriod.addKeyListener(new KeyAdapter() {
  1491. @Override
  1492. public void keyReleased(KeyEvent e) {
  1493. try{
  1494. int localLength = Integer.parseInt(unitGraphLocalPeriod.getText());
  1495. unitGraphLocalPeriod.setBackground(Color.WHITE);
  1496. /**
  1497. * set local graph Period
  1498. */
  1499. if(e.getKeyCode() == KeyEvent.VK_ENTER)
  1500. unitGraph.setLocalPeriod(localLength);
  1501. }catch(NumberFormatException ex){
  1502. unitGraphLocalPeriod.setBackground(PALE_RED);
  1503. }
  1504. }
  1505. });
  1506. /*****************************
  1507. * RIGHT CONTAINER DONE
  1508. *****************************/
  1509. holegJFrame.getContentPane().setLayout(new BorderLayout(0, 0));
  1510. /****************
  1511. * Tree Stuff
  1512. ****************/
  1513. // Override Key Actions
  1514. inputMap = tree.getInputMap();
  1515. inputMap.put(KeyStroke.getKeyStroke("control C"), cntrlCDown);
  1516. inputMap.put(KeyStroke.getKeyStroke("control V"), cntrlVDown);
  1517. inputMap.put(KeyStroke.getKeyStroke("control X"), cntrlXDown);
  1518. inputMap.put(KeyStroke.getKeyStroke("control A"), cntrlADown);
  1519. TreeCellRenderer customRenderer = new TreeCellRenderer() {
  1520. @Override
  1521. public Component getTreeCellRendererComponent(JTree tree,
  1522. Object value, boolean selected, boolean expanded,
  1523. boolean leaf, int row, boolean hasFocus) {
  1524. JLabel label = new JLabel();
  1525. Image imgR;
  1526. if (leaf) {
  1527. for (Category cat : model.getCategories()) {
  1528. for (AbstractCanvasObject cps : cat.getObjects()) {
  1529. if (value.toString().compareTo(cps.getObjName()) == 0) {
  1530. imgR = Util.loadImage(cps.getImage(), 50,
  1531. 50);
  1532. if (imgR != null) {
  1533. label.setIcon(new ImageIcon(imgR));
  1534. }
  1535. label.setText(cps.getName());
  1536. }
  1537. }
  1538. }
  1539. }
  1540. tree.setRowHeight(50);
  1541. if (hasFocus) {
  1542. label.setForeground(new Color(0, 0, 255));
  1543. label.setOpaque(true);
  1544. }
  1545. if (label.getText().length() == 0) {
  1546. label.setText(value.toString());
  1547. if (value.toString().compareTo("Categories") != 0) {
  1548. label.setIcon(new ImageIcon(Util.loadImage(
  1549. "/Images/folder.png")));
  1550. }
  1551. }
  1552. return label;
  1553. }
  1554. };
  1555. tree.setCellRenderer(customRenderer);
  1556. tree.addMouseMotionListener(new MouseMotionAdapter() {
  1557. public void mouseDragged(MouseEvent e){
  1558. checkForDragAndDrop(e);
  1559. }
  1560. /**
  1561. * checks if an object of the current Panel
  1562. * could be replaced by the dragged object
  1563. * @param e
  1564. */
  1565. private void checkForDragAndDrop(MouseEvent e){
  1566. try {
  1567. /**
  1568. * if no object gets dragged -> finished
  1569. */
  1570. if(!dragging)return;
  1571. /**
  1572. * select the current Panel
  1573. */
  1574. chooseTabTemp();
  1575. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1576. if(scrollPane == null)return;
  1577. Component canvasOrUpperNodeCanvas = scrollPane
  1578. .getViewport().getComponent(0);
  1579. /**
  1580. * check for replacements on the canvas
  1581. */
  1582. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  1583. GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  1584. if(unc.getMousePosition()==null)return;
  1585. int x = (int) unc.getMousePosition().getX()+16;
  1586. int y = (int) unc.getMousePosition().getY()+16;
  1587. /**
  1588. * if in upperNode
  1589. */
  1590. if (x <= unc.upperNode.getLeftBorder()) return;
  1591. /**
  1592. * check for replacement
  1593. */
  1594. unc.checkForReplacement(x, y);
  1595. /**
  1596. * repaint
  1597. */
  1598. unc.invalidate();
  1599. unc.repaint();
  1600. } else {
  1601. if(canvas.getMousePosition()==null)return;
  1602. int x = (int) canvas.getMousePosition().getX()+16;
  1603. int y = (int) canvas.getMousePosition().getY()+16;
  1604. /**
  1605. * check for replacement
  1606. */
  1607. canvas.checkForReplacement(x, y);
  1608. /**
  1609. * repaint
  1610. */
  1611. canvas.invalidate();
  1612. canvas.repaint();
  1613. }
  1614. contentPane.updateUI();
  1615. } catch (Exception eex) {
  1616. eex.printStackTrace();
  1617. }
  1618. }});
  1619. tree.addMouseListener(new MouseAdapter() {
  1620. public void mouseReleased(MouseEvent e) {
  1621. try {
  1622. if (dragging) {
  1623. chooseTabTemp();
  1624. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  1625. Component canvasOrUpperNodeCanvas = scrollPane
  1626. .getViewport().getComponent(0);
  1627. if (canvasOrUpperNodeCanvas instanceof GroupNodeCanvas) {
  1628. GroupNodeCanvas unc = (GroupNodeCanvas) canvasOrUpperNodeCanvas;
  1629. int x = (int) unc.getMousePosition().getX() + 16;
  1630. int y = (int) unc.getMousePosition().getY() + 16;
  1631. if (x > unc.upperNode.getLeftBorder()) {
  1632. AbstractCanvasObject h = null;
  1633. if (tempCps instanceof HolonObject) {
  1634. h = new HolonObject(tempCps);
  1635. }
  1636. if (tempCps instanceof HolonSwitch) {
  1637. h = new HolonSwitch(tempCps);
  1638. }
  1639. if (tempCps instanceof HolonBattery)
  1640. {
  1641. h = new HolonBattery(tempCps);
  1642. }
  1643. h.setPosition(x, y);
  1644. /**
  1645. * close UpperNodeTabs of replaced UpperNode
  1646. */
  1647. if(unc.mayBeReplaced!=null &&unc.mayBeReplaced instanceof GroupNode){
  1648. unc.closeUpperNodeTab(unc.mayBeReplaced.getId());
  1649. }
  1650. controller.addObjUpperNode(h, unc.upperNode);
  1651. /**
  1652. * object would be replaced
  1653. */
  1654. unc.mayBeReplaced = null;
  1655. unc.invalidate();
  1656. controller.calculateStateAndVisualForCurrentTimeStep();
  1657. unc.repaint();
  1658. unc.setXY((int) canvas.getMousePosition()
  1659. .getX(), (int) canvas
  1660. .getMousePosition().getY());
  1661. }
  1662. } else {
  1663. int x = (int) canvas.getMousePosition().getX() + 16;
  1664. int y = (int) canvas.getMousePosition().getY() + 16;
  1665. AbstractCanvasObject h = null;
  1666. if (tempCps instanceof HolonObject) {
  1667. h = new HolonObject(tempCps);
  1668. }
  1669. if (tempCps instanceof HolonSwitch) {
  1670. h = new HolonSwitch(tempCps);
  1671. }
  1672. if (tempCps instanceof HolonBattery)
  1673. {
  1674. h = new HolonBattery(tempCps);
  1675. }
  1676. h.setPosition(x, y);
  1677. /**
  1678. * close UpperNodeTabs of replaced UpperNode
  1679. */
  1680. if(canvas.mayBeReplaced!=null &&canvas.mayBeReplaced instanceof GroupNode){
  1681. canvas.closeUpperNodeTab(canvas.mayBeReplaced.getId());
  1682. }
  1683. controller.addObjectCanvas(h);
  1684. /**
  1685. * no object should get replaced
  1686. */
  1687. canvas.mayBeReplaced = null;
  1688. canvas.invalidate();
  1689. canvas.setXY(
  1690. (int) canvas.getMousePosition().getX(),
  1691. (int) canvas.getMousePosition().getY());
  1692. canvas.repaint();
  1693. }
  1694. controller.calculateStateAndVisualForCurrentTimeStep();
  1695. contentPane.updateUI();
  1696. dragging = false;
  1697. }
  1698. } catch (Exception eex) {
  1699. }
  1700. holegJFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
  1701. }
  1702. });
  1703. popmenuEdit.add(editItem);
  1704. popmenuEdit.add(removeItem);
  1705. editItem.setEnabled(false);
  1706. editItem.addActionListener(actionEvent -> {
  1707. });
  1708. tree.addMouseListener(new MouseAdapter() {
  1709. public void mousePressed(MouseEvent e) {
  1710. try {
  1711. actualObjectClicked = tree
  1712. .getPathForLocation(e.getX(), e.getY())
  1713. .getLastPathComponent().toString();
  1714. // if an Object was selected, the porperties are shown in
  1715. // the table
  1716. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree
  1717. .getPathForLocation(e.getX(), e.getY())
  1718. .getLastPathComponent();
  1719. if (selectedNode.getLevel() == 2) {
  1720. controller.searchCategoryObject(selectedNode
  1721. .getParent().toString(), selectedNode
  1722. .toString());
  1723. updCon.deleteRows(model.getSingleTable());
  1724. updCon.deleteRows(model.getMultiTable());
  1725. // if (selected instanceof HolonObject && selected !=
  1726. // null) {
  1727. // selected = (HolonObject) selected;
  1728. // fillElementTable(((HolonObject)
  1729. // selected).getElements());
  1730. // }
  1731. }
  1732. if (SwingUtilities.isRightMouseButton(e)) {
  1733. for (Category cat : model.getCategories()) {
  1734. for (AbstractCanvasObject cps : cat.getObjects()) {
  1735. if (actualObjectClicked.compareTo(cps
  1736. .getObjName()) == 0
  1737. && !(cps instanceof HolonSwitch)) {
  1738. editItem.setEnabled(true);
  1739. popmenuEdit.show(e.getComponent(),
  1740. e.getX(), e.getY());
  1741. catOfObjToBeEdited = selectedNode
  1742. .getParent().toString();
  1743. tempCps = cps;
  1744. }
  1745. }
  1746. }
  1747. } else {
  1748. for (Category cat : model.getCategories()) {
  1749. for (AbstractCanvasObject cps : cat.getObjects()) {
  1750. if (actualObjectClicked.compareTo(cps
  1751. .getObjName()) == 0) {
  1752. File checkPath = new File(cps.getImage());
  1753. if (checkPath.exists()) {
  1754. img = new ImageIcon(cps.getImage())
  1755. .getImage()
  1756. .getScaledInstance(
  1757. 32,
  1758. 32,
  1759. java.awt.Image.SCALE_SMOOTH);
  1760. } else {
  1761. img = Util.loadImage(
  1762. cps.getImage(), 32, 32);
  1763. }
  1764. tempCps = cps;
  1765. dragging = true;
  1766. Cursor cursor = Toolkit.getDefaultToolkit()
  1767. .createCustomCursor(img,
  1768. new Point(0, 0), "Image");
  1769. holegJFrame.setCursor(cursor);
  1770. }
  1771. }
  1772. }
  1773. }
  1774. } catch (Exception eex) {
  1775. }
  1776. }
  1777. });
  1778. editItem.addActionListener(actionEvent -> {
  1779. // Remove the selected Object object
  1780. //AddObjectPopUp(boolean edit, AbstractCpsObject obj, String cat, JFrame parentFrame)
  1781. System.out.println("Edit");
  1782. addObjectPopUP = new AddObjectPopUp(true, tempCps,
  1783. catOfObjToBeEdited, holegJFrame);
  1784. addObjectPopUP.setCategory(catOfObjToBeEdited);
  1785. addObjectPopUP.setController(controller);
  1786. addObjectPopUP.setVisible(true);
  1787. });
  1788. removeItem.addActionListener(actionEvent -> {
  1789. // Remove the selected Object object
  1790. try {
  1791. System.out.println("catOfObjToBeEdited:" + catOfObjToBeEdited + ", tempCps:" + tempCps);
  1792. controller.delObjectCategory(catOfObjToBeEdited, tempCps.getName());
  1793. }catch(IOException e) {
  1794. System.err.println("IOException");
  1795. e.printStackTrace();
  1796. }
  1797. });
  1798. scrollPane1.setViewportView(tree);
  1799. scrollPane1.setColumnHeaderView(panel);
  1800. panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
  1801. toolBar.setAlignmentX(Component.LEFT_ALIGNMENT);
  1802. toolBar.setFloatable(false);
  1803. panel.add(toolBar);
  1804. btnAddPopUp.add(mItemNew);
  1805. mItemNew.addActionListener(actionEvent -> {
  1806. new NewPopUp(controller, holegJFrame);
  1807. });
  1808. btnAddPopUp.addSeparator();
  1809. btnAddPopUp.add(mItemCategory);
  1810. mItemCategory.addActionListener(actionEvent -> {
  1811. new NewPopUp(controller,Option.Category, holegJFrame);
  1812. });
  1813. btnAddPopUp.add(mItemObject);
  1814. mItemObject.addActionListener(actionEvent -> {
  1815. new NewPopUp(controller,Option.Object, holegJFrame);
  1816. });
  1817. btnAddPopUp.add(mItemSwitch);
  1818. mItemSwitch.addActionListener(actionEvent -> {
  1819. new NewPopUp(controller,Option.Switch, holegJFrame);
  1820. });
  1821. btnAddPopUp.add(mItemBattery);
  1822. mItemBattery.addActionListener(actionEvent -> {
  1823. new NewPopUp(controller,Option.Battery, holegJFrame);
  1824. });
  1825. btnAdd.addActionListener(actionEvent -> btnAddPopUp.show(btnAdd, -1, +20));
  1826. btnAdd.setToolTipText("Add a new Category or Item to the library.");
  1827. toolBar.add(btnAdd);
  1828. /**
  1829. * Help Menu Action Listeners
  1830. */
  1831. /**
  1832. * URL of the telecommunication git Wiki
  1833. */
  1834. String tkWikiWebpage = "https://git.tk.informatik.tu-darmstadt.de/carlos.garcia/praktikum-holons/wiki/";
  1835. /** open Introduction Web Page */
  1836. mntmIntroduction.addMouseListener(new MouseAdapter() {
  1837. @Override
  1838. public void mousePressed(MouseEvent e){
  1839. openWebpage(tkWikiWebpage + "Introduction+V2.1");
  1840. }
  1841. });
  1842. /** open UserManual WebPage */
  1843. mntmUserManual.addMouseListener(new MouseAdapter() {
  1844. @Override
  1845. public void mousePressed(MouseEvent e){
  1846. openWebpage(tkWikiWebpage + "User+Manual+V2.1");
  1847. }
  1848. });
  1849. /** open Algorithm Help Web Page*/
  1850. mntmAlgorithmHelp.addMouseListener(new MouseAdapter() {
  1851. @Override
  1852. public void mousePressed(MouseEvent e){
  1853. openWebpage(tkWikiWebpage + "Algorithms+V2.1");
  1854. }
  1855. });
  1856. /** open Code Documentation Web Page */
  1857. mntmCodeDoc.addMouseListener(new MouseAdapter() {
  1858. @Override
  1859. public void mousePressed(MouseEvent e){
  1860. openWebpage(tkWikiWebpage + "Code+documentation+V2.1");
  1861. }
  1862. });
  1863. /**
  1864. * Pop up - About Us with some important information about the
  1865. * developers, source and programming stuff
  1866. */
  1867. mntmAboutUs.addMouseListener(new MouseAdapter() {
  1868. @Override
  1869. public void mousePressed(MouseEvent e) {
  1870. aboutUsPopUp = new AboutUsPopUp(holegJFrame);
  1871. aboutUsPopUp.setVisible(true);
  1872. }
  1873. });
  1874. /**
  1875. * Update of every interaction between the user and the canvas (only on
  1876. * the canvas). Basically the update of all the information concerning
  1877. * the clicked HolonObject. For multi-selection, the propertyTable would
  1878. * be disabled
  1879. */
  1880. canvas.addMouseListener(new MouseAdapter() {
  1881. @Override
  1882. public void mousePressed(MouseEvent e) {
  1883. }
  1884. @Override
  1885. public void mouseReleased(MouseEvent e) {
  1886. holonEleNamesDisplayed = Languages.getLanguage()[25];
  1887. // If any empty space is clicked
  1888. if (temp == null || temp.getId() != model.getSelectedObjectID()) {
  1889. hideScrollGraph();
  1890. elementGraph.setText(Languages.getLanguage()[25]);
  1891. }
  1892. temp = updCon.getActualCps();
  1893. // Erase old data in the PropertyTable
  1894. if (model.getPropertyTable().getRowCount() > 0) {
  1895. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1896. model.getPropertyTable().removeRow(i);
  1897. }
  1898. }
  1899. if (e.isControlDown() && temp != null) {
  1900. if (model.getSelectedCpsObjects().contains(temp)) {
  1901. controller.deleteSelectedObject(temp);
  1902. } else {
  1903. controller.addSelectedObject(temp);
  1904. }
  1905. }
  1906. if (temp instanceof HolonSwitch) {
  1907. showScrollGraph();
  1908. updateUnitGraph((GraphEditable)temp);
  1909. }
  1910. // Write new data in the PropertyTable
  1911. triggerUpdateController(temp);
  1912. // New Tab with NodeOfNode
  1913. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
  1914. && temp instanceof GroupNode) {
  1915. openNewUpperNodeTab();
  1916. try {
  1917. controller.autoSave();
  1918. } catch (IOException e1) {
  1919. e1.printStackTrace();
  1920. }
  1921. }
  1922. if (model.getSelectedCpsObjects().size() > 1) {
  1923. model.getTableHolonElement()
  1924. .setModel(model.getMultiTable());
  1925. } else if (model.getSelectedCpsObjects().size() == 1) {
  1926. model.getTableHolonElement().setModel(
  1927. model.getSingleTable());
  1928. }
  1929. }
  1930. });
  1931. holonCanvas.addMouseListener(new MouseAdapter() {
  1932. @Override
  1933. public void mousePressed(MouseEvent e) {
  1934. hideScrollGraph();
  1935. elementGraph.setText(Languages.getLanguage()[25]);
  1936. if (model.getPropertyTable().getRowCount() > 0) {
  1937. for (int i = model.getPropertyTable().getRowCount() - 1; i > -1; i--) {
  1938. model.getPropertyTable().removeRow(i);
  1939. }
  1940. }
  1941. updCon.deleteRows(model.getMultiTable());
  1942. updCon.deleteRows(model.getSingleTable());
  1943. updCon.paintHolonBody(model.getSelectedHolonBody());
  1944. }
  1945. });
  1946. // Del Button
  1947. btnDel.addActionListener(actionEvent -> {
  1948. Object nodeInfo = tree.getLastSelectedPathComponent();
  1949. if (nodeInfo != null) {
  1950. DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo;
  1951. String nodeName = selectedNode.getUserObject().toString();
  1952. int depthOfNode = selectedNode.getLevel();
  1953. try {
  1954. switch (depthOfNode) {
  1955. case 1:
  1956. int dialogResult = JOptionPane.showConfirmDialog(
  1957. holegJFrame, eraseCategory + nodeName
  1958. + "?", warningText,
  1959. JOptionPane.YES_NO_OPTION);
  1960. if (dialogResult == JOptionPane.YES_OPTION) {
  1961. controller.deleteCategory(nodeName);
  1962. }
  1963. break;
  1964. case 2:
  1965. DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode
  1966. .getParent();
  1967. controller.delObjectCategory(parent.getUserObject()
  1968. .toString(), nodeName);
  1969. break;
  1970. default:
  1971. JOptionPane.showMessageDialog(holegJFrame,
  1972. selectObjBeforeErase);
  1973. }
  1974. } catch (Exception e2) {
  1975. }
  1976. } else {
  1977. JOptionPane.showMessageDialog(holegJFrame,
  1978. selectObjBeforeErase);
  1979. }
  1980. tree.repaint();
  1981. });
  1982. toolBar.add(btnDel);
  1983. holegJFrame.getContentPane().add(splitPane);
  1984. mntmNew.addActionListener(actionEvent -> {
  1985. if (model.getObjectsOnCanvas().size() != 0) {
  1986. int newWarning = JOptionPane.YES_NO_OPTION;
  1987. int dialogForNewWarning = JOptionPane.showConfirmDialog(
  1988. holegJFrame, saveBeforeNew, warningText,
  1989. newWarning);
  1990. if (dialogForNewWarning == JOptionPane.YES_OPTION) {
  1991. mntmSave.doClick();
  1992. }
  1993. }
  1994. model.getEdgesOnCanvas().removeAll(model.getEdgesOnCanvas());
  1995. model.getObjectsOnCanvas().removeAll(model.getObjectsOnCanvas());
  1996. controller.setSelectedObjectID(0);
  1997. controller.setSelecteEdge(null);
  1998. controller.setCurIteration(0);
  1999. hideScrollGraph();
  2000. elementGraph.setText(Languages.getLanguage()[25]);
  2001. canvas.tempCps = null;
  2002. canvas.repaint();
  2003. IdCounter.resetCounter();
  2004. IdCounterElem.resetCounter();
  2005. });
  2006. mntmOpen.addActionListener(new ActionListener() {
  2007. @Override
  2008. public void actionPerformed(ActionEvent evt) {
  2009. menuFileExitActionPerformed();
  2010. }
  2011. private void menuFileExitActionPerformed() {
  2012. JFileChooser fileChooser = new JFileChooser();
  2013. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/exampleNetworks/"));
  2014. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter(
  2015. "Holon Save File(*.holon)", "holon");
  2016. fileChooser.setFileFilter(holonFilter);
  2017. if (fileChooser.showOpenDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
  2018. File file = fileChooser.getSelectedFile();
  2019. try {
  2020. controller.loadFile(file.getAbsolutePath());
  2021. canvas.repaint();
  2022. unitGraph.update(model.getObjectsOnCanvas());
  2023. tree.repaint();
  2024. controller.calculateStateAndVisualForCurrentTimeStep();
  2025. for (JsonObject json : model.getStatisticData()) {
  2026. readStatistics(json);
  2027. }
  2028. } catch (IOException | ArchiveException e) {
  2029. e.printStackTrace();
  2030. JLabel message = new JLabel(
  2031. "The savefile is corrupt and cannot be opened.");
  2032. JOptionPane.showMessageDialog(holegJFrame,
  2033. message, "", JOptionPane.ERROR_MESSAGE);
  2034. }
  2035. }
  2036. }
  2037. });
  2038. mntmSave.addActionListener(new ActionListener() {
  2039. @Override
  2040. public void actionPerformed(ActionEvent evt) {
  2041. menuSaveActionPerformed();
  2042. }
  2043. private void menuSaveActionPerformed() {
  2044. JFileChooser fileChooser = new JFileChooser();
  2045. FileNameExtensionFilter holonFilter = new FileNameExtensionFilter(
  2046. "Holon Save File(*.holon)", "holon");
  2047. fileChooser.setFileFilter(holonFilter);
  2048. if (fileChooser.showSaveDialog(holegJFrame) == JFileChooser.APPROVE_OPTION) {
  2049. File selectedFile = fileChooser.getSelectedFile();
  2050. String fileName = selectedFile.getName();
  2051. String fullPath = fileChooser.getSelectedFile().getPath();
  2052. if (fileChooser.getFileFilter().equals(holonFilter)) {
  2053. if (!fileName.contains("."))
  2054. fullPath += ".holon";
  2055. }
  2056. if (!fullPath.endsWith(".holon")) {
  2057. String suffix = fullPath.substring(fullPath.lastIndexOf("."),
  2058. fullPath.length());
  2059. String[] options = new String[] { "keep .holon",
  2060. "use " + suffix };
  2061. JLabel message = new JLabel(
  2062. "Are you sure to use the extension \"" + suffix
  2063. + "\" instead of \".holon\"?");
  2064. int response = JOptionPane.showOptionDialog(
  2065. holegJFrame, message, "",
  2066. JOptionPane.DEFAULT_OPTION,
  2067. JOptionPane.QUESTION_MESSAGE, null, options,
  2068. options[1]);
  2069. if (response == 0)
  2070. fullPath = fullPath.replace(suffix, ".holon");
  2071. }
  2072. try {
  2073. controller.saveFile(new File(fullPath).getAbsolutePath());
  2074. } catch (IOException | ArchiveException e) {
  2075. e.printStackTrace();
  2076. }
  2077. }
  2078. }
  2079. });
  2080. englishBtn.addActionListener(actionEvent -> {
  2081. Languages.setLanguage(0);
  2082. refreshLanguages();
  2083. updCon.refreshTableProperties(model.getPropertyTable());
  2084. });
  2085. spanishBtn.addActionListener(actionEvent -> {
  2086. Languages.setLanguage(1);
  2087. refreshLanguages();
  2088. updCon.refreshTableProperties(model.getPropertyTable());
  2089. });
  2090. germanBtn.addActionListener(actionEvent -> {
  2091. Languages.setLanguage(2);
  2092. refreshLanguages();
  2093. updCon.refreshTableProperties(model.getPropertyTable());
  2094. });
  2095. czechBtn.addActionListener(actionEvent -> {
  2096. Languages.setLanguage(3);
  2097. refreshLanguages();
  2098. updCon.refreshTableProperties(model.getPropertyTable());
  2099. });
  2100. chineseBtn.addActionListener(actionEvent -> {
  2101. Languages.setLanguage(4);
  2102. refreshLanguages();
  2103. updCon.refreshTableProperties(model.getPropertyTable());
  2104. });
  2105. mntmUndo.addActionListener(new ActionListener() {
  2106. @Override
  2107. public void actionPerformed(ActionEvent evt) {
  2108. menuUndoActionPerformed();
  2109. }
  2110. private void menuUndoActionPerformed() {
  2111. try {
  2112. controller.loadAutoSave(controller.getUndoSave());
  2113. closeInvalidUpperNodeTabs();
  2114. controller.calculateStateAndVisualForCurrentTimeStep();
  2115. canvas.repaint();
  2116. repaintGraphAfterUndoRedo();
  2117. hideScrollGraph();
  2118. } catch (IOException e) {
  2119. e.printStackTrace();
  2120. }
  2121. }
  2122. });
  2123. mntmRedo.addActionListener(new ActionListener() {
  2124. @Override
  2125. public void actionPerformed(ActionEvent evt) {
  2126. menuRedoActionPerformed();
  2127. }
  2128. private void menuRedoActionPerformed() {
  2129. try {
  2130. controller.loadAutoSave(controller.getRedoSave());
  2131. closeInvalidUpperNodeTabs();
  2132. controller.calculateStateAndVisualForCurrentTimeStep();
  2133. canvas.repaint();
  2134. repaintGraphAfterUndoRedo();
  2135. hideScrollGraph();
  2136. } catch (IOException e) {
  2137. e.printStackTrace();
  2138. }
  2139. }
  2140. });
  2141. timePanel = new TimePanel(this,controller);
  2142. timePanel.setBorder(null);
  2143. timePanel.getTimeSlider()
  2144. .addChangeListener(changeEvent -> {
  2145. //TimeSliderChanged event
  2146. controller.calculateStateAndVisualForTimeStep(timePanel.getTimeSlider().getValue());
  2147. unitGraph.repaint();
  2148. if (model.getIsSimRunning()) {
  2149. controller.runAlgorithm(model, controller);
  2150. statSplitPane.repaintGraphs();
  2151. }
  2152. contentPane.updateUI();
  2153. });
  2154. splitPane1.setMinimumSize(new Dimension(0, 25));
  2155. splitPane.setRightComponent(splitPane1);
  2156. splitPane.setDividerLocation(200);
  2157. splitPane1.setDividerLocation(500);
  2158. splitPane.setLeftComponent(scrollPane1);
  2159. tabbedPaneOriginal.addTab("View", tabbedPaneInnerOriginal);
  2160. myPanel.add(canvasSP, BorderLayout.CENTER);
  2161. myPanel.add(lblHint, BorderLayout.PAGE_END);
  2162. lblHint.setBackground(new Color(53, 178, 76, 100));
  2163. lblHint.setOpaque(true);
  2164. tabbedPaneInnerOriginal.addTab("Main Grid", myPanel);
  2165. tabbedPaneOriginal.addTab("Statistics", statScrollPane);
  2166. tabbedPaneOriginal.addTab("Holon", holonCanvas);
  2167. FlexiblePane flexPane = new FlexiblePane(controller);
  2168. controller.setFlexiblePane(flexPane);
  2169. controller.getModel().getObjectListeners().add(flexPane);
  2170. tabbedPaneOriginal.addTab("Flexibility", flexPane);
  2171. splitPane1.setLeftComponent(tabbedPaneOriginal);
  2172. splitPane1.setRightComponent(splitHolonElPro);
  2173. splitPane1.setResizeWeight(0.9);
  2174. splitHolonElPro.setDividerLocation(700);
  2175. // containing the graph and the elements-list
  2176. splitHolonElPro.setTopComponent(splitGraphHolonEl);
  2177. // containing the object's properties
  2178. splitHolonElPro.setBottomComponent(scrollProperties);
  2179. splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
  2180. splitGraphHolonEl.setTopComponent(scrollElements);
  2181. splitGraphHolonEl.setBottomComponent(scrollGraph);
  2182. canvasSP.setViewportView(canvas);
  2183. tabbedPaneOriginal.setBorder(null);
  2184. scrollProperties.setBorder(null);
  2185. scrollGraph.setBorder(null);
  2186. scrollElements.setBorder(null);
  2187. splitPane.setBorder(null);
  2188. splitPane1.setBorder(null);
  2189. splitHolonElPro.setBorder(null);
  2190. splitGraphHolonEl.setBorder(null);
  2191. panelHolonEl.setBorder(null);
  2192. canvasSP.setBorder(null);
  2193. hideScrollGraph();
  2194. tableHolonElementScrollPane.setBorder(null);
  2195. holegJFrame.getContentPane().add(timePanel, BorderLayout.SOUTH);
  2196. try {
  2197. controller.loadAutoSave(System.getProperty("user.home")
  2198. + "/.config/HolonGUI/Category/Category.json");
  2199. } catch (IOException e1) {
  2200. }
  2201. String autoPath = System.getProperty("user.home")
  2202. + "/.config/HolonGUI/Autosave/";
  2203. File dest = new File(autoPath);
  2204. ArrayList<File> oldAutoSaves = controller.filterOldAutoSaveFiles();
  2205. int nrOfOldSaves = oldAutoSaves.size();
  2206. if (nrOfOldSaves > 0) {
  2207. int dialogButton = JOptionPane.YES_NO_OPTION;
  2208. int dialogResult = JOptionPane.showConfirmDialog(holegJFrame,
  2209. "Old autosave file was found, should it be loaded?",
  2210. warningText, dialogButton);
  2211. if (dialogResult == JOptionPane.YES_OPTION) {
  2212. if (dest.exists()) {
  2213. model.setAutoSaveNr(nrOfOldSaves - 1);
  2214. mntmRedo.doClick();
  2215. } else {
  2216. JOptionPane.showMessageDialog(holegJFrame,
  2217. "Autosave could not be loaded.");
  2218. setUpAutoSave(dest);
  2219. }
  2220. } else {
  2221. setUpAutoSave(dest);
  2222. }
  2223. // after all: delete the obsolete/old autosave files from the
  2224. // directory
  2225. controller.deleteObsoleteAutoSaveFiles();
  2226. }
  2227. canvasSP.addComponentListener(new ComponentAdapter() {
  2228. @Override
  2229. public void componentResized(ComponentEvent e) {
  2230. controller.setCanvasX(Math.max(model.getCanvasX(), canvasSP
  2231. .getViewport().getWidth()));
  2232. controller.setCanvasY(Math.max(model.getCanvasY(), canvasSP
  2233. .getViewport().getHeight()));
  2234. canvas.repaint();
  2235. }
  2236. });
  2237. }
  2238. private void initWindowMenu() {
  2239. menuBar.add(menuWindow);
  2240. //Algo
  2241. JMenuItem openMenu = new JMenuItem("Open Algorithm Panel", new ImageIcon(Util.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
  2242. openMenu.addActionListener(actionEvent -> {
  2243. new AddOnWindow(holegJFrame, controller);
  2244. });
  2245. openMenu.setAccelerator(KeyStroke.getKeyStroke('N', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
  2246. menuWindow.add(openMenu);
  2247. //Outliner
  2248. JMenuItem openOutliner = new JMenuItem("Open Outliner", new ImageIcon(Util.loadImage("/Button_Images/iconOutliner.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
  2249. openOutliner.addActionListener(actionEvent -> {
  2250. outlinerList.add(new Outliner(holegJFrame, model, controller));
  2251. });
  2252. openOutliner.setAccelerator(KeyStroke.getKeyStroke('O', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
  2253. menuWindow.add(openOutliner);
  2254. //FlexWindow
  2255. JMenuItem openFlexMenuItem = new JMenuItem("Open Flexibility Panel", new ImageIcon(Util.loadImage("/Button_Images/iconAlgo.png").getScaledInstance(20, 20, java.awt.Image.SCALE_SMOOTH)));
  2256. openFlexMenuItem.addActionListener(actionEvent -> {
  2257. flexList.add(new FlexWindow(holegJFrame, controller));
  2258. });
  2259. openFlexMenuItem.setAccelerator(KeyStroke.getKeyStroke('L', Toolkit.getDefaultToolkit ().getMenuShortcutKeyMask()));
  2260. menuWindow.add(openFlexMenuItem);
  2261. }
  2262. public void updateOutliners(DecoratedState state)
  2263. {
  2264. //remove closed Outliner
  2265. ListIterator<Outliner> iter = outlinerList.listIterator();
  2266. while(iter.hasNext())
  2267. {
  2268. if(iter.next().isClosed) iter.remove();
  2269. }
  2270. //update open Outliner
  2271. for(Outliner out : outlinerList) {
  2272. out.repaintWithDecoratedState(state);
  2273. }
  2274. }
  2275. public void updateFlexWindows()
  2276. {
  2277. //remove closed Outliner
  2278. ListIterator<FlexWindow> iter = flexList.listIterator();
  2279. while(iter.hasNext())
  2280. {
  2281. if(iter.next().isClosed) iter.remove();
  2282. }
  2283. //update open Flex
  2284. for(FlexWindow out : flexList) {
  2285. out.update();
  2286. }
  2287. }
  2288. private void showScrollGraph() {
  2289. scrollGraph.setVisible(true);
  2290. splitGraphHolonEl.setBottomComponent(scrollGraph);
  2291. splitGraphHolonEl.setDividerLocation(distanceBetweenElementsAndGraph);
  2292. }
  2293. private void hideScrollGraph() {
  2294. scrollGraph.setVisible(false);
  2295. splitGraphHolonEl.remove(scrollGraph);
  2296. splitGraphHolonEl.setDividerLocation(0);
  2297. }
  2298. private boolean isUpperPanelInsideBounds() {
  2299. int x = holegJFrame.getX();
  2300. int y = holegJFrame.getY();
  2301. int width = holegJFrame.getWidth();
  2302. // get all connected screen devices
  2303. GraphicsDevice[] screenDevices = GraphicsEnvironment
  2304. .getLocalGraphicsEnvironment().getScreenDevices();
  2305. boolean isUpperPanelVisible = false;
  2306. // and check whether they contain the upper left or upper right point of
  2307. // the frame
  2308. for (GraphicsDevice device : screenDevices) {
  2309. Rectangle bounds = device.getDefaultConfiguration().getBounds();
  2310. if (bounds.contains(x, y) || bounds.contains(x + width, y)) {
  2311. isUpperPanelVisible = true;
  2312. break;
  2313. }
  2314. }
  2315. return isUpperPanelVisible;
  2316. }
  2317. /**
  2318. * Sets up autosave if no old one is loaded at the beginning
  2319. *
  2320. * @param dest
  2321. * path to save-folder
  2322. */
  2323. private void setUpAutoSave(File dest) {
  2324. dest.mkdirs();
  2325. try {
  2326. controller.autoSave();
  2327. } catch (IOException e1) {
  2328. e1.printStackTrace();
  2329. }
  2330. }
  2331. /**
  2332. * adds a specific object type to selected Category also handles input
  2333. * windows and illegal inputs.
  2334. *
  2335. * @param objType
  2336. * type of the Object
  2337. * @param selectedNode
  2338. * The selected Node
  2339. */
  2340. private void addObjectAction(String objType,
  2341. DefaultMutableTreeNode selectedNode) {
  2342. if (selectedNode == null) {
  2343. JOptionPane.showMessageDialog(holegJFrame,
  2344. "Please select a Category first before adding " + objType
  2345. + ".");
  2346. }
  2347. // if selected node is a directory for Categories
  2348. else {
  2349. if (selectedNode.getLevel() == 1) {
  2350. String objname = JOptionPane.showInputDialog(holegJFrame,
  2351. "Please enter a Name for the " + objType);
  2352. Category cat = controller.searchCategory(selectedNode
  2353. .getUserObject().toString());
  2354. if (objname.length() != 0) {
  2355. try {
  2356. switch (objType) {
  2357. case "Switch":
  2358. controller.addSwitch(cat, objname);
  2359. break;
  2360. case "Battery":
  2361. controller.addBattery(cat, objname);
  2362. break;
  2363. }
  2364. } catch (Exception e) {
  2365. }
  2366. }
  2367. } else {
  2368. JOptionPane
  2369. .showMessageDialog(holegJFrame,
  2370. "Objects can not be added to Objects. Please select a Category.");
  2371. }
  2372. }
  2373. }
  2374. /**
  2375. * reloads the Categories from Model.
  2376. *
  2377. * @param categories
  2378. * the current categories
  2379. */
  2380. private void updateCategories(final ArrayList<Category> categories) {
  2381. DefaultTreeModel treemodel = new DefaultTreeModel(new DefaultMutableTreeNode(
  2382. "Categories") {
  2383. private static final long serialVersionUID = 1L;
  2384. {
  2385. DefaultMutableTreeNode node1;
  2386. for (Category c : categories) {
  2387. node1 = new DefaultMutableTreeNode(c.getName());
  2388. for (AbstractCanvasObject obj : c.getObjects()) {
  2389. node1.add(new DefaultMutableTreeNode(obj.getObjName()));
  2390. }
  2391. add(node1);
  2392. }
  2393. }
  2394. });
  2395. tree.setModel(treemodel);
  2396. }
  2397. /**
  2398. * When changes are made to the Categories.
  2399. *
  2400. * @param categories
  2401. * the Categories
  2402. */
  2403. public void onChange(ArrayList<Category> categories) {
  2404. DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
  2405. updateCategories(categories);
  2406. model.reload();
  2407. }
  2408. /**
  2409. * Get the Frame.
  2410. *
  2411. * @return the Frame
  2412. */
  2413. JFrame getFrmCyberPhysical() {
  2414. return holegJFrame;
  2415. }
  2416. private void refreshLanguages() {
  2417. String[] tempArray = Languages.getLanguage();
  2418. // ToolBar
  2419. mnNewMenu.setText(tempArray[0]);
  2420. mntmNew.setText(tempArray[1]);
  2421. mntmOpen.setText(tempArray[2]);
  2422. mntmSave.setText(tempArray[3]);
  2423. mnNewMenuEdit.setText(tempArray[4]);
  2424. mntmUndo.setText(tempArray[5]);
  2425. mntmRedo.setText(tempArray[6]);
  2426. mntmFindReplace.setText(tempArray[7]);
  2427. mntmEditShowedInformation.setText(tempArray[8]);
  2428. mnNewMenuOptions.setText(tempArray[9]);
  2429. mntmResetCategory.setText(tempArray[10]);
  2430. mnNewMenuView.setText(tempArray[11]);
  2431. mntmCanvasSize.setText(tempArray[12]);
  2432. mnHelp.setText(tempArray[13]);
  2433. mntmAboutUs.setText(tempArray[14]);
  2434. mntmEditEdges.setText(tempArray[15]);
  2435. mnLanguage.setText(tempArray[16]);
  2436. canvas.updateLanguages();
  2437. // Tables
  2438. System.arraycopy(tempArray, 17, columnNamesMulti, 0,
  2439. columnNamesMulti.length);
  2440. model.getMultiTable().setColumnIdentifiers(columnNamesMulti);
  2441. System.arraycopy(tempArray, 18, columnNamesSingle, 0,
  2442. columnNamesSingle.length);
  2443. model.getSingleTable().setColumnIdentifiers(columnNamesSingle);
  2444. model.colNames[0] = tempArray[23];
  2445. model.colNames[1] = tempArray[24];
  2446. model.getPropertyTable().setColumnIdentifiers(model.colNames);
  2447. // Graph
  2448. elementGraph.setText(tempArray[25]);
  2449. holonEleNamesDisplayed = tempArray[25];
  2450. resetGraphBtn.setText(tempArray[26]);
  2451. // Warning PopUps
  2452. warningText = tempArray[27];
  2453. saveBeforeNew = tempArray[28];
  2454. eraseCategory = tempArray[29];
  2455. selectObjBeforeErase = tempArray[30];
  2456. // TimePanel
  2457. timePanel.playBtn.setToolTipText(Languages.getLanguage()[89]);
  2458. timePanel.timeResetBtn.setToolTipText(Languages.getLanguage()[90]);
  2459. timePanel.timeForwardBtn.setToolTipText(Languages.getLanguage()[91]);
  2460. timePanel.timeBackwardBtn.setToolTipText(Languages.getLanguage()[92]);
  2461. timePanel.timeSlider.setToolTipText(Languages.getLanguage()[93]);
  2462. // Image Size Slider
  2463. lblImageSize.setText(Languages.getLanguage()[94]);
  2464. }
  2465. /**
  2466. * Checks if a double click was made.
  2467. *
  2468. * @return true if doublecklick, false if not
  2469. */
  2470. private boolean doubleClick() {
  2471. if (click) {
  2472. click = false;
  2473. return true;
  2474. } else {
  2475. click = true;
  2476. Timer t = new Timer("doubleclickTimer", false);
  2477. t.schedule(new TimerTask() {
  2478. @Override
  2479. public void run() {
  2480. click = false;
  2481. }
  2482. }, 350);
  2483. }
  2484. return false;
  2485. }
  2486. /*
  2487. * Open a new Tab with an UpperNodeCanvas
  2488. */
  2489. private void openNewUpperNodeTab() {
  2490. chooseTabTemp();
  2491. JScrollPane scrollPane = getScrollPaneFromTabbedPane();
  2492. if (scrollPane.getViewport().getComponent(0) instanceof MyCanvas) {
  2493. unc = new GroupNodeCanvas(model, controller, unitGraph,
  2494. (GroupNode) temp, "", scrollPane.getViewport().getComponent(0));
  2495. } else {
  2496. unc = new GroupNodeCanvas(model, controller, unitGraph,
  2497. (GroupNode) temp, ((GroupNodeCanvas) scrollPane
  2498. .getViewport().getComponent(0)).path + " -> ", scrollPane.getViewport().getComponent(0));
  2499. }
  2500. unc.setShowedInformation(canvas.getShowedInformation());
  2501. // check if tab already open for clicked NodeOfNode
  2502. boolean dupl = false;
  2503. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  2504. JScrollPane paneOriginal = (JScrollPane) tabbedPaneInnerOriginal
  2505. .getComponentAt(i);
  2506. if (paneOriginal != null
  2507. && ((GroupNodeCanvas) paneOriginal.getViewport()
  2508. .getComponent(0)).upperNode.getId() == temp.getId()) {
  2509. dupl = true;
  2510. // set selected component to view
  2511. tabbedPaneOriginal
  2512. .setSelectedComponent(tabbedPaneInnerOriginal);
  2513. // set selected tab in view to found upper-node-canvas
  2514. tabbedPaneInnerOriginal
  2515. .setSelectedComponent(tabbedPaneInnerOriginal
  2516. .getComponentAt(i));
  2517. }
  2518. if (tabbedPaneSplit.getTabCount() > 0) {
  2519. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
  2520. .getComponentAt(0);
  2521. if (tabbedPaneInnerSplit != null) {
  2522. JScrollPane paneSplit = (JScrollPane) tabbedPaneInnerSplit
  2523. .getComponentAt(i);
  2524. if (!initSplit
  2525. && paneSplit != null
  2526. && ((GroupNodeCanvas) paneSplit.getViewport()
  2527. .getComponent(0)).upperNode.getId() == temp
  2528. .getId()) {
  2529. dupl = true;
  2530. // set selected component to view
  2531. tabbedPaneSplit
  2532. .setSelectedComponent(tabbedPaneInnerSplit);
  2533. // set selected tab in view to found upper-node-canvas
  2534. tabbedPaneInnerSplit
  2535. .setSelectedComponent(tabbedPaneInnerSplit
  2536. .getComponentAt(i));
  2537. }
  2538. }
  2539. }
  2540. // if we found a duplicate, break
  2541. if (dupl) {
  2542. break;
  2543. }
  2544. }
  2545. if (!dupl) {
  2546. unc.setBorder(null);
  2547. unc.setBackground(Color.WHITE);
  2548. unc.setPreferredSize(new Dimension(model.getCanvasX(), model
  2549. .getCanvasY()));
  2550. unc.addMouseListener(new MouseAdapter() {
  2551. @Override
  2552. public void mousePressed(MouseEvent e) {
  2553. hideScrollGraph();
  2554. holonEleNamesDisplayed = Languages.getLanguage()[25];
  2555. elementGraph.setText(holonEleNamesDisplayed);
  2556. chooseTabTemp();
  2557. JScrollPane scrollPane1 = getScrollPaneFromTabbedPane();
  2558. temp = ((GroupNodeCanvas) scrollPane1.getViewport()
  2559. .getComponent(0)).tempCps;
  2560. if (doubleClick() && MouseEvent.BUTTON3 != e.getButton()
  2561. && temp instanceof GroupNode) {
  2562. openNewUpperNodeTab();
  2563. }
  2564. if (temp instanceof HolonSwitch) {
  2565. updateUnitGraph((GraphEditable)temp);
  2566. }
  2567. }
  2568. });
  2569. JScrollPane sp = new JScrollPane(unc);
  2570. sp.setBorder(null);
  2571. // Selected tabbed Pane = tabbedPaneOriginal or tabbedPaneSplit
  2572. if (tabTemp == tabbedPaneOriginal) {
  2573. this.tabbedPaneInnerOriginal.add(temp.getName(), sp);
  2574. this.tabbedPaneInnerOriginal.setSelectedComponent(sp);
  2575. this.tabbedPaneInnerOriginal.setTabComponentAt(
  2576. this.tabbedPaneInnerOriginal.getTabCount() - 1,
  2577. new ButtonTabComponent(this.tabbedPaneInnerOriginal,
  2578. tabbedPaneSplit));
  2579. } else {
  2580. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
  2581. .getComponentAt(0);
  2582. tabbedPaneInnerSplit.add(temp.getName(), sp);
  2583. Component tempC = tabbedPaneInnerSplit.getSelectedComponent();
  2584. tabbedPaneInnerSplit.setComponentAt(
  2585. tabbedPaneInnerSplit.getSelectedIndex(), null);
  2586. tabbedPaneOriginal.setComponentAt(
  2587. tabbedPaneInnerSplit.getSelectedIndex(), tempC);
  2588. tabbedPaneInnerSplit.setSelectedComponent(sp);
  2589. tabbedPaneInnerOriginal.add(temp.getName(), null);
  2590. tabbedPaneInnerOriginal.setTabComponentAt(
  2591. tabbedPaneInnerOriginal.getTabCount() - 1,
  2592. new ButtonTabComponent(tabbedPaneInnerOriginal,
  2593. tabbedPaneInnerSplit));
  2594. }
  2595. temp = null;
  2596. }
  2597. }
  2598. private void updateUpperNodes() {
  2599. for (Component c : tabbedPaneInnerOriginal.getComponents()) {
  2600. if (!(c instanceof JScrollPane)) {
  2601. continue;
  2602. }
  2603. Component pane = ((JScrollPane) c).getViewport().getComponent(0);
  2604. if (pane instanceof GroupNodeCanvas) {
  2605. temp = model.getHashcodeMap()
  2606. .get(((GroupNodeCanvas) pane).code);
  2607. ((GroupNodeCanvas) pane).upperNode = (GroupNode) temp;
  2608. }
  2609. }
  2610. }
  2611. /**
  2612. * Removes UpperNodeTab if UpperNode was deleted
  2613. *
  2614. * @param cps
  2615. * the CPS object that is currently selected
  2616. */
  2617. private void removeUpperNodeTab(AbstractCanvasObject cps) {
  2618. if (cps instanceof GroupNode) {
  2619. boolean splitView = false;
  2620. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  2621. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
  2622. .getComponentAt(i);
  2623. if (scrollPaneOriginal == null) {
  2624. splitView = true;
  2625. } else if (((GroupNodeCanvas) scrollPaneOriginal.getViewport()
  2626. .getComponent(0)).upperNode.getId() == cps.getId()) {
  2627. ((ButtonTabComponent) tabbedPaneInnerOriginal
  2628. .getTabComponentAt(i)).removeTabs();
  2629. break;
  2630. }
  2631. }
  2632. // If SplitView is on and the view on
  2633. // tabbedPaneSplit is the deleted upperNode
  2634. if (splitView && tabbedPaneSplit.getComponentCount() > 0) {
  2635. JTabbedPane tabbedPaneInnerSplit = (JTabbedPane) tabbedPaneSplit
  2636. .getComponentAt(0);
  2637. if (((GroupNodeCanvas) ((JScrollPane) tabbedPaneInnerSplit
  2638. .getSelectedComponent()).getViewport().getComponent(0)).upperNode
  2639. .getId() == cps.getId()) {
  2640. ((ButtonTabComponent) tabbedPaneInnerOriginal
  2641. .getTabComponentAt(tabbedPaneInnerSplit
  2642. .getSelectedIndex())).removeTabs();
  2643. }
  2644. }
  2645. }
  2646. }
  2647. private void readStatistics(JsonObject json) {
  2648. List<String> keys = json.entrySet().stream().map(i -> i.getKey())
  2649. .collect(Collectors.toCollection(ArrayList::new));
  2650. // Saved Values
  2651. JsonObject obj;
  2652. AbstractCanvasObject cps;
  2653. int prop;
  2654. Color color;
  2655. StatisticGraphPanel stat = new StatisticGraphPanel(model, controller,//TODO
  2656. json.get("KEY").getAsString(), model.getGraphTable());
  2657. for (String k : keys) {
  2658. if (!k.equals("KEY")) {
  2659. obj = json.get(k).getAsJsonObject();
  2660. cps = (obj.get("ID") == JsonNull.INSTANCE ? null : controller
  2661. .searchTracked(obj.get("ID").getAsInt()));
  2662. prop = obj.get("PROPERTY").getAsInt();
  2663. color = model.getGson().fromJson(obj.get("COLOR"), Color.class);
  2664. stat.addObject(new TrackedDataSet(cps, prop, color, model.getIterations()));
  2665. }
  2666. model.getGraphTable().put(json.get("KEY").getAsString(), stat);
  2667. model.getStatPanel().getGraphPanel().add(stat);
  2668. }
  2669. }
  2670. /**
  2671. * chooses whether to set the tabTemp to tabbedPaneOriginal or
  2672. * tabbedPaneSplit
  2673. */
  2674. private void chooseTabTemp() {
  2675. // is the uppernode on tabbedPaneOriginal or tabbedPaneSplit
  2676. /* TODO: Fix or Remove SplitView */
  2677. if (tabbedPaneOriginal.getMousePosition() != null || initSplit) {
  2678. tabTemp = tabbedPaneOriginal;
  2679. } else {
  2680. tabTemp = tabbedPaneSplit;
  2681. }
  2682. }
  2683. private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane,
  2684. int index) {
  2685. tabTemp = tabbedPane;
  2686. return getScrollPaneFromTabbedPane(index);
  2687. }
  2688. // private JScrollPane getScrollPaneFromTabbedPane(JTabbedPane tabbedPane) {
  2689. // return getScrollPaneFromTabbedPane(tabbedPane, -1);
  2690. // }
  2691. private JScrollPane getScrollPaneFromTabbedPane() {
  2692. return getScrollPaneFromTabbedPane(-1);
  2693. }
  2694. private JScrollPane getScrollPaneFromTabbedPane(int index) {
  2695. Component upperLevelSelectedComponent;
  2696. if(tabTemp == null)
  2697. {
  2698. return null;
  2699. }
  2700. if (index == -1) {
  2701. upperLevelSelectedComponent = tabTemp.getSelectedComponent();
  2702. } else {
  2703. upperLevelSelectedComponent = tabTemp.getComponentAt(index);
  2704. }
  2705. if (upperLevelSelectedComponent instanceof JTabbedPane) {
  2706. Component nextLevel = ((JTabbedPane) upperLevelSelectedComponent).getSelectedComponent();
  2707. if(nextLevel instanceof JPanel)
  2708. return (JScrollPane) ((JPanel)nextLevel).getComponent(0);
  2709. else
  2710. return (JScrollPane) nextLevel;
  2711. } else if (upperLevelSelectedComponent instanceof JScrollPane) {
  2712. return (JScrollPane) upperLevelSelectedComponent;
  2713. } else {
  2714. return null;
  2715. }
  2716. }
  2717. private void repaintGraphAfterUndoRedo() {
  2718. for (AbstractCanvasObject cps : model.getObjectsOnCanvas()) {
  2719. unitGraph.repaintGraph(cps);
  2720. }
  2721. }
  2722. /**
  2723. * if flexibility was turned on, then active needs to be turned off, the
  2724. * energy currently produced/consumed
  2725. *
  2726. * @param eleBTemp
  2727. * element that needs to be updated
  2728. * @param selectedValueBY
  2729. * the y value in the table
  2730. */
  2731. private void updateElementTableAfterChange(HolonElement eleBTemp,
  2732. int selectedValueBY) {
  2733. // model.getSingleTable().setValueAt(false,
  2734. // selectedValueBY, 6);
  2735. model.getSingleTable().setValueAt(eleBTemp.isActive(), selectedValueBY,
  2736. 5);
  2737. model.getSingleTable().setValueAt(eleBTemp.getAmount(),
  2738. selectedValueBY, 4);
  2739. model.getSingleTable().setValueAt(
  2740. controller.getSimManager().getActualFlexManager().isAFlexInUseOfHolonElement(eleBTemp),
  2741. selectedValueBY, 3);
  2742. model.getSingleTable().setValueAt(eleBTemp.getEnergyPerElement(),
  2743. selectedValueBY, 2);
  2744. }
  2745. public void triggerUpdateController(AbstractCanvasObject temp) {
  2746. if(model != null) { return;}
  2747. if (temp != null) {
  2748. updCon.paintProperties(temp);
  2749. }
  2750. updCon.refreshTableHolonElement(model.getMultiTable(),
  2751. model.getSingleTable());
  2752. updCon.refreshTableProperties(model.getPropertyTable());
  2753. }
  2754. /**
  2755. * Custom Mouse adapter makes contentPane gain focus once mouse leaves this
  2756. * component so copy/paste/cut and "select all" works
  2757. */
  2758. private class FocusCanvasMouseAdapter extends MouseAdapter {
  2759. @Override
  2760. public void mouseExited(MouseEvent e) {
  2761. contentPane.requestFocus();
  2762. }
  2763. }
  2764. /**
  2765. * This Method updates the UnitGraph, saves the old LocalModeState and load the new LocalModeState.
  2766. * @param element The new Element to load the UnitGraph
  2767. */
  2768. private void updateUnitGraph(GraphEditable element){
  2769. //SaveOld LocalMode State.
  2770. if(localPeriodInput.isVisible())
  2771. {
  2772. //Save Old State
  2773. validateInput(localPeriodInput.getEditor().getItem().toString(), false);
  2774. }
  2775. //Update UnitGraph
  2776. unitGraph.initNewElement(element);
  2777. //Load LocalMode State.
  2778. changeLocalPeriodButtonAppeareance(unitGraph.isUsingLocalPeriod());
  2779. localPeriodInput.getEditor().setItem(unitGraph.getLocalPeriod());
  2780. }
  2781. /**
  2782. * Displayed the actual LocalModeState.
  2783. * @param enabled
  2784. */
  2785. private void changeLocalPeriodButtonAppeareance(boolean enabled) {
  2786. localPeriodInput.setVisible(enabled);
  2787. if(enabled)
  2788. {
  2789. localPeriodButtonImage.setImage(Util.loadImage("/Images/Graph.png"));
  2790. }else {
  2791. localPeriodButtonImage.setImage(GrayFilter.createDisabledImage(Util.loadImage("/Images/Graph.png")));
  2792. }
  2793. }
  2794. /**
  2795. * Validate the LocalMode Input and when its valid save on the Element.
  2796. * @param text the inputText to validate.
  2797. * @param bShowMessage when true, open a MessageDialog when text invalid.
  2798. */
  2799. private void validateInput(String text, boolean bShowMessage) {
  2800. int localPeriodInputValue;
  2801. try {
  2802. localPeriodInputValue = Integer.parseInt(text);
  2803. } catch (NumberFormatException e) {
  2804. if(bShowMessage)
  2805. JOptionPane.showMessageDialog(contentPane, '"' +text + '"'+ " is not a valid Input. \n Use whole numbers.");
  2806. return;
  2807. }
  2808. unitGraph.setLocalPeriod(localPeriodInputValue);
  2809. }
  2810. public void updateIterations() {
  2811. this.statSplitPane.updateIterations();
  2812. }
  2813. private void openWebpage(String URL){
  2814. try {
  2815. java.awt.Desktop.getDesktop().browse(new URI(URL));
  2816. } catch (IOException e1) {
  2817. // TODO Auto-generated catch block
  2818. e1.printStackTrace();
  2819. } catch (URISyntaxException e1) {
  2820. // TODO Auto-generated catch block
  2821. e1.printStackTrace();
  2822. }
  2823. }
  2824. /**
  2825. * Function to set the visibility for Hints
  2826. * @param enable true = show false = hide
  2827. */
  2828. public void showHint(boolean enable){
  2829. lblHint.setVisible(enable);
  2830. }
  2831. /**
  2832. * closes all UpperNodeTabs, that don't have a
  2833. * valid UpperNode (e.g. if it was ungrouped/deleted/replaced and so on)
  2834. */
  2835. private void closeInvalidUpperNodeTabs() {
  2836. /**
  2837. * close bugged Tabs
  2838. */
  2839. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  2840. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
  2841. .getComponentAt(i);
  2842. if (((GroupNodeCanvas) scrollPaneOriginal.getViewport()
  2843. .getComponent(0)).upperNode == null) {
  2844. ((ButtonTabComponent) tabbedPaneInnerOriginal
  2845. .getTabComponentAt(i)).removeTabs();
  2846. break;
  2847. }
  2848. }
  2849. }
  2850. public void repaintCanvas() {
  2851. tabbedPaneInnerOriginal.repaint();
  2852. }
  2853. /**
  2854. * Class should be reworked as soon as possible!
  2855. * @param state
  2856. */
  2857. public void guiDisable(boolean state) {
  2858. canvas.disabled = state;
  2859. for (int i = 1; i < tabbedPaneInnerOriginal.getTabCount(); i++) {
  2860. JScrollPane scrollPaneOriginal = (JScrollPane) tabbedPaneInnerOriginal
  2861. .getComponentAt(i);
  2862. if (((GroupNodeCanvas) scrollPaneOriginal.getViewport()
  2863. .getComponent(0)).upperNode != null) {
  2864. ((GroupNodeCanvas) scrollPaneOriginal.getViewport()
  2865. .getComponent(0)).disable = state;
  2866. }
  2867. }
  2868. }
  2869. }