package ui.view; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.border.LineBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import Interfaces.CategoryListener; import classes.Category; import classes.CpsEdge; import classes.CpsObject; import classes.HolonElement; import classes.HolonObject; import classes.HolonSwitch; import classes.HolonTransformer; import ui.controller.Control; import ui.model.Model;; public class GUI implements CategoryListener { private JFrame frmCyberPhysical; private final JMenuBar menuBar = new JMenuBar(); private final JMenu mnNewMenu = new JMenu("File"); private final JMenu mnNewMenu_1 = new JMenu("Edit"); private final JMenu mnNewMenu_2 = new JMenu("Options"); private final JMenu mnNewMenu_3 = new JMenu("View"); private final JMenu mnHelp = new JMenu("Help"); private final JMenuItem mntmOpen = new JMenuItem("Open"); private final JMenuItem mntmNew = new JMenuItem("New"); private final JMenuItem mntmSave = new JMenuItem("Save"); private final JMenuItem aboutUs = new JMenuItem("About Us"); private final JMenuItem canvasSize = new JMenuItem("View Size"); private final JSplitPane splitPane = new JSplitPane(); private final JSplitPane splitPane_1 = new JSplitPane(); private final JScrollPane scrollPane_1 = new JScrollPane(); private final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); private final JScrollPane scrollPane_2 = new JScrollPane(); private JPopupMenu popmenuEdit = new JPopupMenu(); private JMenuItem editItem = new JMenuItem("Edit Object"); private String catOfObjToBeEdited; private final JLabel maxGraph = new JLabel("100%"); private final JLabel medGraph = new JLabel("50%"); private final JLabel minGraph = new JLabel("0%"); private final JLabel elementGraph = new JLabel("None "); private final ArrayList selectedElements = new ArrayList(); private String holonEleNamesDisplayed = "None "; private final JTree tree = new JTree(); private final JEditorPane dtrpnHereWillBe = new JEditorPane(); /****************************************** ************* Right Container************* ******************************************/ // Right Container: here comes the information about the HolonObject, such // as HolonElements Information, Properties and Consumption/Production graph private final JSplitPane split_HolonEl_Pro = new JSplitPane(JSplitPane.VERTICAL_SPLIT); private final JSplitPane split_Graph_HolonEl = new JSplitPane(JSplitPane.VERTICAL_SPLIT); // In this section are all the Holonelements that correspond to the clicked // HolonObject with consumption/production, name and amount. private JTable tableHolonElement = new JTable(); private PropertyTable tableModelHolonElement = new PropertyTable(); private final JPanel scrollElements = new JPanel(); private JScrollPane tableHolonElementScrollPane = new JScrollPane(); // In this section are all the properties that correspond to the clicked // HolonObject, such as connections, name, Type, etc. private JTable tableProperties = new JTable(); private JPanel graphLabel = new JPanel(); private DefaulTable tableModelProperties; private final JScrollPane scrollProperties = new JScrollPane(); // In this section is the graph for the selected HolonElement of the clicked // HolonObject private JTable tableGraph = new JTable(); private DefaultTableModel tableModelGraph = new DefaultTableModel(); private final JScrollPane scrollGraph = new JScrollPane(); private Model model; private final Control controller; // Pop up Windows private AddObjectPopUp addObjectPopUP; private AboutUsPopUp aboutUsPopUp; private AddElementPopUp addElementPopUp; private final JPanel panel = new JPanel(); private final JPanel panel_HolonEl = new JPanel(); private final JComboBox comboBox = new JComboBox(); // private final JComboBox comboBoxGraph = new JComboBox(); // Buttons private final JButton btnAdd = new JButton("+"); private final JButton btnDel = new JButton("-"); private final JButton btnAddHolEL = new JButton("+"); private final JButton btnDelHolEL = new JButton("-"); private final JButton resetGraphBtn = new JButton("Reset"); private final JToolBar toolBar = new JToolBar(); private final JToolBar toolBarHolonEl = new JToolBar(); private final JToolBar toolBarGraph = new JToolBar(); // variables private boolean dragging = false; private String actualObjectClicked; private Image img = null; private CpsObject tempCps = null; private HolonElement tempElement = null; private int yValueElements = 0; private MyCanvas canvas; private UnitGraph unitGraph; private final JSplitPane splitPane_3 = new JSplitPane(); private final JSlider sizeSlider = new JSlider(); private final JLabel lblImageSize = new JLabel("Image Size"); // Time Stuff private TimePanel timePanel; private final JMenu mnAlgorithm = new JMenu("Algorithm"); private final JCheckBoxMenuItem chckbxmntmUseAlgorithm = new JCheckBoxMenuItem("Use Algorithm"); private final JSplitPane splitPane_2 = new JSplitPane(); private final JLabel lblSelect = new JLabel("Select"); private final JComboBox comboBoxAlgo = new JComboBox(); private int yTHIS; private int xTHIS; private int yBTHIS; private int xBTHIS; private CpsObject temp = null; private final JButton btnTest = new JButton("test"); private final JMenuItem mntmUndo = new JMenuItem("Undo"); private final JMenuItem mntmRedo = new JMenuItem("Redo"); /** * Create the application. */ public GUI(Control control) { this.controller = control; this.model = control.getModel(); this.canvas = new MyCanvas(model, control); this.unitGraph = new UnitGraph(model, control); control.initListener(this); initialize(); updateCategories(model.getCategories()); controller.setCanvas(canvas); } /** * Initialize the contents of the frame. */ @SuppressWarnings({ "serial", "unchecked" }) private void initialize() { frmCyberPhysical = new JFrame(); frmCyberPhysical.setTitle("Cyber Physical Systems Model"); frmCyberPhysical.setBounds(100, 100, 1000, 800); // frmCyberPhysical.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frmCyberPhysical.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { if (JOptionPane.showConfirmDialog(frmCyberPhysical, "Are you sure to close this window?", "Really Closing?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION) { deleteDirectory(new File(System.getProperty("user.home") + "/HolonGUI/Autosave")); System.exit(0); } } private void deleteDirectory(File path) { if (path.exists()) { File[] files = path.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } } }); frmCyberPhysical.setJMenuBar(menuBar); frmCyberPhysical.setIconImage(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage() .getScaledInstance(30, 30, Image.SCALE_SMOOTH)); menuBar.add(mnNewMenu); mnNewMenu.add(mntmNew); mnNewMenu.add(mntmOpen); mnNewMenu.add(mntmSave); menuBar.add(mnNewMenu_1); mnNewMenu_1.add(mntmUndo); mnNewMenu_1.add(mntmRedo); menuBar.add(mnNewMenu_2); menuBar.add(mnNewMenu_3); mnNewMenu_3.add(canvasSize); canvasSize.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPanel myPanel = new JPanel(); JTextField field1 = new JTextField("" + canvas.getWidth() + ""); JTextField field2 = new JTextField("" + canvas.getHeight() + ""); myPanel.add(field1); myPanel.add(field2); JOptionPane.showMessageDialog(null, myPanel); canvas.setPreferredSize( new Dimension(Integer.parseInt(field1.getText()), Integer.parseInt(field2.getText()))); canvas.repaint(); } }); mnNewMenu_3.add(splitPane_3); sizeSlider.setMinimum(15); sizeSlider.setMaximum(115); sizeSlider.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { controller.setScale(sizeSlider.getValue()); tree.setRowHeight(model.getScale()); canvas.objectSelectionHighlighting(); canvas.repaint(); } }); splitPane_3.setRightComponent(sizeSlider); splitPane_3.setLeftComponent(lblImageSize); menuBar.add(mnHelp); mnHelp.add(aboutUs); menuBar.add(mnAlgorithm); mnAlgorithm.add(chckbxmntmUseAlgorithm); mnAlgorithm.add(splitPane_2); splitPane_2.setLeftComponent(lblSelect); splitPane_2.setRightComponent(comboBoxAlgo); canvas.setBackground(Color.WHITE); canvas.setPreferredSize(new Dimension(1000, 1000)); JScrollPane canvasSP = new JScrollPane(canvas); canvasSP.setBorder(null); tabbedPane.addTab("Modeling", new ImageIcon(new ImageIcon(this.getClass().getResource("/Images/home.png")) .getImage().getScaledInstance(30, 30, Image.SCALE_SMOOTH)), canvasSP, "Model a CPS"); tabbedPane.addTab("Simulation", new ImageIcon(new ImageIcon(this.getClass().getResource("/Images/Dummy_House.png")).getImage() .getScaledInstance(30, 30, Image.SCALE_SMOOTH)), scrollPane_2, "Simulate the CPS"); dtrpnHereWillBe.setText("Here will be the Simulation"); scrollPane_2.setViewportView(dtrpnHereWillBe); /******************** * RIGHT CONTAINER (INFORMATION) **********************/ // Set up of the HolonElements section Object[] columnNames = { "Device", "Energy", "Quantity", "Activated" }; tableModelHolonElement.setColumnIdentifiers(columnNames); tableHolonElement.setBorder(null); tableHolonElement.setModel(tableModelHolonElement); tableHolonElement.setFillsViewportHeight(true); tableHolonElement.setCellSelectionEnabled(true); tableHolonElement.setColumnSelectionAllowed(true); tableHolonElementScrollPane.setViewportView(tableHolonElement); scrollElements.setLayout(new BorderLayout(0, 0)); scrollElements.add(panel_HolonEl, BorderLayout.NORTH); scrollElements.add(tableHolonElementScrollPane); panel_HolonEl.setLayout(new BoxLayout(panel_HolonEl, BoxLayout.X_AXIS)); toolBarHolonEl.add(btnAddHolEL); toolBarHolonEl.add(btnDelHolEL); toolBarHolonEl.setFloatable(false); panel_HolonEl.add(toolBarHolonEl); // Set up of the Properties section Object[] colNames = { "Field", "Information" }; tableModelProperties = new DefaulTable(100, colNames.length); tableModelProperties.setColumnIdentifiers(colNames); tableProperties.setModel(tableModelProperties); tableProperties.setFillsViewportHeight(true); tableProperties.setCellSelectionEnabled(true); tableProperties.setColumnSelectionAllowed(true); scrollProperties.setViewportView(tableProperties); // Set up of the Graph section Object[] tempText = { "Here comes the graph for each clicked HolonElement" }; tableModelGraph.setColumnIdentifiers(tempText); tableGraph.setModel(tableModelGraph); tableGraph.setFillsViewportHeight(true); tableGraph.setCellSelectionEnabled(true); tableGraph.setColumnSelectionAllowed(true); scrollGraph.setViewportView(unitGraph); graphLabel.setLayout(new BorderLayout(0, 10)); graphLabel.add(maxGraph, BorderLayout.NORTH); graphLabel.add(medGraph, BorderLayout.CENTER); graphLabel.add(minGraph, BorderLayout.SOUTH); toolBarGraph.add(elementGraph); toolBarGraph.add(resetGraphBtn); toolBarGraph.setFloatable(false); scrollGraph.setRowHeaderView(graphLabel); scrollGraph.setColumnHeaderView(toolBarGraph); /*********************** * HolonElement Table Actions **********************/ /* * Add HolonElement to given HolonObject */ btnAddHolEL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { CpsObject tempCpsObject = getActualCps(); if (tempCpsObject != null && tempCpsObject.getClass() == HolonObject.class && tempCpsObject.getID() != 0) { addElementPopUp = new AddElementPopUp(); addElementPopUp.setActualCps(getActualCps()); addElementPopUp.setVisible(true); HolonElement ele = addElementPopUp.getElement(); controller.addElementCanvasObject(tempCpsObject.getID(), ele.getEleName(), ele.getAmount(), ele.getEnergy()); refreshTableHolonElement(); refreshTableProperties(); controller.calculateStateForTimeStep(model.getCurIteration()); } } }); /* * Delete the choosen HolonElement of the selected HolonObject */ btnDelHolEL.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (getActualCps().getClass() == HolonObject.class) { HolonObject obj = (HolonObject) getActualCps(); tempElement = getActualHolonElement(obj, yValueElements); if (tempElement != null && obj.getClass() == HolonObject.class && obj.getID() != 0) { controller.deleteElementCanvas(obj.getID(), tempElement.getEleName()); refreshTableHolonElement(); refreshTableProperties(); controller.calculateStateForTimeStep(model.getCurIteration()); } } } }); /* * Communication between HolonElement Table and displayed Graph */ tableHolonElement.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { HolonObject obj = (HolonObject) getActualCps(); yValueElements = e.getY(); HolonElement ele = getActualHolonElement(obj, yValueElements); if (e.isControlDown() && ele != null) { if (!selectedElements.contains(ele)) { selectedElements.add(ele); if (!holonEleNamesDisplayed.equals("None ")) { holonEleNamesDisplayed = holonEleNamesDisplayed + "; " + ele.getEleName() + " "; } else { holonEleNamesDisplayed = ele.getEleName() + " "; } unitGraph.repaintWithNewElement(selectedElements); } } else if (ele != null) { selectedElements.clear(); selectedElements.add(ele); holonEleNamesDisplayed = ele.getEleName() + " "; unitGraph.repaintWithNewElement(selectedElements); } else { elementGraph.setText("None "); unitGraph.empty(); } // if any HolonElement is double-clicked --> Edit instance of // selected HolonElement if (e.getClickCount() == 2) { yTHIS = e.getY(); xTHIS = e.getX(); } if (e.getClickCount() == 1 && ele == null) { selectedElements.clear(); holonEleNamesDisplayed = "None "; } for (int i = 0; i < selectedElements.size(); i++) { if (i == 0) { System.out.println("Selected Items: " + selectedElements.get(i).getEleName()); } else { System.out.println(selectedElements.get(i).getEleName()); } } elementGraph.setText(holonEleNamesDisplayed); yBTHIS = e.getY(); xBTHIS = e.getX(); } }); /* * If the HolonElement Table enters to editing instance, than is the * propertyChangeListener triggered */ tableHolonElement.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { try { int yMouse = yTHIS; int yBMouse = yBTHIS; int selectedValueX = (int) Math.floor(xTHIS / (tableHolonElement.getWidth() / 4)); int selectedValueY = (int) Math.floor(yMouse / 16); int selectedValueBX = (int) Math.floor(xBTHIS / (tableHolonElement.getWidth() / 4)); int selectedValueBY = (int) Math.floor(yBMouse / 16); if (getActualCps() != null && getActualCps().getClass() == HolonObject.class) { if (selectedValueBX == 3) { HolonElement eleBTemp = getActualHolonElement((HolonObject) getActualCps(), yBMouse); String newBStuff = tableModelHolonElement.getValueAt(selectedValueBY, selectedValueBX) .toString(); Boolean bTemp = Boolean.parseBoolean(newBStuff); eleBTemp.setActive(bTemp); } else { HolonElement eleTemp = getActualHolonElement((HolonObject) getActualCps(), yMouse); String newStuff = tableModelHolonElement.getValueAt(selectedValueY, selectedValueX) .toString(); if (selectedValueX == 0) { eleTemp.setEleName(newStuff); } else if (selectedValueX == 1) { Float ftemp = Float.parseFloat(newStuff); eleTemp.setEnergy(ftemp); } else if (selectedValueX == 2) { Integer iTemp = Integer.parseInt(newStuff); eleTemp.setAmount(iTemp); } } refreshTableProperties(); tableModelHolonElement.fireTableDataChanged(); controller.calculateStateForTimeStep(model.getCurIteration()); unitGraph.repaint(); } } catch (Exception e) { } } }); /*********************** * HolonElement Properties Actions **********************/ /* * If any value at the Properties Table enters to editing instance, than * is PropertyChangeListener triggered (For HolonObject, the only value * to be edited is the name and for CpsEdge the Max.flow) */ tableProperties.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { try { Object temp; if (getActualCps() != null) { if (getActualCps() instanceof HolonObject) { temp = tableModelProperties.getValueAt(0, 1); getActualCps().setName(temp.toString()); } else if (getActualCps() instanceof HolonTransformer) { // get Info of the Properties for Transformer } } else { temp = tableModelProperties.getValueAt(2, 1); Float ftemp = Float.parseFloat(temp.toString()); model.getSelectedEdge().setCapacity(ftemp); } canvas.repaint(); } catch (Exception e) { } } }); /*********************** * HolonElement Graph Actions **********************/ /* * Reset the graph of the selected HolonElement */ resetGraphBtn.setBorder(new LineBorder(Color.BLACK)); resetGraphBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { unitGraph.reset(); } }); /***************************** * RIGHT CONTAINER DONE *****************************/ frmCyberPhysical.getContentPane().setLayout(new BorderLayout(0, 0)); TreeCellRenderer customRenderer = new TreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel label = new JLabel(); Image imgR = null; if (leaf) { for (Category cat : model.getCategories()) { for (CpsObject cps : cat.getObjects()) { if (value.toString().compareTo(cps.getObjName()) == 0) { File checkPath = new File(cps.getImage()); if (checkPath.exists()) { imgR = new ImageIcon(cps.getImage()).getImage().getScaledInstance( controller.getScale(), controller.getScale(), java.awt.Image.SCALE_SMOOTH); } else { imgR = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage() .getScaledInstance(controller.getScale(), controller.getScale(), java.awt.Image.SCALE_SMOOTH); } if (imgR != null) { label.setIcon(new ImageIcon(imgR)); } label.setText(cps.getName()); } } } } tree.setRowHeight(model.getScale()); if (hasFocus) { label.setForeground(new Color(0, 0, 255)); label.setOpaque(true); } if (label.getText().length() == 0) { label.setText(value.toString()); if (value.toString().compareTo("Categories") != 0) { label.setIcon(new ImageIcon(this.getClass().getResource("/Images/folder.png"))); } } return label; } }; tree.setCellRenderer(customRenderer); tree.addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent e) { try { if (dragging) { int x = (int) canvas.getMousePosition().getX(); int y = (int) canvas.getMousePosition().getY(); CpsObject h = null; if (tempCps.getClass() == HolonObject.class) { h = new HolonObject(tempCps); } if (tempCps.getClass() == HolonSwitch.class) { h = new HolonSwitch(tempCps); } if (tempCps.getClass() == HolonTransformer.class) { h = new HolonTransformer(tempCps); } h.setPosition(x, y); controller.addObjectCanvas(h); canvas.repaint(); dragging = false; } } catch (Exception e2) { } frmCyberPhysical.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); popmenuEdit.add(editItem); editItem.setEnabled(false); editItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); tree.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { try { actualObjectClicked = tree.getPathForLocation(e.getX(), e.getY()).getLastPathComponent().toString(); // if an Object was selected, the porperties are shown in // the table DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree .getPathForLocation(e.getX(), e.getY()).getLastPathComponent(); if (selectedNode.getLevel() == 2) { CpsObject selected = controller.searchCategoryObject(selectedNode.getParent().toString(), selectedNode.toString()); deleteRows(); // if (selected instanceof HolonObject && selected != // null) { // selected = (HolonObject) selected; // fillElementTable(((HolonObject) // selected).getElements()); // } } if (SwingUtilities.isRightMouseButton(e)) { for (Category cat : model.getCategories()) { for (CpsObject cps : cat.getObjects()) { if (actualObjectClicked.compareTo(cps.getObjName()) == 0 && !(cps instanceof HolonSwitch)) { editItem.setEnabled(true); popmenuEdit.show(e.getComponent(), e.getX(), e.getY()); catOfObjToBeEdited = selectedNode.getParent().toString(); tempCps = cps; } } } } else { for (Category cat : model.getCategories()) { for (CpsObject cps : cat.getObjects()) { if (actualObjectClicked.compareTo(cps.getObjName()) == 0) { File checkPath = new File(cps.getImage()); if (checkPath.exists()) { img = new ImageIcon(cps.getImage()).getImage().getScaledInstance( controller.getScale(), controller.getScale(), java.awt.Image.SCALE_SMOOTH); } else { img = new ImageIcon(this.getClass().getResource(cps.getImage())).getImage() .getScaledInstance(controller.getScale(), controller.getScale(), java.awt.Image.SCALE_SMOOTH); } tempCps = cps; dragging = true; Cursor cursor = Toolkit.getDefaultToolkit().createCustomCursor(img, new Point(0, 0), "Image"); frmCyberPhysical.setCursor(cursor); } } } } } catch (Exception e2) { } } }); editItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // Remove the selected Object object addObjectPopUP = new AddObjectPopUp(true, tempCps, catOfObjToBeEdited); addObjectPopUP.setCategory(catOfObjToBeEdited); addObjectPopUP.setController(controller); addObjectPopUP.setVisible(true); } }); scrollPane_1.setViewportView(tree); scrollPane_1.setColumnHeaderView(panel); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); toolBar.setFloatable(false); panel.add(toolBar); toolBar.add(comboBox); comboBox.setModel(new DefaultComboBoxModel(new String[] { "Category", "Object", "Transformer", "Switch" })); // Add Button btnAdd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Object nodeInfo = tree.getLastSelectedPathComponent(); String selectedOption = comboBox.getSelectedItem().toString(); DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo; switch (selectedOption) { case "Category": String catName = JOptionPane.showInputDialog("Please enter a Name for Category "); if (catName.length() != 0) { controller.addCategory(catName); } break; case "Object": if (selectedNode == null) { JOptionPane.showMessageDialog(new JFrame(), "Please select a Category first before adding " + selectedOption + "."); } if (selectedNode.getLevel() == 1) { CpsObject tmp = new HolonObject(""); addObjectPopUP = new AddObjectPopUp(false, tmp, null); addObjectPopUP.setVisible(true); addObjectPopUP.setController(controller); addObjectPopUP.setCategory(selectedNode.toString()); } break; default: addObjectAction(selectedOption, selectedNode); break; } tree.repaint(); } }); /** * Pop up - About Us with some important information about the * developers, source and programming stuff */ aboutUs.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { aboutUsPopUp = new AboutUsPopUp(); aboutUsPopUp.setVisible(true); } }); /** * Update of every interaction between the user and the canvas (only on * the canvas). Basically the update of all the information concerning * the clicked HolonObject */ canvas.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (temp == null || temp.getID() != model.getSelectedObjectID()) { unitGraph.empty(); elementGraph.setText("None "); } temp = getActualCps(); // Update of the Information about the HolonElements - only for // if (temp instanceof HolonObject) { // refreshTableHolonElement(); // } // Update of the Information about the Properties - only for // CpsObjects // Erase old data if (tableModelProperties.getRowCount() > 0) { for (int i = tableModelProperties.getRowCount() - 1; i > -1; i--) { tableModelProperties.removeRow(i); } } // Write new data if (temp != null) { Object[] tempName = { "Name", temp.getName() }; tableModelProperties.addRow(tempName); Object[] tempId = { "ID", temp.getID() }; tableModelProperties.addRow(tempId); if (temp instanceof HolonObject) { refreshTableHolonElement(); Object[] tempEnergy = { "Total Energy", ((HolonObject) temp).getCurrentEnergy() }; tableModelProperties.addRow(tempEnergy); } else if (temp instanceof HolonTransformer) { deleteRows(); Object[] tempRatioPerc = { "Ratio Type", true }; tableModelProperties.addRow(tempRatioPerc); } else if (temp instanceof HolonSwitch) { deleteRows(); Object[] tempActive = { "Active", ((HolonSwitch) temp).getActiveAt()[model.getCurIteration()] }; tableModelProperties.addRow(tempActive); unitGraph.repaintWithNewSwitch((HolonSwitch) temp); elementGraph.setText(temp.getName()); } else { deleteRows(); } tableModelProperties.setCellEditable(0, 1, true); tableModelProperties.setCellEditable(2, 1, false); ArrayList temp_array = temp.getConnections(); if (!temp_array.isEmpty()) { boolean first = true; for (CpsEdge temp2 : temp_array) { if (first) { first = false; if (temp.getID() != temp2.getA().getID()) { Object[] tempConnection = { temp.getName() + " is connected to", temp2.getA().getName() + " with ID: " + temp2.getA().getID() }; tableModelProperties.addRow(tempConnection); } else { Object[] tempConnection = { temp.getName() + " is connected to", temp2.getB().getName() + " with ID: " + temp2.getB().getID() }; tableModelProperties.addRow(tempConnection); } } else { if (temp.getID() != temp2.getA().getID()) { Object[] tempConnection = { "", temp2.getA().getName() + " with ID: " + temp2.getA().getID() }; tableModelProperties.addRow(tempConnection); } else { Object[] tempConnection = { "", temp2.getB().getName() + " with ID: " + temp2.getB().getID() }; tableModelProperties.addRow(tempConnection); } } } } } else if (model.getSelectedEdge() != null) { Object[] tempName = { "Name", "Edge: " + model.getSelectedEdge().getA().getName() + " to " + model.getSelectedEdge().getB().getName() }; tableModelProperties.addRow(tempName); Object[] tempFlow = { "Current flow", model.getSelectedEdge().getFlow() }; tableModelProperties.addRow(tempFlow); Object[] tempCapacity = { "Max. Capacity", model.getSelectedEdge().getCapacity() }; tableModelProperties.addRow(tempCapacity); tableModelProperties.setCellEditable(0, 1, false); tableModelProperties.setCellEditable(2, 1, true); } else if (getActualCps() == null) { deleteRows(); } } }); toolBar.add(btnAdd); // Del Button btnDel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { Object nodeInfo = tree.getLastSelectedPathComponent(); if (nodeInfo != null) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) nodeInfo; String nodeName = selectedNode.getUserObject().toString(); int depthOfNode = selectedNode.getLevel(); switch (depthOfNode) { case 1: int dialogResult = JOptionPane.showConfirmDialog(null, "Do you realy want to delete the Category " + nodeName + "?", "Warning", JOptionPane.YES_NO_OPTION); if (dialogResult == JOptionPane.YES_OPTION) { controller.deleteCategory(nodeName); } break; case 2: DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent(); controller.delObjectCategory(parent.getUserObject().toString(), nodeName); break; default: JOptionPane.showMessageDialog(new JFrame(), "Please select a Category or an Object in order to delete something."); } } else { JOptionPane.showMessageDialog(new JFrame(), "Please select a Category or an Object in order to delete something."); } tree.repaint(); } }); toolBar.add(btnDel); frmCyberPhysical.getContentPane().add(splitPane); mntmNew.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { model.getEdgesOnCanvas().removeAll(model.getEdgesOnCanvas()); model.getObjectsOnCanvas().removeAll(model.getObjectsOnCanvas()); controller.setSelectedObjectID(0); controller.setSelecteEdge(null); controller.setCurIteration(0); unitGraph.empty(); elementGraph.setText("None "); canvas.tempCps = null; canvas.objectSelectionHighlighting(); canvas.repaint(); } }); mntmOpen.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { menuFileExitActionPerformed(evt); } private void menuFileExitActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fileChooser = new JFileChooser(); JFrame test = new JFrame(); FileNameExtensionFilter jsonFilter = new FileNameExtensionFilter("*.json", "json"); fileChooser.setFileFilter(jsonFilter); if (fileChooser.showOpenDialog(test) == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); try { controller.loadFile(file.getAbsolutePath()); canvas.repaint(); ArrayList tempList = new ArrayList<>(); for (CpsObject cps : model.getObjectsOnCanvas()) { if (cps instanceof HolonObject) { for (HolonElement h : ((HolonObject) cps).getElements()) { tempList.add(h); unitGraph.repaintWithNewElement(tempList); unitGraph.fillArrayofValue(); tempList.remove(0); } } else if (cps instanceof HolonSwitch) { unitGraph.repaintWithNewSwitch((HolonSwitch) cps); unitGraph.fillArrayofBooleans(); } } unitGraph.empty(); tree.repaint(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); mntmSave.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { menuSaveActionPerformed(evt); } private void menuSaveActionPerformed(java.awt.event.ActionEvent evt) { JFileChooser fileChooser = new JFileChooser(); JFrame test = new JFrame(); FileNameExtensionFilter jsonFilter = new FileNameExtensionFilter("*.json", "json"); fileChooser.setFileFilter(jsonFilter); if (fileChooser.showSaveDialog(test) == JFileChooser.APPROVE_OPTION) { String file = fileChooser.getSelectedFile().getPath(); if (!file.endsWith(".json")) file += ".json"; try { controller.saveFile(new File(file).getAbsolutePath()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }); mntmUndo.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { menuUndoActionPerformed(evt); } private void menuUndoActionPerformed(java.awt.event.ActionEvent evt) { try { controller.loadFile(controller.getUndoSave()); canvas.repaint(); ArrayList tempList = new ArrayList<>(); for (CpsObject cps : model.getObjectsOnCanvas()) { if (cps instanceof HolonObject) { for (HolonElement h : ((HolonObject) cps).getElements()) { tempList.add(h); unitGraph.repaintWithNewElement(tempList); unitGraph.fillArrayofValue(); tempList.remove(0); } } else if (cps instanceof HolonSwitch) { unitGraph.repaintWithNewSwitch((HolonSwitch) cps); unitGraph.fillArrayofBooleans(); } } unitGraph.empty(); tree.repaint(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); mntmRedo.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent evt) { menuUndoActionPerformed(evt); } private void menuUndoActionPerformed(java.awt.event.ActionEvent evt) { try { controller.loadFile(controller.getRedoSave()); canvas.repaint(); ArrayList tempList = new ArrayList<>(); for (CpsObject cps : model.getObjectsOnCanvas()) { if (cps instanceof HolonObject) { for (HolonElement h : ((HolonObject) cps).getElements()) { tempList.add(h); unitGraph.repaintWithNewElement(tempList); unitGraph.fillArrayofValue(); tempList.remove(0); } } else if (cps instanceof HolonSwitch) { unitGraph.repaintWithNewSwitch((HolonSwitch) cps); unitGraph.fillArrayofBooleans(); } } unitGraph.empty(); tree.repaint(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); timePanel = new TimePanel(model, controller); timePanel.setBorder(null); ((JSlider) (timePanel.getComponent(1))).addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { int i = model.getCurIteration(); controller.calculateStateForTimeStep(i); unitGraph.repaint(); } }); splitPane.setRightComponent(splitPane_1); splitPane.setDividerLocation(200); splitPane_1.setDividerLocation(500); splitPane.setLeftComponent(scrollPane_1); splitPane_1.setLeftComponent(tabbedPane); splitPane_1.setRightComponent(split_HolonEl_Pro); split_HolonEl_Pro.setDividerLocation(400); split_HolonEl_Pro.setTopComponent(split_Graph_HolonEl); split_HolonEl_Pro.setBottomComponent(scrollProperties); split_Graph_HolonEl.setDividerLocation(150); split_Graph_HolonEl.setTopComponent(scrollGraph); split_Graph_HolonEl.setBottomComponent(scrollElements); tabbedPane.setBorder(null); scrollProperties.setBorder(null); scrollGraph.setBorder(null); scrollElements.setBorder(null); splitPane.setBorder(null); splitPane_1.setBorder(null); split_HolonEl_Pro.setBorder(null); split_Graph_HolonEl.setBorder(null); scrollPane_2.setBorder(null); panel_HolonEl.setBorder(null); tableHolonElementScrollPane.setBorder(null); frmCyberPhysical.getContentPane().add(timePanel, BorderLayout.SOUTH); } /* * adds a specific object type to selected Category also handles input * windows and illegal inputs */ public void addObjectAction(String objType, DefaultMutableTreeNode selectedNode) { if (selectedNode == null) { JOptionPane.showMessageDialog(new JFrame(), "Please select a Category first before adding " + objType + "."); } // if selected node is a directory for Categories else { if (selectedNode.getLevel() == 1) { String objname = JOptionPane.showInputDialog("Please enter a Name for the " + objType); Category cat = controller.searchCategory(selectedNode.getUserObject().toString()); if (objname.length() != 0) { switch (objType) { case "Switch": controller.addSwitch(cat, objname); break; case "Transformer": controller.addTransformer(cat, objname); break; } } } else { JOptionPane.showMessageDialog(new JFrame(), "Objects can not be added to Objects. Please select a Category."); } } } /** * reloads the Categories from Model */ public void updateCategories(final ArrayList categories) { tree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Categories") { { DefaultMutableTreeNode node_1; for (Category c : categories) { node_1 = new DefaultMutableTreeNode(c.getName()); // kann eventuell umgeƤndert werden for (CpsObject obj : c.getObjects()) { node_1.add(new DefaultMutableTreeNode(obj.getObjName())); } add(node_1); } } })); } /** * */ public void onChange(ArrayList categories) { DefaultTreeModel model = (DefaultTreeModel) tree.getModel(); updateCategories(categories); model.reload(); } /** * * @return */ public JFrame getFrmCyberPhysical() { return frmCyberPhysical; } /** * Getter for selected CpsObject * * @return selected CpsObject */ public CpsObject getActualCps() { int tempID = model.getSelectedObjectID(); CpsObject tempCps = controller.searchByID(tempID); return tempCps; } /** * Search for actual selected HolonElement * * @param obj * selected HolonObject * @param yValue * Y-Coord in the HolonElementsTable * @return the selected HolonElement */ public HolonElement getActualHolonElement(HolonObject obj, int yValue) { final int yTemp = (int) Math.floor(yValue / 16); int rowsTotal = tableModelHolonElement.getRowCount(); if (rowsTotal != 0 && rowsTotal > yTemp) { model.setSelectedHolonElement(obj.getElements().get(yTemp)); return obj.getElements().get(yTemp); } else { model.setSelectedHolonElement(null); return null; } } /** * Update the HolonElement Table, that means erase all rows and add the new * rows with new data */ public void refreshTableHolonElement() { // Update of the Information about the HolonElements - only for // HolonObjects deleteRows(); if (getActualCps() != null) { fillElementTable(((HolonObject) getActualCps()).getElements()); } tableModelHolonElement.fireTableDataChanged(); } /** * Erase all information of the HolonElement Model */ public void deleteRows() { if (tableModelHolonElement.getRowCount() > 0) { for (int i = tableModelHolonElement.getRowCount() - 1; i > -1; i--) { tableModelHolonElement.removeRow(i); } } } /** * Add the Information of the given ArrayList in the HolonElement Model as * Name,Energy and Amount * * @param elements * ArrayList to be displayed */ public void fillElementTable(ArrayList elements) { for (HolonElement he : elements) { Object[] temp = { he.getEleName(), he.getEnergy(), he.getAmount(), he.getActive() }; tableModelHolonElement.addRow(temp); } } /** * Update the information concerning properties of the selected CpsObject */ public void refreshTableProperties() { CpsObject tempCps = getActualCps(); if (tempCps != null && tempCps.getClass() == HolonObject.class) { tableModelProperties.removeRow(2); Object[] tempEnergy = { "Total Energy", ((HolonObject) tempCps).getCurrentEnergy() }; tableModelProperties.insertRow(2, tempEnergy); } else if (tempCps instanceof HolonTransformer) { // Refresh Transformer Info } } private static void addPopup(Component component, final JPopupMenu popup) { component.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showMenu(e); } } private void showMenu(MouseEvent e) { popup.show(e.getComponent(), e.getX(), e.getY()); } }); } }