GUI.java 87 KB

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