GUI.java 87 KB

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