Sfoglia il codice sorgente

Improves Connection Creation PopUp

* more elegant importCode
* refreshGui function
Andreas T. Meyer-Berg 5 anni fa
parent
commit
32bb10ed2c

+ 370 - 280
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/popups/ConnectionCreationPanel.java

@@ -5,7 +5,6 @@ import java.awt.Dimension;
 import java.awt.Window;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
-import java.io.File;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.LinkedList;
@@ -13,7 +12,6 @@ import java.util.concurrent.ThreadLocalRandom;
 import java.util.stream.Collectors;
 
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.Controller;
-import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.ImportController;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Connection;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.ConnectionPerformance;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Link;
@@ -23,10 +21,9 @@ import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.Protocol;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.SmartDevice;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.protocols.MQTT_protocol;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.core.simpleImplementation.SimpleLink;
-import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.util.JavaFileFilter;
 
-import javax.swing.JFileChooser;
 import javax.swing.JFrame;
+import javax.swing.JOptionPane;
 import javax.swing.JPanel;
 import javax.swing.JLabel;
 import javax.swing.JScrollPane;
@@ -59,9 +56,9 @@ public class ConnectionCreationPanel extends JScrollPane {
 	 * Connection which is edited
 	 */
 	private Connection connection;
-	
+
 	/**
-	 * Index of the disconnected option in the boxes Array 
+	 * Index of the disconnected option in the boxes Array
 	 */
 	private int disconnectedIndex;
 
@@ -70,11 +67,31 @@ public class ConnectionCreationPanel extends JScrollPane {
 	 */
 	private Port[] ports;
 
+	/**
+	 * ComboBox for link selection
+	 */
+	private JComboBox<String> cmbSelectedLink;
+
+	/**
+	 * ComboBox for connection selection
+	 */
+	private JComboBox<String> cmbConnection;
+
+	/**
+	 * ComboBox for the protocol selection
+	 */
+	private JComboBox<String> cmbProtocolType;
+
 	/**
 	 * ComboBoxes to allow role changes of the different Ports
 	 */
 	private JComboBox<String>[] boxes;
 
+	/**
+	 * ComboBox for the status
+	 */
+	JComboBox<String> cmbStatus;
+
 	/**
 	 * True if an existing connection is being edited, or false if a new one is
 	 * being created
@@ -82,20 +99,20 @@ public class ConnectionCreationPanel extends JScrollPane {
 	private boolean edit;
 
 	/**
-	 * Last index which was selected in the protocolType ComboBox, to allow restore
-	 * the selected Index in case of invalid protocols
+	 * Last index which was selected in the protocolType ComboBox, to allow
+	 * restore the selected Index in case of invalid protocols
 	 */
 	private int lastProtocolIndex = 0;
-	
+
 	/**
-	 * Last index which was selected in the selectedLink ComboBox, to allow restore
-	 * the selected Index in case of invalid links
+	 * Last index which was selected in the selectedLink ComboBox, to allow
+	 * restore the selected Index in case of invalid links
 	 */
 	private int lastLinkIndex = -1;
 
 	/**
-	 * Last index which was selected in the selectedConnection ComboBox, to allow restore
-	 * the selected Index in case of invalid Connection
+	 * Last index which was selected in the selectedConnection ComboBox, to
+	 * allow restore the selected Index in case of invalid Connection
 	 */
 	private int lastConnectionIndex = -1;
 
@@ -124,6 +141,11 @@ public class ConnectionCreationPanel extends JScrollPane {
 	 */
 	private JTextField tfPacketLossRate;
 
+	/**
+	 * Should not update if mutex is true
+	 */
+	private boolean mutex = true;
+
 	/**
 	 * @wbp.parser.constructor
 	 */
@@ -156,14 +178,13 @@ public class ConnectionCreationPanel extends JScrollPane {
 
 	@SuppressWarnings("unchecked")
 	private void initializePanel() {
-		if(connection != null && connection.getProtocol()!=null)
-			disconnectedIndex = connection.getProtocol().getNumberOfRoles();
-		else
-			disconnectedIndex = 0;
-		
+		// Init variables
+		disconnectedIndex = connection.getProtocol().getNumberOfRoles();
+
 		availableProtocols = controller.getControllerImport().getProtocols();
 		availableConnection = controller.getControllerImport().getConnections();
 
+		// Sets up window
 		setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
 		this.setPreferredSize(new Dimension(600, 220 + ports.length * 20));
 		content = new JPanel();
@@ -181,7 +202,6 @@ public class ConnectionCreationPanel extends JScrollPane {
 		content.add(lblName);
 
 		tfName = new JTextField();
-		tfName.setText(connection.getName());
 		tfName.setBounds(155, 10, 290, 20);
 		content.add(tfName);
 		tfName.setColumns(10);
@@ -189,137 +209,147 @@ public class ConnectionCreationPanel extends JScrollPane {
 
 			@Override
 			public void actionPerformed(ActionEvent e) {
+				if (mutex) {
+					tfName.setText(connection.getName());
+					return;
+				}
 				connection.setName(tfName.getText());
 			}
 		});
-		
+
 		JLabel lblSelectedLink = new JLabel("Selected link:");
 		lblSelectedLink.setHorizontalAlignment(SwingConstants.RIGHT);
 		lblSelectedLink.setBounds(10, 40, 140, 20);
 		content.add(lblSelectedLink);
-		
-		JComboBox<String> cmbSelectedLink = new JComboBox<String>();
+
+		// Check if model contains link
+		if (connection.getLink() != null
+				&& !controller.getLinks().contains(connection.getLink()))
+			controller.addLink(connection.getLink());
+
+		cmbSelectedLink = new JComboBox<String>();
 		cmbSelectedLink.setBounds(155, 40, 125, 20);
 		content.add(cmbSelectedLink);
-		int linkIndex = 0;
-		for(Link l:controller.getLinks()){
-			cmbSelectedLink.addItem(l.getName());
-			if(l.equals(connection.getLink())){
-				lastLinkIndex = linkIndex;
-			}
-			linkIndex++;
-		}
-		cmbSelectedLink.setSelectedIndex(lastLinkIndex);
-		cmbSelectedLink.addActionListener(a -> {
-			int cmbSelectedLinkIndex = cmbSelectedLink.getSelectedIndex();
-			if(cmbSelectedLinkIndex == -1) return;
-			Link newLink = null;
-			Iterator<Link> linkIterator = controller.getLinks().iterator();
-			for(int i = 0; i<cmbSelectedLinkIndex && linkIterator.hasNext(); i++){
-				linkIterator.next();
-			}
-			if(linkIterator.hasNext())
-				newLink = linkIterator.next();
-			if(!controller.changeLinkOfConnection(connection, newLink)){
-				//if LinkChange failed: Restore
-				cmbSelectedLink.setSelectedIndex(lastLinkIndex);
-			}else{
-				lastLinkIndex = cmbSelectedLinkIndex;
-			}
-			
-		});
-		
+
+		cmbSelectedLink
+				.addActionListener(a -> {
+					if (mutex) {
+						cmbSelectedLink.setSelectedIndex(lastLinkIndex);
+						return;
+					}
+					int cmbSelectedLinkIndex = cmbSelectedLink
+							.getSelectedIndex();
+					if (cmbSelectedLinkIndex == -1)
+						return;
+					Link newLink = null;
+					Iterator<Link> linkIterator = controller.getLinks()
+							.iterator();
+					for (int i = 0; i < cmbSelectedLinkIndex
+							&& linkIterator.hasNext(); i++) {
+						linkIterator.next();
+					}
+					if (linkIterator.hasNext())
+						newLink = linkIterator.next();
+					if (!controller.changeLinkOfConnection(connection, newLink)) {
+						// if LinkChange failed: Restore
+						cmbSelectedLink.setSelectedIndex(lastLinkIndex);
+					} else {
+						lastLinkIndex = cmbSelectedLinkIndex;
+					}
+
+				});
+
 		JButton btnCreateLink = new JButton("Create Link");
 		btnCreateLink.setBounds(290, 40, 155, 20);
 		content.add(btnCreateLink);
-		btnCreateLink.addActionListener(a->{
-			new LinkCreationDialog(connection.getParticipants().stream().map(lElem->lElem.getOwner()).collect(Collectors.toList()), controller, content);
-			//TODO: Update ComboBox
-		});
-		
+		btnCreateLink.addActionListener(a -> {
+			new LinkCreationDialog(connection.getParticipants().stream()
+					.map(lElem -> lElem.getOwner())
+					.collect(Collectors.toList()), controller, content);
+			// TODO: Refresh
+			});
+
 		JLabel lblConnectionType = new JLabel("Connection type:");
 		lblConnectionType.setHorizontalAlignment(SwingConstants.RIGHT);
 		lblConnectionType.setBounds(10, 70, 140, 20);
 		content.add(lblConnectionType);
-		JComboBox<String> cmbConnection = new JComboBox<String>();
-		cmbConnection.setBounds(155, 70, 125, 20);
-		content.add(cmbConnection);
-		
-		for (int i = 0; i < availableConnection.size(); i++)
-			cmbConnection.addItem(availableConnection.get(i).getSimpleName());
 
+		cmbConnection = new JComboBox<String>();
 		cmbConnection.setBounds(155, 70, 125, 20);
 		content.add(cmbConnection);
-		// Set Index to selected Protocol
-		for (int i = 0; i < availableConnection.size(); i++)
-			if (connection.getClass()
-					.equals(availableConnection.get(i))){
-				//Select the right protocol and save last index
-				cmbConnection.setSelectedIndex(i);
+
+		cmbConnection.addActionListener(a -> {
+			if (mutex) {
+				cmbConnection.setSelectedIndex(lastConnectionIndex);
+				return;
 			}
-		cmbConnection.addActionListener(a->{
 			cmbConnection.getSelectedIndex();
 			int selectedIndex = cmbConnection.getSelectedIndex();
-			if(lastConnectionIndex!=selectedIndex && selectedIndex!=-1){
-				Connection newConnection = controller.changeConnectionType(connection, availableConnection.get(selectedIndex));
-				if(newConnection==null){
+			if (lastConnectionIndex != selectedIndex && selectedIndex != -1) {
+				Connection newConnection = controller.changeConnectionType(
+						connection, availableConnection.get(selectedIndex));
+				if (newConnection == null) {
 					System.out.println("Warning invalidConnection changed");
 					cmbConnection.setSelectedIndex(lastConnectionIndex);
-				}else{
+				} else {
 					connection = newConnection;
 					lastConnectionIndex = selectedIndex;
 				}
-			}else{
+			} else {
 				cmbConnection.setSelectedIndex(lastConnectionIndex);
 			}
-			
+
 		});
-		
+
 		JButton btnImportConnection = new JButton("Import Connection");
 		btnImportConnection.setBounds(290, 70, 155, 20);
 		content.add(btnImportConnection);
+		btnImportConnection.addActionListener(a -> {
+			ImportPopUp<Connection> popUp = new ImportPopUp<Connection>(this,
+					Connection.class);
+			try {
+				Class<? extends Connection> imported = popUp.showPopUp();
+				if (imported == null)
+					return;
+				if (controller.getControllerImport().addConnection(imported)) {
+					refreshGUI();
+				} else {
+					JOptionPane.showMessageDialog(frame,
+							"Import failed: Invalid Connection");
+				}
+			} catch (Exception e1) {
+				JOptionPane.showMessageDialog(frame,
+						"Import failed: " + e1.getMessage());
+			}
+		});
 
 		JLabel lblProtocolType = new JLabel("Protocol Type:");
 		lblProtocolType.setHorizontalAlignment(SwingConstants.RIGHT);
 		lblProtocolType.setBounds(10, 100, 140, 20);
 		content.add(lblProtocolType);
 
-		JComboBox<String> cmbProtocolType = new JComboBox<String>();
-		for (int i = 0; i < availableProtocols.size(); i++)
-			try {
-				cmbProtocolType.addItem(availableProtocols.get(i).newInstance()
-						.getName());
-			} catch (InstantiationException | IllegalAccessException e1) {
-				System.out.println("Protocol " + i + " is invalid");
-				cmbProtocolType.addItem("unknown");
-			}
+		cmbProtocolType = new JComboBox<String>();
 		cmbProtocolType.setBounds(155, 100, 125, 20);
 		content.add(cmbProtocolType);
-		// Set Index to selected Protocol
-		for (int i = 0; i < availableProtocols.size(); i++)
-			if (connection.getProtocol().getClass()
-					.equals(availableProtocols.get(i))){
-				//Select the right protocol and save last index
-				cmbProtocolType.setSelectedIndex(i);
-				lastProtocolIndex = i;
-			}
 
 		// Add Functionality for changing protocol
 		cmbProtocolType.addActionListener(new ActionListener() {
 			@Override
 			public void actionPerformed(ActionEvent e) {
+				// TODO: Improve ImportPopUp
 				/**
 				 * Old Protocol
 				 */
 				Protocol oldProtocol = connection.getProtocol();
-				//Set Mutex to true, to disallow changes of roles during the editing
+				// Set Mutex to true, to disallow changes of roles during the
+				// editing
 				protocolChange = true;
 				/**
 				 * New Protocol which should be created and configured
 				 */
 				Protocol newProtocol = null;
 				try {
-					//Create new Instance of the protocol
+					// Create new Instance of the protocol
 					newProtocol = availableProtocols.get(
 							cmbProtocolType.getSelectedIndex()).newInstance();
 				} catch (InstantiationException | IllegalAccessException e1) {
@@ -330,7 +360,7 @@ public class ConnectionCreationPanel extends JScrollPane {
 					cmbProtocolType.setSelectedIndex(lastProtocolIndex);
 					System.out
 							.println("WARNING: Invalid Protocol Selected - restore last index");
-				} else if(connection.setProtocol(newProtocol)){
+				} else if (connection.setProtocol(newProtocol)) {
 					/**
 					 * New Roles as Strings
 					 */
@@ -339,36 +369,39 @@ public class ConnectionCreationPanel extends JScrollPane {
 					 * The old disconnected status
 					 */
 					int oldDisconnected = oldProtocol.getNumberOfRoles();
-					//Update to new disconnected Index
+					// Update to new disconnected Index
 					disconnectedIndex = newProtocol.getNumberOfRoles();
-					//Update Protocol
-						
+					// Update Protocol
+
 					// Update lastProtocolIndex to new Index
 					lastProtocolIndex = cmbProtocolType.getSelectedIndex();
-					//Update Boxes
+					// Update Boxes
 					for (int i = 0; i < boxes.length; i++) {
 						/**
 						 * The previous selected Index
 						 */
 						int oldSelected = boxes[i].getSelectedIndex();
-						//Update Labels of the current Box
+						// Update Labels of the current Box
 						boxes[i].removeAllItems();
 						for (int j = 0; j < newRoles.length; j++)
 							boxes[i].addItem(newRoles[j]);
 						boxes[i].addItem("Disconnected");
-						//Try to update the Roles
+						// Try to update the Roles
 						if (oldSelected < 0 || oldSelected >= disconnectedIndex
 								|| oldSelected == oldDisconnected) {
-							//Invalid Index -> Disconnected
-							controller.removeDeviceFromConnection(ports[i], connection);
+							// Invalid Index -> Disconnected
+							controller.removeDeviceFromConnection(ports[i],
+									connection);
 							boxes[i].setSelectedIndex(disconnectedIndex);
 						} else {
-							if (controller.addDeviceToConnection(ports[i], connection, oldSelected)){
-								//Set to Box to display role
+							if (controller.addDeviceToConnection(ports[i],
+									connection, oldSelected)) {
+								// Set to Box to display role
 								boxes[i].setSelectedIndex(oldSelected);
 							} else {
-								//Could not be added -> Disconnected
-								controller.removeDeviceFromConnection(ports[i], connection);
+								// Could not be added -> Disconnected
+								controller.removeDeviceFromConnection(ports[i],
+										connection);
 								boxes[i].setSelectedIndex(disconnectedIndex);
 							}
 						}
@@ -376,7 +409,7 @@ public class ConnectionCreationPanel extends JScrollPane {
 				} else {
 					cmbProtocolType.setSelectedIndex(lastProtocolIndex);
 				}
-				//Set Mutex back to false - allow changes
+				// Set Mutex back to false - allow changes
 				protocolChange = false;
 			}
 		});
@@ -385,184 +418,158 @@ public class ConnectionCreationPanel extends JScrollPane {
 		btnImportProtocol.setBounds(290, 100, 155, 20);
 		content.add(btnImportProtocol);
 		btnImportProtocol.addActionListener(a -> {
-			//Filechooser starting in the base directory
-			JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir")));
-			fc.setFileFilter(new JavaFileFilter());
-			int returnVal = fc.showOpenDialog(this);
-
-	        if (returnVal == JFileChooser.APPROVE_OPTION) {
-	        	/**
-	        	 * selected File
-	        	 */
-	            File file = fc.getSelectedFile();
-	            String[] parts = file.getName().split("[.]");
-	            if(parts.length <= 1)
-	            	return;
-	            /**
-	             * Check the file type
-	             */
-	            String ending = parts[parts.length-1].toLowerCase();
-	            if(ending.equals("java")){
-	            	
-	            	// Compile source file.
-	            	/**
-	            	 * Imported Java Class
-	            	 */
-	            	Class<? extends Protocol> imported = null;
-	            	try {
-						imported = (Class<? extends Protocol>) ImportController.importJavaClass(file);
-					} catch (Exception e) {
-						e.printStackTrace();
-					}
-	            	if(imported==null){
-	            		System.out.println("WARNING: Importing failed");
-	            	}else{
-	            		@SuppressWarnings("rawtypes")
-						Class[] interfaces = imported.getInterfaces();
-	            		boolean isProtocol = false;
-	            		for(int i = 0; i<interfaces.length; i++){
-	            			if(interfaces[i] == Protocol.class)
-	            				isProtocol = true;
-	            		}
-	            		if(!isProtocol){
-	            			System.out.println("WARNING: No valid protocol");
-	            		}
-	            		//Add Protocol
-	            		if(controller.getControllerImport().addProtocol(imported)){
-	            			//Update GUI
-	            			try {
-								cmbProtocolType.addItem((imported.newInstance()).getName());
-								availableProtocols.add(imported);
-							} catch (Exception e1) {
-								System.out.println("Adding Protocol to the Links failed");
-							}
-	            		}else{
-	            			System.out.println("Importing into the model failed");
-	            		}
-	            	}
-	            }else{
-	            	System.out.println("WARNING: Invalid File Type");
-	            	return;
-	            }
-	        } else {
-	           //Importing Cancelled by user
-	        }
+			// TODO: Improve Import
+				ImportPopUp<Protocol> popUp = new ImportPopUp<Protocol>(this,
+						Protocol.class);
+
+				Class<? extends Protocol> imported = null;
+				try {
+					imported = popUp.showPopUp();
+				} catch (Exception e1) {
+					JOptionPane.showMessageDialog(frame,
+							"Import failed: " + e1.getMessage());
+					return;
+				}
+				if (imported == null) {
+					// Import cancelled
+				return;
+			}
+			// Add Protocol
+			if (controller.getControllerImport().addProtocol(imported)) {
+				// Update GUI
+				refreshGUI();
+			} else {
+				JOptionPane.showMessageDialog(frame,
+						"Import failed: Invalid Protocol");
+				return;
+			}
 		});
-		
+
 		JLabel lblPacketlossrate = new JLabel("PacketLossRate:");
 		lblPacketlossrate.setHorizontalAlignment(SwingConstants.RIGHT);
 		lblPacketlossrate.setBounds(10, 130, 140, 20);
-		lblPacketlossrate.setToolTipText("Probability of Packet loss, should be a Double in [0.0,1.0]");
+		lblPacketlossrate
+				.setToolTipText("Probability of Packet loss, should be a Double in [0.0,1.0]");
 		content.add(lblPacketlossrate);
-		
+
 		tfPacketLossRate = new JTextField();
 		tfPacketLossRate.setBounds(155, 130, 90, 20);
 		content.add(tfPacketLossRate);
 		tfPacketLossRate.setColumns(10);
-		tfPacketLossRate.setText(""+connection.getPacketLossProbability());
-		tfPacketLossRate.getDocument().addDocumentListener(new DocumentListener() {
-			
-			@Override
-			public void removeUpdate(DocumentEvent e) {
-				updateConnectionAndField();
-			}
-			
-			@Override
-			public void insertUpdate(DocumentEvent e) {
-				updateConnectionAndField();
-			}
-			
-			@Override
-			public void changedUpdate(DocumentEvent e) {
-				updateConnectionAndField();
-			}
-			
-			private void updateConnectionAndField(){
-				try{
-					double newRate = Double.parseDouble(tfPacketLossRate.getText());
-					if(newRate >= 0.0 && newRate <= 1.0){
-						connection.setPacketLossProbability(newRate);
-						tfPacketLossRate.setBackground(Color.WHITE);
-					}else{
-						tfPacketLossRate.setBackground(Color.RED);
+		tfPacketLossRate.getDocument().addDocumentListener(
+				new DocumentListener() {
+
+					@Override
+					public void removeUpdate(DocumentEvent e) {
+						updateConnectionAndField();
 					}
-				}catch(Exception exception){
-					tfPacketLossRate.setBackground(Color.RED);					
-				}
-			}
-		});
-		
+
+					@Override
+					public void insertUpdate(DocumentEvent e) {
+						updateConnectionAndField();
+					}
+
+					@Override
+					public void changedUpdate(DocumentEvent e) {
+						updateConnectionAndField();
+					}
+
+					private void updateConnectionAndField() {
+						try {
+							double newRate = Double
+									.parseDouble(tfPacketLossRate.getText());
+							if (newRate >= 0.0 && newRate <= 1.0) {
+								connection.setPacketLossProbability(newRate);
+								tfPacketLossRate.setBackground(Color.WHITE);
+							} else {
+								tfPacketLossRate.setBackground(Color.RED);
+							}
+						} catch (Exception exception) {
+							tfPacketLossRate.setBackground(Color.RED);
+						}
+					}
+				});
+
 		JLabel lblStatus = new JLabel("Status:");
 		lblStatus.setHorizontalAlignment(SwingConstants.RIGHT);
 		lblStatus.setBounds(250, 130, 60, 20);
 		content.add(lblStatus);
-		
-		JComboBox<String> cmbStatus = new JComboBox<String>();
-		for(int i = 0; i<5; i++)
-			cmbStatus.addItem(Connection.getStatusName((byte)i));
+
+		cmbStatus = new JComboBox<String>();
+		for (int i = 0; i < 5; i++)
+			cmbStatus.addItem(Connection.getStatusName((byte) i));
 		cmbStatus.setBounds(320, 130, 125, 20);
-		cmbStatus.setSelectedIndex(connection.getStatus());
+
 		content.add(cmbStatus);
 		cmbStatus.addActionListener(new ActionListener() {
 			@Override
 			public void actionPerformed(ActionEvent e) {
-				if(cmbStatus.getSelectedIndex()<0||cmbStatus.getSelectedIndex()>4)
+				if (mutex) {
+					cmbStatus.setSelectedIndex(connection.getStatus());
+				}
+				if (cmbStatus.getSelectedIndex() < 0
+						|| cmbStatus.getSelectedIndex() > 4)
 					cmbStatus.setSelectedIndex(connection.getStatus());
 				else
 					connection.setStatus((byte) cmbStatus.getSelectedIndex());
-				
+
 			}
 		});
-		
-				JButton btnCreate = new JButton("Verify and Create");
-				btnCreate.setBounds(125, 160, 206, 25);
-				content.add(btnCreate);
-				
-				btnCreate.addActionListener(new ActionListener() {
 
-					@Override
-					public void actionPerformed(ActionEvent e) {
-						
-						if(!edit){ 
-							if(!connection.getLink().getConnections().contains(connection))
-							connection.getLink().addConnection(connection);
-							for(int i = 0; i<ports.length; i++){
-								if(!ports[i].getOwner().getLinks().contains(connection.getLink()))
-									ports[i].getOwner().addLink(connection.getLink());
-								if(connection.getProtocol().getDevices().contains(ports[i])){
-									if(!connection.getParticipants().contains(ports[i]))
-										connection.addSmartDevice(ports[i]);
-									if(ports[i].getConnection()!=connection)
-										ports[i].setConnection(connection);
-									if(!ports[i].getOwner().getPorts().contains(ports[i]))
-										ports[i].getOwner().addPort(ports[i]);
-								} else {
-									if(connection.getParticipants().contains(ports[i]))
-										connection.removeSmartDevice(ports[i]);
-									if(ports[i].getConnection()!=null)
-										ports[i].setConnection(null);
-									if(ports[i].getOwner().getPorts().contains(ports[i]))
-										ports[i].getOwner().removePort(ports[i]);
-									
-								}
-							}
-							if(!controller.getLinks().contains(connection.getLink()))
-								controller.addLink(connection.getLink());
-							if(!controller.getConnections().contains(connection))
-								controller.addConnection(connection);
-						}
-						 
-						connection.setName(tfName.getText());
-						content.setVisible(false);
-						setVisible(false);
-						if (frame != null) {
-							frame.setVisible(false);
-							frame.dispose();
+		JButton btnCreate = new JButton("Verify and Create");
+		btnCreate.setBounds(125, 160, 206, 25);
+		content.add(btnCreate);
+
+		btnCreate.addActionListener(new ActionListener() {
+			@Override
+			public void actionPerformed(ActionEvent e) {
+
+				if (!edit) {
+					if (!connection.getLink().getConnections()
+							.contains(connection))
+						connection.getLink().addConnection(connection);
+					for (int i = 0; i < ports.length; i++) {
+						if (!ports[i].getOwner().getLinks()
+								.contains(connection.getLink()))
+							ports[i].getOwner().addLink(connection.getLink());
+						if (connection.getProtocol().getDevices()
+								.contains(ports[i])) {
+							if (!connection.getParticipants()
+									.contains(ports[i]))
+								connection.addSmartDevice(ports[i]);
+							if (ports[i].getConnection() != connection)
+								ports[i].setConnection(connection);
+							if (!ports[i].getOwner().getPorts()
+									.contains(ports[i]))
+								ports[i].getOwner().addPort(ports[i]);
+						} else {
+							if (connection.getParticipants().contains(ports[i]))
+								connection.removeSmartDevice(ports[i]);
+							if (ports[i].getConnection() != null)
+								ports[i].setConnection(null);
+							if (ports[i].getOwner().getPorts()
+									.contains(ports[i]))
+								ports[i].getOwner().removePort(ports[i]);
+
 						}
-						controller.notifyObservers();
 					}
-				});
-		
+					if (!controller.getLinks().contains(connection.getLink()))
+						controller.addLink(connection.getLink());
+					if (!controller.getConnections().contains(connection))
+						controller.addConnection(connection);
+				}
+
+				connection.setName(tfName.getText());
+				content.setVisible(false);
+				setVisible(false);
+				if (frame != null) {
+					frame.setVisible(false);
+					frame.dispose();
+				}
+				controller.notifyObservers();
+			}
+		});
+
 		/**
 		 * Height of the current Box which is being created
 		 */
@@ -570,11 +577,11 @@ public class ConnectionCreationPanel extends JScrollPane {
 
 		boxes = new JComboBox[ports.length];
 		for (int i = 0; i < ports.length; i++) {
-			//Effectively final variables for the action listener
+			// Effectively final variables for the action listener
 			int pos = i;
 			Port currentPort = ports[i];
 			SmartDevice currentDevice = currentPort.getOwner();
-			
+
 			JLabel lblDevice = new JLabel(currentDevice.getName() + ":"
 					+ currentPort.getPortNumber() + ":");
 			lblDevice.setHorizontalAlignment(SwingConstants.RIGHT);
@@ -587,9 +594,10 @@ public class ConnectionCreationPanel extends JScrollPane {
 			boxes[pos].addItem("Disconnected");
 			boxes[pos].setBounds(250, currentHeight, 240, 18);
 			content.add(boxes[pos]);
-			if(edit){
-				int roleOfDevice = connection.getProtocol().getRoleOfDevice(currentPort);
-				if(roleOfDevice != -1)
+			if (edit) {
+				int roleOfDevice = connection.getProtocol().getRoleOfDevice(
+						currentPort);
+				if (roleOfDevice != -1)
 					boxes[pos].setSelectedIndex(roleOfDevice);
 				else
 					boxes[pos].setSelectedIndex(disconnectedIndex);
@@ -598,19 +606,23 @@ public class ConnectionCreationPanel extends JScrollPane {
 				 * Number of tries to add the Port
 				 */
 				int n = 5;
-				for(int j = 0; j <= n; j++){
-					if(j == 0){//Try to add Router first
-						if(controller.addDeviceToConnection(currentPort, connection, 0)){
+				for (int j = 0; j <= n; j++) {
+					if (j == 0) {// Try to add Router first
+						if (controller.addDeviceToConnection(currentPort,
+								connection, 0)) {
 							boxes[pos].setSelectedIndex(0);
 							break;
-						}										
-					}else if(j == n){//If it could not be added
+						}
+					} else if (j == n) {// If it could not be added
 						boxes[pos].setSelectedIndex(disconnectedIndex);
-						controller.removeDeviceFromConnection(currentPort, connection);
+						controller.removeDeviceFromConnection(currentPort,
+								connection);
 						break;
-					}else{
-						int randomRole = ThreadLocalRandom.current().nextInt(0, disconnectedIndex);
-						if(controller.addDeviceToConnection(currentPort, connection, randomRole)){
+					} else {
+						int randomRole = ThreadLocalRandom.current().nextInt(0,
+								disconnectedIndex);
+						if (controller.addDeviceToConnection(currentPort,
+								connection, randomRole)) {
 							boxes[pos].setSelectedIndex(randomRole);
 							break;
 						}
@@ -625,24 +637,102 @@ public class ConnectionCreationPanel extends JScrollPane {
 						return;
 					}
 					/**
-					 * Selected Index of the ComboBox, which represents the new role (or disconnected)
+					 * Selected Index of the ComboBox, which represents the new
+					 * role (or disconnected)
 					 */
 					int selected = boxes[pos].getSelectedIndex();
 					/**
 					 * True if role was successfully changed
 					 */
-					boolean successfullChange = controller.changeRoleOfDevice(connection.getProtocol(),connection,
-							ports[pos], selected);
+					boolean successfullChange = controller.changeRoleOfDevice(
+							connection.getProtocol(), connection, ports[pos],
+							selected);
 					/**
 					 * Set to Disconnected, if role could not be changed
 					 */
-					if(!successfullChange){
-						boxes[pos].setSelectedIndex(connection.getProtocol().getNumberOfRoles());
-					}	
+					if (!successfullChange) {
+						boxes[pos].setSelectedIndex(connection.getProtocol()
+								.getNumberOfRoles());
+					}
 				}
 			});
 			currentHeight += 20;
 		}
+		refreshGUI();
+	}
+
+	/**
+	 * Refreshes the GUI
+	 */
+	private void refreshGUI() {
+		// Set Mutex
+		mutex = true;
+		/*
+		 * Update Variables
+		 */
+
+		disconnectedIndex = connection.getProtocol().getNumberOfRoles();
+
+		availableProtocols = controller.getControllerImport().getProtocols();
+		availableConnection = controller.getControllerImport().getConnections();
+
+		/**
+		 * Update Boxes, Textfield e.g.
+		 */
+
+		// Update Name Textfield
+		tfName.setText(connection.getName());
+
+		// Update packet loss field
+		tfPacketLossRate.setText("" + connection.getPacketLossProbability());
+
+		// Update Status
+		cmbStatus.setSelectedIndex(connection.getStatus());
+
+		// Update selected Connection
+		availableConnection = controller.getControllerImport().getConnections();
+		cmbConnection.removeAllItems();
+		for (Class<? extends Connection> c : availableConnection)
+			cmbConnection.addItem(c.getSimpleName());
+		// Set Index to selected Connection
+		for (int i = 0; i < availableConnection.size(); i++)
+			if (connection.getClass().equals(availableConnection.get(i))) {
+				// Select the right protocol and save last index
+				lastConnectionIndex = i;
+			}
+		cmbConnection.setSelectedIndex(lastConnectionIndex);
+
+		// Update selected Link
+		int linkIndex = 0;
+		for (Link l : controller.getLinks()) {
+			cmbSelectedLink.addItem(l.getName());
+			if (l.equals(connection.getLink())) {
+				lastLinkIndex = linkIndex;
+			}
+			linkIndex++;
+		}
+		cmbSelectedLink.setSelectedIndex(lastLinkIndex);
+
+		// Update protocol
+		for (int i = 0; i < availableProtocols.size(); i++)
+			try {
+				cmbProtocolType.addItem(availableProtocols.get(i).newInstance()
+						.getName());
+			} catch (InstantiationException | IllegalAccessException e1) {
+				System.out.println("Protocol " + i + " is invalid");
+				cmbProtocolType.addItem("unknown");
+			}
+		// Set Index to selected Protocol
+		for (int i = 0; i < availableProtocols.size(); i++)
+			if (connection.getProtocol().getClass()
+					.equals(availableProtocols.get(i))) {
+				// Select the right protocol and save last index
+				lastProtocolIndex = i;
+			}
+		cmbProtocolType.setSelectedIndex(lastProtocolIndex);
+
+		// Release mutex
+		mutex = false;
 	}
 
 	/**
@@ -666,7 +756,7 @@ public class ConnectionCreationPanel extends JScrollPane {
 		Model m = new Model();
 		m.addConnectionNetwork(testNet);
 		m.addConnectionNetwork(new SimpleLink("Wifi"));
-		m.addConnectionNetwork (new SimpleLink("Ethernet"));
+		m.addConnectionNetwork(new SimpleLink("Ethernet"));
 		panel = new ConnectionCreationPanel(ports, testNet, new Controller(m));
 		panel.setFrame(frame);
 		frame.setContentPane(panel);

+ 3 - 3
src/main/java/de/tu_darmstadt/tk/SmartHomeNetworkSim/view/popups/ImportPopUp.java

@@ -1,9 +1,9 @@
 package de.tu_darmstadt.tk.SmartHomeNetworkSim.view.popups;
 
+import java.awt.Container;
 import java.io.File;
 
 import javax.swing.JFileChooser;
-import javax.swing.JPanel;
 
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.ClassImportException;
 import de.tu_darmstadt.tk.SmartHomeNetworkSim.control.ImportController;
@@ -17,7 +17,7 @@ import de.tu_darmstadt.tk.SmartHomeNetworkSim.view.util.JavaFileFilter;
  */
 public class ImportPopUp<T> {
 
-	private JPanel panel;
+	private Container panel;
 	private Class<T> classType;
 	
 	/**
@@ -25,7 +25,7 @@ public class ImportPopUp<T> {
 	 * @param panel position relative to this panel
 	 * @param classType superclass/interface of the imported class
 	 */
-	public ImportPopUp (JPanel panel, Class<T> classType) {
+	public ImportPopUp (Container panel, Class<T> classType) {
 		this.panel = panel;
 		this.classType = classType;
 	}