GUI.java 105 KB

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