GUI.java 105 KB

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