GUI.java 89 KB

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