GUI.java 105 KB

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