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