Example usage for javax.swing JLabel setBounds

List of usage examples for javax.swing JLabel setBounds

Introduction

In this page you can find the example usage for javax.swing JLabel setBounds.

Prototype

public void setBounds(int x, int y, int width, int height) 

Source Link

Document

Moves and resizes this component.

Usage

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccSwing.CFAccSwingAccountEntryAttrJPanel.java

public void doLayout() {
    JLabel label;
    JComponent compo;//from   ww  w.  j a  v a  2s.c  om
    CFJReferenceEditor reference;
    Dimension dim;
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 1024;
    Dimension jpsz = getSize();
    int usefieldwidth = jpsz.width - 215;

    label = getSwingLabelOwnerTenant();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceOwnerTenant();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelContainerAccount();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceContainerAccount();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupSplit();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupSplit();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupDrCcy();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupDrCcy();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupCrCcy();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupCrCcy();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupCvtCcy();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupCvtCcy();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupBalCcy();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupBalCcy();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupXfrAccount();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupXfrAccount();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelEntryId();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorEntryId();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelEntryStamp();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorEntryStamp();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelDescription();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDescription();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelDebit();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDebit();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelCredit();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorCredit();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelConvertedAmount();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorConvertedAmount();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelBalance();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorBalance();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccSwing.CFAccSwingAccountEntryAttrJPanel.java

public CFAccSwingAccountEntryAttrJPanel(ICFAccSwingSchema argSchema, ICFAccAccountEntryObj argFocus) {
    super();//w w  w.ja  v a 2s  . c  o m
    JLabel label;
    JComponent compo;
    CFJReferenceEditor reference;
    final String S_ProcName = "construct-schema-focus";
    if (argSchema == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "argSchema");
    }
    // argFocus is optional; focus may be set later during execution as
    // conditions of the runtime change.
    swingSchema = argSchema;
    setSwingFocusAsAccountEntry(argFocus);
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 785;
    final int panelwidth = fieldx + fieldwidth + spacing;
    // temporary -- I think you have to have a panel bigger than the coordinates initially
    setSize(panelwidth, 100000);

    label = getSwingLabelOwnerTenant();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceOwnerTenant();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelContainerAccount();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceContainerAccount();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupSplit();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupSplit();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupDrCcy();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupDrCcy();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupCrCcy();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupCrCcy();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupCvtCcy();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupCvtCcy();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupBalCcy();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupBalCcy();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelLookupXfrAccount();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceLookupXfrAccount();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelEntryId();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorEntryId();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelEntryStamp();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorEntryStamp();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelDescription();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDescription();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelDebit();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDebit();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelCredit();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorCredit();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelConvertedAmount();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorConvertedAmount();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelBalance();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorBalance();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    // Now we can set the proper size based on the fields and references populated
    setSize(panelwidth, y);
    Dimension pfsz = new Dimension(panelwidth, y);
    setPreferredSize(pfsz);
    Dimension min = new Dimension(400, y);
    setMinimumSize(min);
    populateFields();
    adjustComponentEnableStates();
    swingIsInitializing = false;
}

From source file:dpcs.Interface.java

public Interface() {
    setIconImage(Toolkit.getDefaultToolkit().getImage(Interface.class.getResource("/graphics/Icon.png")));
    setTitle("Droid PC Suite");
    setResizable(false);//from  w w  w  .  j a v a2 s .  c o m
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1088, 715);
    try {
        InputStreamReader reader2 = new InputStreamReader(
                getClass().getResourceAsStream("/others/app-version.txt"));
        String tmp = IOUtils.toString(reader2);
        AppVersion = Double.parseDouble(tmp);
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    JMenu mnMenu = new JMenu("Menu");
    menuBar.add(mnMenu);
    JMenuItem mntmExit = new JMenuItem("Exit");

    mntmExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            System.exit(0);
        }
    });

    JMenu mnADBandFastbootTools = new JMenu("ADB and Fastboot tools");
    mnMenu.add(mnADBandFastbootTools);
    mnADBandFastbootTools.setToolTipText("Access various ADB and Fastboot tools");

    JMenuItem mntmDevicestate = new JMenuItem("View device state");
    mntmDevicestate.setToolTipText("Check android device state");
    mntmDevicestate.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb get-state");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, "State: " + reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmAdbHelp = new JMenuItem("View ADB help");
    mntmAdbHelp.setToolTipText("Get help regarding ADB");
    mntmAdbHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ADBHelp obj = new ADBHelp();
            obj.setVisible(true);
        }
    });

    JMenuItem mntmNoOfUsers = new JMenuItem("Max user(s) supported?");
    mntmNoOfUsers.setToolTipText("Max no. of user(s) supported by android device");
    mntmNoOfUsers.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb shell pm get-max-users");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnADBandFastbootTools.add(mntmNoOfUsers);
    mnADBandFastbootTools.add(mntmAdbHelp);

    JMenuItem mntmAdbVersion = new JMenuItem("View ADB version");
    mntmAdbVersion.setToolTipText("Check the version of ADB installed on your computer");
    mnADBandFastbootTools.add(mntmAdbVersion);
    mntmAdbVersion.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb version");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmViewDeviceList = new JMenuItem("View connected device");
    mntmViewDeviceList.setToolTipText(
            "Displays connected device, it will show name and serial no. of the only connected device because of connectivity limit");
    mntmViewDeviceList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                JTextArea Devicelistviewer = new JTextArea();
                Devicelistviewer.setEditable(false);
                Devicelistviewer.setForeground(Color.BLACK);
                Devicelistviewer.setOpaque(false);
                Process p1 = Runtime.getRuntime().exec("adb devices -l");
                p1.waitFor();
                int i = 0;
                String line;
                String[] array = new String[1024];
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                while ((line = reader.readLine()) != null) {
                    array[i] = line;
                    Devicelistviewer.append(line + "\n");
                }
                JOptionPane.showMessageDialog(null, Devicelistviewer);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnADBandFastbootTools.add(mntmViewDeviceList);
    mnADBandFastbootTools.add(mntmDevicestate);

    JMenuItem mntmViewFastbootHelp = new JMenuItem("View fastboot help");
    mntmViewFastbootHelp.setToolTipText("Get help regarding fastboot");
    mntmViewFastbootHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FastbootHelp obj = new FastbootHelp();
            obj.setVisible(true);
        }
    });
    mnADBandFastbootTools.add(mntmViewFastbootHelp);

    JMenuItem mntmSerialNo = new JMenuItem("View serial no.");
    mntmSerialNo.setToolTipText("Check ADB connectivity serial no. of your android device");
    mnADBandFastbootTools.add(mntmSerialNo);
    mntmSerialNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb get-serialno");
                p1.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p1.getInputStream()));
                JOptionPane.showMessageDialog(null, "Serial No: " + reader.readLine());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmWaitForDevice = new JMenuItem("Wait for device");
    mntmWaitForDevice.setToolTipText("Ask ADB to wait for your device until the device can accept commands");
    mntmWaitForDevice.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb wait-for-device");
                p1.waitFor();
                JOptionPane.showMessageDialog(null, "Waiting...");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnADBandFastbootTools.add(mntmWaitForDevice);

    JMenuItem mntmDeviceFeatures = new JMenuItem("Device features");
    mnMenu.add(mntmDeviceFeatures);
    mntmDeviceFeatures.setToolTipText("View list of features supported by the android device");
    mntmDeviceFeatures.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Devicefeatures obj = new Devicefeatures();
            obj.setVisible(true);
        }
    });

    JMenu mnDeviceSpecificTools = new JMenu("Device specific tools");
    mnMenu.add(mnDeviceSpecificTools);
    mnDeviceSpecificTools.setToolTipText("View tools which only work with few  or specific devices");

    JMenu mnHTC = new JMenu("HTC");
    mnDeviceSpecificTools.add(mnHTC);
    mnHTC.setToolTipText("View list of tools which only work with HTC devices");

    JMenuItem mntmGetCidNo = new JMenuItem("Get CID no.");
    mntmGetCidNo.setToolTipText("Get CID Number of the device");
    mntmGetCidNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot getvar cid");
                p2.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine());
                Process p3 = Runtime.getRuntime().exec("fastboot reboot");
                p3.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenuItem mntmBootloaderRelatedInfo = new JMenuItem("Bootloader related info");
    mntmBootloaderRelatedInfo.setToolTipText("View CID No.,Main-ver, bootloader info Etc.");
    mntmBootloaderRelatedInfo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot getvar all");
                p2.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p2.getInputStream()));
                JOptionPane.showMessageDialog(null, reader.readLine() + "\n");
                Process p3 = Runtime.getRuntime().exec("fastboot reboot");
                p3.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnHTC.add(mntmBootloaderRelatedInfo);
    mnHTC.add(mntmGetCidNo);

    JMenuItem mntmWriteSuperCIDNo = new JMenuItem("Write Super CID no.");
    mntmWriteSuperCIDNo.setToolTipText("Write Super CID Number to device");
    mntmWriteSuperCIDNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                int supercidno;
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                supercidno = Integer.parseInt(JOptionPane.showInputDialog(null,
                        "Enter the Super CID Number to be written :\nfor ex. 11111111"));
                Process p2 = Runtime.getRuntime().exec("fastboot oem writecid " + supercidno);
                p2.waitFor();
                JOptionPane.showMessageDialog(null, "Done, Click OK to reboot");
                Process p3 = Runtime.getRuntime().exec("fastboot reboot");
                p3.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    mnHTC.add(mntmWriteSuperCIDNo);

    JMenu mnSamsung = new JMenu("Samsung");
    mnSamsung.setToolTipText("View list of tools which only work with Samsung devices");
    mnDeviceSpecificTools.add(mnSamsung);

    JMenuItem mntmDownloadMode = new JMenuItem("Download Mode");
    mntmDownloadMode.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot download");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });
    mntmDownloadMode.setToolTipText(
            "Reboot to Download Mode for flashing firmware to samsung device using Odin or Heimdall");
    mnSamsung.add(mntmDownloadMode);

    mnMenu.add(mntmExit);
    JMenu mnHelp = new JMenu("Help");
    menuBar.add(mnHelp);

    JMenuItem mntmCommonWorkarounds = new JMenuItem("Common workarounds");
    mntmCommonWorkarounds.setToolTipText(
            "View solutions and tips to avoid the common problems while using this application");
    mntmCommonWorkarounds.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Workarounds obj = new Workarounds();
            obj.setVisible(true);
        }
    });

    JMenuItem mntmAbout = new JMenuItem("About");
    mntmAbout.setToolTipText("Information about the application");
    mntmAbout.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            About obj = new About();
            obj.setVisible(true);
        }
    });
    mnHelp.add(mntmAbout);

    JMenuItem mntmCheckForUpdates = new JMenuItem("Check for updates");
    mntmCheckForUpdates.setToolTipText("Check for the new updates of this application");
    mntmCheckForUpdates.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Updater();
        }
    });

    JMenuItem mntmChangelog = new JMenuItem("Changelog");
    mntmChangelog.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Changelog obj = new Changelog();
            obj.setVisible(true);
        }
    });
    mntmChangelog.setToolTipText("View changes made to this application over the time");
    mnHelp.add(mntmChangelog);
    mnHelp.add(mntmCheckForUpdates);
    mnHelp.add(mntmCommonWorkarounds);

    JMenuItem mntmNeedHelp = new JMenuItem("Online help");
    mntmNeedHelp.setToolTipText("Get online help for Droid PC Suite");
    mntmNeedHelp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                JOptionPane.showMessageDialog(null, "Post your queries on XDA-Developers thread");
                Desktop.getDesktop().browse(new URL(
                        "http://forum.xda-developers.com/android/development/tool-droid-pc-suite-t3398599")
                                .toURI());
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    });

    JMenuItem mntmForceConnect = new JMenuItem("Force connect");
    mnHelp.add(mntmForceConnect);
    mntmForceConnect.setToolTipText("Force connect android device to computer using ADB protocol");
    mntmForceConnect.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JOptionPane.showMessageDialog(null,
                    "Go to developer options and turn off android debugging and turn it on again");
            JOptionPane.showMessageDialog(null,
                    "Now tap on Revoke USB debugging authorizations and confirm it by tapping OK on android device");
            JOptionPane.showMessageDialog(null, "Now disconnect your android device and reconnect it via USB");
            JOptionPane.showMessageDialog(null, "Reboot your device. After it completely boots up click OK");
            try {
                adbconnected = false;
                Process p1 = Runtime.getRuntime().exec("adb kill-server");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb devices");
                p2.waitFor();
                JOptionPane.showMessageDialog(null, "Check if your device asks to Allow USB debugging");
                JOptionPane.showMessageDialog(null,
                        "If yes check always allow from this computer checkbox and tap OK on your android device");
                Process p3 = Runtime.getRuntime().exec("adb shell touch /sdcard/.CheckADBConnection");
                p3.waitFor();
                Process p4 = Runtime.getRuntime().exec("adb pull /sdcard/.CheckADBConnection");
                p4.waitFor();
                Process p5 = Runtime.getRuntime().exec("adb shell rm /sdcard/.CheckADBConnection");
                p5.waitFor();
                File file = new File(".CheckADBConnection");
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                    adbconnected = true;
                    ADBConnectionLabel.setText("Device is connected");
                    JOptionPane.showMessageDialog(null, "Success!");
                } else {
                    adbconnected = false;
                    ADBConnectionLabel.setText("");
                    ADBConnectionLabel.setText("Connect your device...");
                    JOptionPane.showMessageDialog(null,
                            "Please try again or perhaps try installing your android device adb drivers on PC");
                }
            } catch (Exception e1) {
                System.err.println(e1);
            }
            try {
                File file = new File("su");
                Process p1 = Runtime.getRuntime().exec("adb pull /system/xbin/su");
                p1.waitFor();
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                    rooted = true;
                    RootStatusLabel.setText("Device is rooted");
                } else {
                    if (adbconnected == true) {
                        rooted = false;
                        RootStatusLabel.setText("Device is not rooted");
                    } else {
                        rooted = false;
                        RootStatusLabel.setText("");
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });

    JMenu mnLegalInformation = new JMenu("Legal information");
    mnLegalInformation.setToolTipText("Vew legal information about the application");
    mnHelp.add(mnLegalInformation);

    JMenuItem mntmDroidPcSuite = new JMenuItem("Droid PC Suite license");
    mntmDroidPcSuite.setToolTipText("View Droid PC Suite licence");
    mntmDroidPcSuite.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GPLLicense obj = new GPLLicense();
            obj.setVisible(true);
        }
    });
    mnLegalInformation.add(mntmDroidPcSuite);

    JMenuItem mntmOpenSourceLicenses = new JMenuItem("Open source licenses");
    mntmOpenSourceLicenses
            .setToolTipText("View other open source licences for other softwares used with this application");
    mntmOpenSourceLicenses.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ApacheLicense obj = new ApacheLicense();
            obj.setVisible(true);
        }
    });
    mnLegalInformation.add(mntmOpenSourceLicenses);
    mnHelp.add(mntmNeedHelp);
    contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    ApplicationStatus = new JLabel("");
    ApplicationStatus.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            if (!ApplicationStatus.getText().equals("")) {
                int dialogButton = JOptionPane.YES_NO_OPTION;
                int dialogResult = JOptionPane.showConfirmDialog(null,
                        "Do you want to clear application status?", "Application status", dialogButton);
                if (dialogResult == 0) {
                    ApplicationStatus.setText("");
                }
            }
        }
    });

    JLabel lblApplicationVersion = new JLabel("Version: " + AppVersion);
    lblApplicationVersion.setBounds(818, 150, 135, 22);
    contentPane.add(lblApplicationVersion);
    ApplicationStatus.setBounds(12, 230, 1062, 17);
    contentPane.add(ApplicationStatus);

    RootStatusLabel = new JLabel("");
    RootStatusLabel.setBounds(921, 12, 153, 17);
    RootStatusLabel.setForeground(Color.RED);
    contentPane.add(RootStatusLabel);

    ADBConnectionLabel = new JLabel("");
    ADBConnectionLabel.setBounds(900, 0, 175, 17);
    ADBConnectionLabel.setForeground(Color.GREEN);
    contentPane.add(ADBConnectionLabel);

    JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.setBounds(0, 255, 1075, 447);
    contentPane.add(tabbedPane);

    JPanel panel_7 = new JPanel();
    panel_7.setBackground(Color.WHITE);
    tabbedPane.addTab("General", null, panel_7, null);
    panel_7.setLayout(null);

    JButton btnADBTerminal = new JButton("ADB Terminal");
    btnADBTerminal.setToolTipText("Send commands to your android device via ADB protocol, EXPERIMENTAL!");
    btnADBTerminal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Terminal obj = new Terminal();
            obj.setVisible(true);
        }
    });

    JButton btnBuildpropeditor = new JButton("build.prop Editor");
    btnBuildpropeditor
            .setToolTipText("Editor for editing build properties of your android device, Use with Caution!");
    btnBuildpropeditor.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Buildpropeditor obj = new Buildpropeditor();
            obj.setVisible(true);
        }
    });
    btnBuildpropeditor.setBounds(541, 27, 220, 75);
    panel_7.add(btnBuildpropeditor);
    btnADBTerminal.setBounds(25, 27, 220, 75);
    panel_7.add(btnADBTerminal);

    JLabel lblNoteInstallationTo = new JLabel("# Only for android 4.4.x and higher");
    lblNoteInstallationTo.setBounds(20, 311, 1046, 15);
    panel_7.add(lblNoteInstallationTo);

    GeneralDone = new JLabel("");
    GeneralDone.setText("");
    GeneralDone.setBounds(766, 27, 300, 220);
    panel_7.add(GeneralDone);

    JButton btnFileManager = new JButton("File Manager");
    btnFileManager.setToolTipText("Access files on your android device");
    btnFileManager.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GeneralDone.setText("");
            filemanager.FileManager.main(null);
        }
    });
    btnFileManager.setBounds(25, 131, 220, 75);
    panel_7.add(btnFileManager);

    JLabel lblNeedsRoot = new JLabel(
            "* Needs root access, also may not work with some devices regardless of root access");
    lblNeedsRoot.setBounds(20, 326, 1046, 15);
    panel_7.add(lblNeedsRoot);

    JButton btnScreenshot = new JButton("Screenshot");
    btnScreenshot.setToolTipText("Screenshot your android device screen");
    btnScreenshot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb shell screencap -p /sdcard/screenshot.png");
                p1.waitFor();
                JFileChooser directorychooser = new JFileChooser();
                directorychooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                directorychooser.setDialogTitle("Select path to save the screenshot");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG Files", "png");
                directorychooser.setFileFilter(filter);
                directorychooser.setApproveButtonText("Save");
                int returnVal = directorychooser.showOpenDialog(getParent());
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    Process p2 = Runtime.getRuntime().exec("adb pull /sdcard/screenshot.png "
                            + directorychooser.getSelectedFile().getAbsolutePath());
                    p2.waitFor();
                }
                Process p3 = Runtime.getRuntime().exec("adb shell rm /sdcard/screenshot.png");
                p3.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    btnScreenshot.setBounds(282, 131, 220, 75);
    panel_7.add(btnScreenshot);

    JButton btnScreenRecorder = new JButton("Screen Recorder #");
    btnScreenRecorder.setToolTipText("Record android device screen");
    btnScreenRecorder.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String[] options = new String[] { "5 Sec", "30 Sec", "60 Sec", "180 Sec", "Custom" };
            int response = JOptionPane.showOptionDialog(null, "Select duration of recording", "Screen Recorder",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
            int time = 0, bitrate = 8000000;
            try {
                if (response == 0) {
                    time = 5;
                }
                if (response == 1) {
                    time = 30;
                }
                if (response == 2) {
                    time = 60;
                }
                if (response == 3) {
                    time = 180;
                }
                if (response == 4) {
                    time = Integer.parseInt(JOptionPane.showInputDialog(null,
                            "Enter the duration of recording in seconds (1 - 180): for ex. 25 for 25 Seconds"));
                    bitrate = Integer.parseInt(JOptionPane.showInputDialog(null,
                            "Enter the bitrate of recording (Default = 8000000 (8Mbps))"));
                }
                JOptionPane.showMessageDialog(null, "You will need to wait for " + time + " seconds, Click ok");
                Process p1 = Runtime.getRuntime().exec("adb shell screenrecord --bit-rate " + bitrate
                        + " --time-limit " + time + " /sdcard/videorecording.mp4");
                p1.waitFor();
                JOptionPane.showMessageDialog(null, "Recording finished, Select destination to save the file");
                JFileChooser directorychooser = new JFileChooser();
                directorychooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                directorychooser.setDialogTitle("Select path to save the recording");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("MP4 Files", "mp4");
                directorychooser.setFileFilter(filter);
                directorychooser.setApproveButtonText("Save");
                int returnVal = directorychooser.showOpenDialog(getParent());
                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    Process p2 = Runtime.getRuntime().exec("adb pull /sdcard/videorecording.mp4 "
                            + directorychooser.getSelectedFile().getAbsolutePath());
                    p2.waitFor();
                }
                Process p3 = Runtime.getRuntime().exec("adb shell rm /sdcard/videorecording.mp4");
                p3.waitFor();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    btnScreenRecorder.setBounds(541, 131, 220, 75);
    panel_7.add(btnScreenRecorder);

    JButton btnAppManager = new JButton("App Manager");
    btnAppManager.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            GeneralDone.setText("");
            String[] MainOptions = new String[] { "Install apps", "Uninstall apps" };
            int MainResponse = JOptionPane.showOptionDialog(null, "Select an operation", "App Manager",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, MainOptions, MainOptions[0]);
            if (MainResponse == 0) {
                try {
                    GeneralDone.setText("");
                    String[] options = new String[] { "User apps", "Priv-apps", "System apps" };
                    int response = JOptionPane.showOptionDialog(null, "Where to install the app?", "Installer",
                            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (response == 0) {
                        try {
                            GeneralDone.setText("");
                            JFileChooser chooser = new JFileChooser();
                            FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
                            chooser.setFileFilter(filter);
                            int returnVal = chooser.showOpenDialog(getParent());
                            if (returnVal == JFileChooser.APPROVE_OPTION) {
                                File file = chooser.getSelectedFile();
                                String filename = chooser.getSelectedFile().getName();
                                try {
                                    ApplicationStatus.setText("Installing...");
                                    String[] commands = new String[3];
                                    commands[0] = "adb";
                                    commands[1] = "install";
                                    commands[2] = file.getAbsolutePath();
                                    ApplicationStatus.setText("Installing App...");
                                    Process p1 = Runtime.getRuntime().exec(commands, null);
                                    p1.waitFor();
                                    ApplicationStatus.setText(filename
                                            + " has been successfully installed on your android device!");
                                    GeneralDone.setIcon(
                                            new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                                } catch (Exception e1) {
                                    System.err.println(e1);
                                }
                            }
                        } catch (Exception e1) {
                        }
                    }
                    if (response == 1) {
                        GeneralDone.setText("");
                        JFileChooser chooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
                        chooser.setFileFilter(filter);
                        int returnVal = chooser.showOpenDialog(getParent());
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                            File file = chooser.getSelectedFile();
                            try {
                                ApplicationStatus.setText("Installing...");
                                Process p1 = Runtime.getRuntime().exec("adb remount");
                                p1.waitFor();
                                String[] pushcommand = new String[4];
                                pushcommand[0] = "adb";
                                pushcommand[1] = "push";
                                pushcommand[2] = file.getAbsolutePath();
                                pushcommand[3] = "/system/priv-app/";
                                ApplicationStatus.setText("Installing App...");
                                Process p2 = Runtime.getRuntime().exec(pushcommand, null);
                                p2.waitFor();
                                ApplicationStatus.setText("Rebooting your android device");
                                Process p3 = Runtime.getRuntime().exec("adb reboot");
                                p3.waitFor();
                                ApplicationStatus.setText("");
                                GeneralDone.setIcon(
                                        new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                            } catch (Exception e1) {
                                System.err.println(e1);
                            }
                        }
                    }
                    if (response == 2) {
                        GeneralDone.setText("");
                        JFileChooser chooser = new JFileChooser();
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
                        chooser.setFileFilter(filter);
                        int returnVal = chooser.showOpenDialog(getParent());
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                            File file = chooser.getSelectedFile();
                            try {
                                ApplicationStatus.setText("Installing...");
                                Process p1 = Runtime.getRuntime().exec("adb remount");
                                p1.waitFor();
                                String[] pushcommand = new String[4];
                                pushcommand[0] = "adb";
                                pushcommand[1] = "push";
                                pushcommand[2] = file.getAbsolutePath();
                                pushcommand[3] = "/system/app/";
                                Process p2 = Runtime.getRuntime().exec(pushcommand, null);
                                p2.waitFor();
                                ApplicationStatus.setText("Rebooting your android device");
                                Process p3 = Runtime.getRuntime().exec("adb reboot");
                                p3.waitFor();
                                ApplicationStatus.setText("");
                                GeneralDone.setIcon(
                                        new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                            } catch (Exception e1) {
                                System.err.println(e1);
                            }
                        }
                    }
                } catch (Exception e1) {
                }
            }
            if (MainResponse == 1) {
                try {
                    GeneralDone.setText("");
                    String[] options = new String[] { "User apps", "Priv-apps", "System apps" };
                    int response = JOptionPane.showOptionDialog(null,
                            "Which kind of app you want to uninstall?", "Uninstaller",
                            JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
                    if (response == 0) {
                        try {
                            UninstallUserApps obj = new UninstallUserApps();
                            obj.setVisible(true);
                        } catch (Exception e1) {
                        }
                    }
                    if (response == 1) {
                        try {
                            UninstallPrivApps obj = new UninstallPrivApps();
                            obj.setVisible(true);
                        } catch (Exception e1) {
                        }
                    }
                    if (response == 2) {
                        try {
                            UninstallSystemApps obj = new UninstallSystemApps();
                            obj.setVisible(true);
                        } catch (Exception e1) {
                        }
                    }
                } catch (Exception e1) {
                }
            }
        }
    });
    btnAppManager.setToolTipText("Manage Apps on your android device");
    btnAppManager.setBounds(282, 27, 220, 75);
    panel_7.add(btnAppManager);

    JLabel lblInstallationAndUninstallation = new JLabel(
            "Installation and Uninstallation of apps to Priv-app is only for android 4.4 and higher, requires root and even simply may not work on your device!");
    lblInstallationAndUninstallation.setBounds(20, 356, 1046, 15);
    panel_7.add(lblInstallationAndUninstallation);

    JLabel lblInstallationAndUninstallation_1 = new JLabel(
            "Installation and Uninstallation of apps to System requires root, and may not work for your device!");
    lblInstallationAndUninstallation_1.setBounds(20, 341, 1046, 15);
    panel_7.add(lblInstallationAndUninstallation_1);

    JPanel panel_8 = new JPanel();
    panel_8.setBackground(Color.WHITE);
    tabbedPane.addTab("Advanced", null, panel_8, null);
    panel_8.setLayout(null);

    JButton btnMemoryInformation = new JButton("Memory Information");
    btnMemoryInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Memoryinfo obj = new Memoryinfo();
            obj.setVisible(true);
        }
    });

    JButton btnClearBatteryStats = new JButton("Clear Battery Stats *");
    btnClearBatteryStats.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb remount");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb shell su -c rm -r /data/system/batterystats.bin");
                p2.waitFor();
                String[] options = new String[] { "Yes", "No" };
                int response = JOptionPane.showOptionDialog(null, "Done, would you like to reboot your device?",
                        "Reboot device? (Recommended)", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
                        null, options, options[0]);
                if (response == 0) {
                    try {
                        Process p3 = Runtime.getRuntime().exec("adb reboot");
                        p3.waitFor();
                    } catch (Exception e1) {
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    btnClearBatteryStats.setToolTipText("Clear outdated or invalid battery stats");
    btnClearBatteryStats.setBounds(25, 131, 220, 75);
    panel_8.add(btnClearBatteryStats);
    btnMemoryInformation.setToolTipText("View current memory information of android device");
    btnMemoryInformation.setBounds(25, 236, 220, 75);
    panel_8.add(btnMemoryInformation);

    JButton btnBatteryInformation = new JButton("Battery Information");
    btnBatteryInformation.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            Batteryinfo obj = new Batteryinfo();
            obj.setVisible(true);
        }
    });
    btnBatteryInformation.setToolTipText("View current battery information of android device");
    btnBatteryInformation.setBounds(541, 27, 220, 75);
    panel_8.add(btnBatteryInformation);

    JButton btnCpuInformation = new JButton("CPU Information");
    btnCpuInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            CPUinfo obj = new CPUinfo();
            obj.setVisible(true);
        }
    });
    btnCpuInformation.setToolTipText("View current CPU information of android device");
    btnCpuInformation.setBounds(282, 131, 220, 75);
    panel_8.add(btnCpuInformation);

    JButton btnAppInformation = new JButton("App Information");
    btnAppInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Appinfo obj = new Appinfo();
            obj.setVisible(true);
        }
    });
    btnAppInformation.setToolTipText("View current app information of android device");
    btnAppInformation.setBounds(25, 27, 220, 75);
    panel_8.add(btnAppInformation);

    JButton btnKillApps = new JButton("Kill Apps");
    btnKillApps.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String[] options = new String[] { "Enter package name", "Kill all apps" };
            int response = JOptionPane.showOptionDialog(null, "Which app(s) should be killed?", "Kill Apps",
                    JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
            if (response == 0) {
                try {
                    JOptionPane.showMessageDialog(null,
                            "You can find an app package name from App Packages List");
                    String selectedapp = (JOptionPane.showInputDialog(null, "Enter app's package name:"));
                    Process p1 = Runtime.getRuntime().exec("adb shell am force-stop " + selectedapp);
                    p1.waitFor();
                    JOptionPane.showMessageDialog(null, selectedapp + " has been killed");
                } catch (Exception e1) {
                }
            }
            if (response == 1) {
                try {
                    Process p1 = Runtime.getRuntime().exec("adb shell am kill-all");
                    p1.waitFor();
                    JOptionPane.showMessageDialog(null, "All 'safe to kill' apps have been killed");
                } catch (Exception e1) {
                }
            }
        }
    });
    btnKillApps.setToolTipText("Kill any app currently running on android device");
    btnKillApps.setBounds(541, 131, 220, 75);
    panel_8.add(btnKillApps);

    JButton btnWifiInformation = new JButton("WiFi Information");
    btnWifiInformation.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Wifiinfo obj = new Wifiinfo();
            obj.setVisible(true);
        }
    });
    btnWifiInformation.setToolTipText("View current wifi information of android device");
    btnWifiInformation.setBounds(541, 236, 220, 75);
    panel_8.add(btnWifiInformation);

    JButton btnAppPackageList = new JButton("App Packages List");
    btnAppPackageList.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AppPackagesList obj = new AppPackagesList();
            obj.setVisible(true);
        }
    });
    btnAppPackageList.setToolTipText("View all installed app packages list information");
    btnAppPackageList.setBounds(282, 27, 220, 75);
    panel_8.add(btnAppPackageList);

    JLabel lblAdvancedToolsNote = new JLabel(
            "Note: All of the above tools are not supported by every device or ROM");
    lblAdvancedToolsNote.setBounds(25, 345, 736, 15);
    panel_8.add(lblAdvancedToolsNote);

    JButton btnUnroot = new JButton("Unroot Device");
    btnUnroot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                File file1 = new File(".events");
                if (!file1.exists()) {
                    List<String> lines = Arrays.asList("Unroot_Warning_Shown = True");
                    Path file = Paths.get(".events");
                    Files.write(file, lines, Charset.forName("UTF-8"));
                    JOptionPane.showMessageDialog(null,
                            "Only the SU Binary will get removed since there are lot of different root management\napplications for android available, I can't regularly search for them and add their\nsupport to this application. If you think this concerns you, you can help me by sending\nme a list of root management applicationsfor android like supersu, kingroot, kingoroot,\netc. But I can't promise that I will add support for each of them. Cheers! :)");
                }
                JOptionPane.showMessageDialog(null, "Unrooting work only on non-production builds of android");
                Process p1 = Runtime.getRuntime().exec("adb pull /system/xbin/su");
                p1.waitFor();
                File file2 = new File("su");
                if (file2.exists() && !file2.isDirectory()) {
                    file2.delete();
                    Process p2 = Runtime.getRuntime().exec("adb remount");
                    p2.waitFor();
                    Process p3 = Runtime.getRuntime().exec("adb shell su -c rm -r /system/xbin/su");
                    p3.waitFor();
                    JOptionPane.showMessageDialog(null, "Operation completed");
                } else {
                    JOptionPane.showMessageDialog(null, "This device is not rooted");
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
    btnUnroot.setToolTipText("Unroot device by removing SU binary from the device");
    btnUnroot.setBounds(282, 236, 220, 75);
    panel_8.add(btnUnroot);

    JLabel lblNewLabel_1 = new JLabel(
            "* Needs root access, also may not work with some devices regardless of root access");
    lblNewLabel_1.setBounds(25, 372, 736, 15);
    panel_8.add(lblNewLabel_1);

    JPanel panel_10 = new JPanel();
    panel_10.setBackground(Color.WHITE);
    tabbedPane.addTab("Developer", null, panel_10, null);
    panel_10.setLayout(null);

    JButton btnUnpackAPKs = new JButton("Unpack APKs");
    btnUnpackAPKs.addActionListener(new ActionListener() {
        private Component parentFrame;

        public void actionPerformed(ActionEvent e) {
            File path = null;
            JFileChooser chooser1 = new JFileChooser();
            chooser1.setDialogTitle("Select an APK file to extract");
            FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk");
            chooser1.setCurrentDirectory(new java.io.File("."));
            chooser1.setFileFilter(filter);
            int returnVal = chooser1.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser1.getSelectedFile();
                String filename = chooser1.getSelectedFile().getName();
                JFileChooser chooser2 = new JFileChooser();
                chooser2.setDialogTitle("Extract APK file to");
                chooser2.setCurrentDirectory(new java.io.File("."));
                chooser2.setAcceptAllFileFilterUsed(false);
                chooser2.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int userSelection = chooser2.showSaveDialog(parentFrame);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    path = chooser2.getSelectedFile();
                }
                String outputDir = path.getAbsolutePath();
                java.util.zip.ZipFile zipFile = null;
                try {
                    zipFile = new ZipFile(file);
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        File entryDestination = new File(outputDir, entry.getName());
                        if (entry.isDirectory()) {
                            entryDestination.mkdirs();
                        } else {
                            entryDestination.getParentFile().mkdirs();
                            InputStream in = zipFile.getInputStream(entry);
                            OutputStream out = null;
                            out = new FileOutputStream(entryDestination);
                            IOUtils.copy(in, out);
                            IOUtils.closeQuietly(in);
                            out.close();
                        }
                    }
                    zipFile.close();
                    JOptionPane.showMessageDialog(null, filename + " has been successfully extracted");
                } catch (Exception e1) {
                    e1.printStackTrace();
                    JOptionPane.showMessageDialog(null, "An error occured");
                }
            }
        }
    });
    btnUnpackAPKs.setToolTipText("Unpack APKs stored on disk");
    btnUnpackAPKs.setBounds(541, 27, 220, 75);
    panel_10.add(btnUnpackAPKs);

    JButton btnRepackAPKs = new JButton("Repack APKs");
    btnRepackAPKs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            new Repacker();
        }
    });
    btnRepackAPKs.setToolTipText("Repack previously unpacked APKs and save to them to disk");
    btnRepackAPKs.setBounds(25, 27, 220, 75);
    panel_10.add(btnRepackAPKs);

    JButton btnStartAnActivity = new JButton("Start an activity *");
    btnStartAnActivity.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                String packagename = JOptionPane.showInputDialog(null, "Enter the package name of the app",
                        "com.package.name");
                String activityname = JOptionPane.showInputDialog(null, "Enter the activity name of the app",
                        "MainActivity");
                Process p1 = Runtime.getRuntime().exec("adb shell am start -n " + packagename + "/"
                        + packagename + "com.package.name." + activityname);
                p1.waitFor();
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        }
    });
    btnStartAnActivity.setToolTipText("Start an actvity of an android app on your android device");
    btnStartAnActivity.setBounds(282, 27, 220, 75);
    panel_10.add(btnStartAnActivity);

    JLabel lblActivityWill = new JLabel(
            "* An activity will not start if you enter wrong package name or activity name");
    lblActivityWill.setBounds(25, 381, 736, 15);
    panel_10.add(lblActivityWill);

    JPanel panel_5 = new JPanel();
    panel_5.setBackground(Color.WHITE);
    tabbedPane.addTab("Backup & Restore", null, panel_5, null);
    panel_5.setLayout(null);

    BackupAndRestoreDone = new JLabel("");
    BackupAndRestoreDone.setText("");
    BackupAndRestoreDone.setBounds(758, 70, 300, 220);
    panel_5.add(BackupAndRestoreDone);

    JLabel lblRestoreOperations = new JLabel("Restore Operations");
    lblRestoreOperations.setBounds(541, 12, 142, 36);
    panel_5.add(lblRestoreOperations);

    final JButton btnRestoreFromCustomLocationBackup = new JButton("From Custom Location");
    btnRestoreFromCustomLocationBackup
            .setToolTipText("Restore data to android device from the backup stored somewhere on the computer");
    btnRestoreFromCustomLocationBackup.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("Android Backup Files", "ab");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    ApplicationStatus.setText("Restoring may take upto several minutes, please be patient...");
                    JOptionPane.showMessageDialog(null,
                            "Unlock your device and confirm the restore operation when asked");
                    String[] commands = new String[3];
                    commands[0] = "adb";
                    commands[1] = "restore";
                    commands[2] = file.getAbsolutePath();
                    ApplicationStatus.setText("Restoring...");
                    Process p1 = Runtime.getRuntime().exec(commands, null);
                    p1.waitFor();
                    ApplicationStatus.setText("Restore completed successfully!");
                    BackupAndRestoreDone
                            .setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnRestoreFromCustomLocationBackup.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnRestoreFromCustomLocationBackup.setBounds(510, 70, 220, 75);
    panel_5.add(btnRestoreFromCustomLocationBackup);

    JLabel lblBackup = new JLabel("Backup Operations");
    lblBackup.setBounds(192, 12, 142, 36);
    panel_5.add(lblBackup);

    final JButton btnBackupInternelStorage = new JButton("Internel Storage");
    btnBackupInternelStorage.setToolTipText("Backup android device internal storage");
    btnBackupInternelStorage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-shared";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupInternelStorage.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupInternelStorage.setBounds(270, 70, 220, 75);
    panel_5.add(btnBackupInternelStorage);

    final JButton btnBackupSingleApp = new JButton("Single App");
    btnBackupSingleApp.setToolTipText("Backup a single app from android device");
    btnBackupSingleApp.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                String message = JOptionPane.showInputDialog(null, "Please specify a package name to backup");
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = message;
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupSingleApp.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupSingleApp.setBounds(25, 184, 220, 75);
    panel_5.add(btnBackupSingleApp);

    final JButton btnBackupAppAndAppData = new JButton("App and App Data");
    btnBackupAppAndAppData.setToolTipText("Backup app and it's data from android device");
    btnBackupAppAndAppData.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-all";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupAppAndAppData.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupAppAndAppData.setBounds(25, 70, 220, 75);
    panel_5.add(btnBackupAppAndAppData);

    final JButton btnBackupWholeDevice = new JButton("Whole Device");
    btnBackupWholeDevice.setToolTipText("Backup whole android device");
    btnBackupWholeDevice.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[6];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-all";
                commands[3] = "-apk";
                commands[4] = "-shared";
                commands[5] = "-system";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupWholeDevice.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupWholeDevice.setBounds(25, 303, 220, 75);
    panel_5.add(btnBackupWholeDevice);

    final JButton btnRestorePreviousBackup = new JButton("Previous Backup");
    btnRestorePreviousBackup.setToolTipText("Restore data to android device from the previous backup");
    btnRestorePreviousBackup.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Restoring can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the restore operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "restore";
                commands[2] = "backup.ab";
                ApplicationStatus.setText("Restoring...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Restore completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnRestorePreviousBackup.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRestorePreviousBackup.setBounds(510, 184, 220, 75);
    panel_5.add(btnRestorePreviousBackup);

    final JButton btnBackupSystem = new JButton("System");
    btnBackupSystem.setToolTipText("Backup android device system");
    btnBackupSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            BackupAndRestoreDone.setText("");
            try {
                ApplicationStatus.setText("Backup can take upto several minutes, please be patient...");
                JOptionPane.showMessageDialog(null,
                        "Unlock your device and confirm the backup operation when asked");
                String[] commands = new String[3];
                commands[0] = "adb";
                commands[1] = "backup";
                commands[2] = "-system";
                ApplicationStatus.setText("Performing backup...");
                Process p1 = Runtime.getRuntime().exec(commands, null);
                p1.waitFor();
                ApplicationStatus.setText("Backup completed successfully!");
                BackupAndRestoreDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                btnBackupSystem.setSelected(false);
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnBackupSystem.setBounds(270, 184, 220, 75);
    panel_5.add(btnBackupSystem);

    JPanel panel_2 = new JPanel();
    panel_2.setBackground(Color.WHITE);
    tabbedPane.addTab("Rebooter", null, panel_2, null);
    panel_2.setLayout(null);

    JLabel lblRebootFrom = new JLabel("Reboot from :");
    lblRebootFrom.setBounds(25, 180, 220, 15);
    panel_2.add(lblRebootFrom);

    JLabel lblRebootTo = new JLabel("Reboot to :");
    lblRebootTo.setBounds(25, 12, 220, 15);
    panel_2.add(lblRebootTo);

    JLabel lblNotFor = new JLabel("# Not for Samsung devices");
    lblNotFor.setBounds(514, 359, 238, 19);
    panel_2.add(lblNotFor);

    JLabel lblDeviceMust_1 = new JLabel("Device must be in fastboot mode (Except for Reboot System)");
    lblDeviceMust_1.setBounds(25, 332, 479, 19);
    panel_2.add(lblDeviceMust_1);

    JLabel lblYouMust_1 = new JLabel("* You must have a bootloader that supports fastboot commands");
    lblYouMust_1.setBounds(25, 359, 470, 19);
    panel_2.add(lblYouMust_1);

    JButton btnRebootFromFastboot = new JButton("Fastboot *");
    btnRebootFromFastboot.setToolTipText("Reboot android device from fastboot mode to normal");
    btnRebootFromFastboot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("fastboot reboot");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootFromFastboot.setBounds(28, 232, 220, 75);
    panel_2.add(btnRebootFromFastboot);

    JButton btnRebootToBootloaderFromFastboot = new JButton("Fastboot to Bootloader *");
    btnRebootToBootloaderFromFastboot.setToolTipText("Reboot to Bootloader mode while accessing fastboot mode");
    btnRebootToBootloaderFromFastboot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("fasboot reboot-bootloader");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToBootloaderFromFastboot.setBounds(281, 232, 220, 75);
    panel_2.add(btnRebootToBootloaderFromFastboot);

    JButton btnRebootToFastboot = new JButton("Fastboot");
    btnRebootToFastboot.setToolTipText("Reboot android device to fastboot mode");
    btnRebootToFastboot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot fastboot");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToFastboot.setBounds(281, 55, 220, 75);
    panel_2.add(btnRebootToFastboot);

    JButton btnRebootToBootloader = new JButton("Bootloader #");
    btnRebootToBootloader.setToolTipText("Reboot android device to bootloader mode");
    btnRebootToBootloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot bootloader");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToBootloader.setBounds(28, 55, 220, 75);
    panel_2.add(btnRebootToBootloader);

    JButton btnRebootToRecovery = new JButton("Recovery");
    btnRebootToRecovery.setToolTipText("Reboot android device to recovery mode");
    btnRebootToRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot recovery");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootToRecovery.setBounds(532, 55, 220, 75);
    panel_2.add(btnRebootToRecovery);

    JButton btnRebootSystem = new JButton("System");
    btnRebootSystem.setToolTipText("Reboot android device normally");
    btnRebootSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText("Rebooting...");
                Process p1 = Runtime.getRuntime().exec("adb reboot");
                p1.waitFor();
                ApplicationStatus.setText("Done");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnRebootSystem.setBounds(785, 55, 220, 75);
    panel_2.add(btnRebootSystem);

    JPanel panel_9 = new JPanel();
    panel_9.setBackground(Color.WHITE);
    tabbedPane.addTab("Bypass Security", null, panel_9, null);
    panel_9.setLayout(null);

    JLabel lblRootOperationsexperimental = new JLabel(
            "Method #1 : Root Operations (Recommended) [EXPERIMENTAL] :");
    lblRootOperationsexperimental.setBounds(12, 12, 507, 15);
    panel_9.add(lblRootOperationsexperimental);

    JButton btnPattern = new JButton("Pattern #");
    btnPattern.setToolTipText("Remove pattern security from android device (Experimental)");
    btnPattern.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Trying to break into security...");
                Process p1 = Runtime.getRuntime().exec("adb shell su -c rm /data/system/gesture.key");
                p1.waitFor();
                ApplicationStatus.setText(
                        "Done, now try to unlock the device with a random pattern then change security manually from settings");
            } catch (Exception e1) {
            }
        }
    });

    btnPattern.setBounds(220, 75, 220, 75);
    panel_9.add(btnPattern);

    JButton btnPasswordPin = new JButton("Password/ PIN #");
    btnPasswordPin.setToolTipText("Remove password or pin security from android device (Experimental)");
    btnPasswordPin.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Trying to break into security...");
                Process p1 = Runtime.getRuntime().exec("adb shell su -c rm /data/system/password.key");
                p1.waitFor();
                ApplicationStatus.setText("Done, check your device...");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnPasswordPin.setBounds(630, 75, 220, 75);
    panel_9.add(btnPasswordPin);

    JLabel lblMayNot = new JLabel("# Works on Android 4.4.x and lower");
    lblMayNot.setBounds(630, 250, 366, 15);
    panel_9.add(lblMayNot);

    JLabel lblNonRoot = new JLabel("Method # 2 : Non - Root/ Root Operations [EXPERIMENTAL] :");
    lblNonRoot.setBounds(12, 191, 507, 15);
    panel_9.add(lblNonRoot);

    JButton btnJellyBeanPatternPinPassword = new JButton("Pattern/ PIN/ Password *");
    btnJellyBeanPatternPinPassword
            .setToolTipText("Remove pattern, pin or password security from android device (Experimental)");
    btnJellyBeanPatternPinPassword.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                ApplicationStatus.setText("Trying to break into security...");
                Process p1 = Runtime.getRuntime().exec(
                        "adb shell am start -n com.android.settings/com.android.settings.ChooseLockGeneric --ez confirm_credentials false --ei lockscreen.password_type 0 --activity-clear-task");
                p1.waitFor();
                ApplicationStatus.setText("Rebooting...");
                Process p2 = Runtime.getRuntime().exec("adb reboot");
                p2.waitFor();
                ApplicationStatus.setText("Done, check your device...");
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnJellyBeanPatternPinPassword.setBounds(220, 250, 220, 75);
    panel_9.add(btnJellyBeanPatternPinPassword);

    JLabel lblWorksWell = new JLabel("* Works well on Jelly Bean Devices but may or");
    lblWorksWell.setBounds(630, 273, 366, 15);
    panel_9.add(lblWorksWell);

    JLabel lblNewLabel = new JLabel("may not work for older/ newer android versions");
    lblNewLabel.setBounds(640, 293, 356, 15);
    panel_9.add(lblNewLabel);

    JPanel panel_4 = new JPanel();
    panel_4.setBackground(Color.WHITE);
    tabbedPane.addTab("Logger", null, panel_4, null);
    panel_4.setLayout(null);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(0, 72, 1072, 285);
    panel_4.add(scrollPane);

    LogViewer = new JTextArea();
    LogViewer.setEditable(false);
    scrollPane.setViewportView(LogViewer);

    JButton btnSaveAsTextFile = new JButton("Save as a text file");
    btnSaveAsTextFile.setToolTipText("Save printed logcat as a text file on computer");
    btnSaveAsTextFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (LogViewer.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "No log found, please click view log");
            } else {
                ApplicationStatus.setText("");
                JFrame parentFrame = new JFrame();
                JFileChooser fileChooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter("Text Files", "txt");
                fileChooser.setFileFilter(filter);
                fileChooser.setDialogTitle("Save as a text file");
                int userSelection = fileChooser.showSaveDialog(parentFrame);
                if (userSelection == JFileChooser.APPROVE_OPTION) {
                    File fileToSave = fileChooser.getSelectedFile();
                    FileWriter write = null;
                    try {
                        write = new FileWriter(fileToSave.getAbsolutePath() + ".txt");
                        LogViewer.write(write);
                        ApplicationStatus.setText("Logcat saved");
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (write != null)
                            try {
                                write.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                    }
                }
            }
        }
    });

    btnSaveAsTextFile.setBounds(420, 13, 220, 47);
    panel_4.add(btnSaveAsTextFile);

    JButton btnClearLogcat = new JButton("Clear");
    btnClearLogcat.setToolTipText("Clean the printed logcat from the screen");
    btnClearLogcat.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            LogViewer.setText("");
            File file = new File(".logcat.txt");
            if (file.exists() && !file.isDirectory()) {
                file.delete();
            }
            ApplicationStatus.setText("Logcat cleared");
        }
    });
    btnClearLogcat.setBounds(12, 13, 220, 48);
    panel_4.add(btnClearLogcat);

    JButton btnViewLogcat = new JButton("View Logcat");
    btnViewLogcat.setToolTipText("Print android device logcat on screen");
    btnViewLogcat.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ApplicationStatus.setText("Generating logcat, please wait a moment...");
            try {
                Process p1 = Runtime.getRuntime().exec("adb logcat -d > /sdcard/.logcat.txt");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb logcat -c");
                p2.waitFor();
                Process p3 = Runtime.getRuntime().exec("adb pull /sdcard/.logcat.txt");
                p3.waitFor();
                Process p4 = Runtime.getRuntime().exec("adb shell rm /sdcard/.logcat.txt");
                p4.waitFor();
                try {
                    Reader reader = new FileReader(new File(".logcat.txt"));
                    LogViewer.read(reader, "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                File file = new File(".logcat.txt");
                if (file.exists() && !file.isDirectory()) {
                    file.delete();
                }
                ApplicationStatus.setText("");
            } catch (Exception e) {
                System.err.println(e);
            }
        }
    });

    btnViewLogcat.setBounds(838, 13, 220, 47);
    panel_4.add(btnViewLogcat);

    JLabel lblNoteLogcatG = new JLabel(
            "Note: Logcat generation takes some time, program may not respond for a few moments");
    lblNoteLogcatG.setBounds(12, 364, 1046, 15);
    panel_4.add(lblNoteLogcatG);

    JPanel panel = new JPanel();
    panel.setBackground(Color.WHITE);
    tabbedPane.addTab("Flasher", null, panel, null);
    panel.setLayout(null);

    final JButton btnFlashSystem = new JButton("System");
    btnFlashSystem.setToolTipText("Flash system partition");
    btnFlashSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase system");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "system";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashSystem.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    final JButton btnFlashData = new JButton("Data");
    btnFlashData.setToolTipText("Flash data partition");
    btnFlashData.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase data");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "data";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashData.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    final JButton btnFlashViaRecovery = new JButton("Flash via Recovery");
    btnFlashViaRecovery.setToolTipText("Flash a zip archive using recovery");
    btnFlashViaRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("zip Files", "zip");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                try {
                    JOptionPane.showMessageDialog(null,
                            "Select Update via ADB from recovery menu using physical keys on your device");
                    String[] commands = new String[3];
                    commands[0] = "adb";
                    commands[1] = "sideload";
                    commands[2] = file.getAbsolutePath();
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec(commands, null);
                    p1.waitFor();
                    ApplicationStatus.setText("Sideloaded...");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashViaRecovery.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    FlasherDone = new JLabel("");
    FlasherDone.setText("");
    FlasherDone.setBounds(760, 29, 300, 220);
    panel.add(FlasherDone);
    btnFlashViaRecovery.setBounds(25, 131, 220, 75);
    panel.add(btnFlashViaRecovery);
    btnFlashData.setBounds(541, 27, 220, 75);
    panel.add(btnFlashData);
    btnFlashSystem.setBounds(282, 236, 220, 75);
    panel.add(btnFlashSystem);

    final JButton btnFlashCache = new JButton("Cache");
    btnFlashCache.setToolTipText("Flash cache partition");
    btnFlashCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase cache");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "cache";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashCache.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashCache.setBounds(282, 27, 220, 75);
    panel.add(btnFlashCache);

    final JButton btnBootImage = new JButton("Boot");
    btnBootImage.setToolTipText("Flash boot partition");
    btnBootImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase boot");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "boot";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnBootImage.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnBootImage.setBounds(25, 27, 220, 75);
    panel.add(btnBootImage);

    final JButton btnFlashZipArchive = new JButton("Zip Archive");
    btnFlashZipArchive.setToolTipText("Flash a zip archive");
    btnFlashZipArchive.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("zip Files", "zip");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    String[] commands = new String[3];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = file.getAbsolutePath();
                    Process p1 = Runtime.getRuntime().exec(commands, null);
                    p1.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashZipArchive.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashZipArchive.setBounds(541, 236, 220, 75);
    panel.add(btnFlashZipArchive);

    final JButton btnFlashRecovery = new JButton("Recovery");
    btnFlashRecovery.setToolTipText("Flash recovery partition");
    btnFlashRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            FlasherDone.setText("");
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase recovery");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "recovery";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashRecovery.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashRecovery.setBounds(541, 131, 220, 75);
    panel.add(btnFlashRecovery);

    JLabel lblYouMust = new JLabel(
            "Note: Your device's bootloader must support fastboot commands and should be in fastboot mode");
    lblYouMust.setBounds(25, 356, 835, 19);
    panel.add(lblYouMust);

    final JButton btnFlashSplash = new JButton("Splash");
    btnFlashSplash.setToolTipText("Flash splash partition");
    btnFlashSplash.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase splash");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "splash";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashSplash.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });

    btnFlashSplash.setBounds(25, 236, 220, 75);
    panel.add(btnFlashSplash);

    JButton btnFlashRadio = new JButton("Radio");
    btnFlashRadio.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            JFileChooser chooser = new JFileChooser();
            FileNameExtensionFilter filter = new FileNameExtensionFilter("IMG Files", "img");
            chooser.setFileFilter(filter);
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = chooser.getSelectedFile();
                String filename = chooser.getSelectedFile().getName();
                try {
                    ApplicationStatus.setText("Flashing...");
                    Process p1 = Runtime.getRuntime().exec("fastboot erase radio");
                    p1.waitFor();
                    String[] commands = new String[4];
                    commands[0] = "fastboot";
                    commands[1] = "flash";
                    commands[2] = "radio";
                    commands[3] = file.getAbsolutePath();
                    Process p2 = Runtime.getRuntime().exec(commands, null);
                    p2.waitFor();
                    ApplicationStatus
                            .setText(filename + "has been successfully flashed on your android device");
                    FlasherDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
                    btnFlashSplash.setSelected(false);
                } catch (Exception e1) {
                    System.err.println(e1);
                }
            }
        }
    });
    btnFlashRadio.setToolTipText("Flash radio partition");
    btnFlashRadio.setBounds(282, 131, 220, 75);
    panel.add(btnFlashRadio);

    JPanel panel_1 = new JPanel();
    panel_1.setBackground(Color.WHITE);
    tabbedPane.addTab("Wiper", null, panel_1, null);
    panel_1.setLayout(null);

    WiperDone = new JLabel("");
    WiperDone.setText("");
    WiperDone.setBounds(758, 26, 300, 220);
    panel_1.add(WiperDone);

    JLabel label_13 = new JLabel("** Device must be rooted");
    label_13.setBounds(25, 336, 252, 19);
    panel_1.add(label_13);

    JButton btnWipeRecovery = new JButton("Recovery");
    btnWipeRecovery.setToolTipText("Wipe recovery partition");
    btnWipeRecovery.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase cache");
                p1.waitFor();
                ApplicationStatus.setText("Recovery has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeRecovery.setBounds(541, 131, 220, 75);
    panel_1.add(btnWipeRecovery);

    JButton btnWipeBoot = new JButton("Boot");
    btnWipeBoot.setToolTipText("Flash boot partition");
    btnWipeBoot.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase boot");
                p1.waitFor();
                ApplicationStatus.setText("Boot has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeBoot.setBounds(25, 27, 220, 75);
    panel_1.add(btnWipeBoot);

    JButton btnWipeSystem = new JButton("System");
    btnWipeSystem.setToolTipText("Wipe system partition");
    btnWipeSystem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase system");
                p1.waitFor();
                ApplicationStatus.setText("System has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeSystem.setBounds(282, 236, 220, 75);
    panel_1.add(btnWipeSystem);

    JButton btnWipeSplash = new JButton("Splash");
    btnWipeSplash.setToolTipText("Wipe splash partition");
    btnWipeSplash.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase splash");
                p1.waitFor();
                ApplicationStatus.setText("Splash has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeSplash.setBounds(25, 236, 220, 75);
    panel_1.add(btnWipeSplash);

    JButton btnWipeData = new JButton("Data");
    btnWipeData.setToolTipText("Wipe data partition");
    btnWipeData.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase data");
                p1.waitFor();
                ApplicationStatus.setText("Data has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeData.setBounds(25, 131, 220, 75);
    panel_1.add(btnWipeData);

    JButton btnFlashDalvikCache = new JButton("Dalvik Cache **");
    btnFlashDalvikCache.setToolTipText("Wipe dalvik cache");
    btnFlashDalvikCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("adb shell su -c rm * /data/dalvik-cache");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("adb shell su -c rm * /cache/dalvik-cache");
                p2.waitFor();
                ApplicationStatus.setText("Dalvik Cache has been wiped! Now rebooting device...");
                Process p3 = Runtime.getRuntime().exec("adb reboot");
                p3.waitFor();
                ApplicationStatus.setText("Done");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnFlashDalvikCache.setBounds(541, 27, 220, 75);
    panel_1.add(btnFlashDalvikCache);

    JButton btnWipeCache = new JButton("Cache");
    btnWipeCache.setToolTipText("Wipe cache partition");
    btnWipeCache.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase cache");
                p1.waitFor();
                ApplicationStatus.setText("Cache has been wiped! Now rebooting device...");
                Process p2 = Runtime.getRuntime().exec("adb reboot");
                p2.waitFor();
                ApplicationStatus.setText("Done");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnWipeCache.setBounds(282, 27, 220, 75);
    panel_1.add(btnWipeCache);

    JButton btnWipeRadio = new JButton("Radio");
    btnWipeRadio.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            WiperDone.setText("");
            try {
                ApplicationStatus.setText("Wiping...");
                Process p1 = Runtime.getRuntime().exec("fastboot erase radio");
                p1.waitFor();
                ApplicationStatus.setText("Radio has been wiped");
                WiperDone.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Done.png")));
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });
    btnWipeRadio.setToolTipText("Wipe radio partition");
    btnWipeRadio.setBounds(282, 131, 220, 75);
    panel_1.add(btnWipeRadio);

    JLabel lblNoteYourDevices = new JLabel(
            "Note: Your device's bootloader must support fastboot commands and should be in fastboot mode");
    lblNoteYourDevices.setBounds(25, 357, 835, 19);
    panel_1.add(lblNoteYourDevices);

    JPanel panel_3 = new JPanel();
    panel_3.setBackground(Color.WHITE);
    tabbedPane.addTab("Bootloader", null, panel_3, null);
    panel_3.setLayout(null);

    JLabel label_17 = new JLabel("Note: Don't worry if the app says to connect your device while");
    label_17.setBounds(66, 320, 600, 19);
    panel_3.add(label_17);

    JLabel label_18 = new JLabel("android is not booted ex. fastboot, bootloader, booting etc.");
    label_18.setBounds(66, 337, 600, 19);
    panel_3.add(label_18);

    JLabel lblOnlyForNexus = new JLabel(
            "Works only with specific devices ex. Nexus, Android One, FEW MTK devices etc.");
    lblOnlyForNexus.setBounds(66, 351, 600, 24);
    panel_3.add(lblOnlyForNexus);

    JButton btnUnlockBootloader = new JButton("Unlock Bootloader");
    btnUnlockBootloader.setToolTipText("Unlock android device bootloader");
    btnUnlockBootloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                ApplicationStatus.setText(
                        "Unlocking bootloader will factory reset your device and may void your device warranty!");
                JOptionPane.showMessageDialog(null,
                        "You will need to re-enable USB debugging later as your device will get factory reset");
                Process p1 = Runtime.getRuntime().exec("adb reboot bootloader");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot oem unlock");
                p2.waitFor();
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnUnlockBootloader.setBounds(282, 27, 220, 75);
    panel_3.add(btnUnlockBootloader);

    JButton btnLockBootloader = new JButton("Lock Bootloader");
    btnLockBootloader.setToolTipText("Lock android device bootloader");
    btnLockBootloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Process p1 = Runtime.getRuntime().exec("adb reboot bootloader");
                p1.waitFor();
                Process p2 = Runtime.getRuntime().exec("fastboot oem lock");
                p2.waitFor();
            } catch (Exception e1) {
                System.err.println(e1);
            }
        }
    });

    btnLockBootloader.setBounds(25, 27, 220, 75);
    panel_3.add(btnLockBootloader);

    JPanel panel_6 = new JPanel();
    panel_6.setBackground(Color.WHITE);
    tabbedPane.addTab("Crypto", null, panel_6, null);
    panel_6.setLayout(null);

    JButton btnSHA512 = new JButton("SHA-512");
    btnSHA512.setToolTipText("Calculate SHA-512 sum of a file");
    btnSHA512.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha512Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA512.setBounds(541, 131, 220, 75);
    panel_6.add(btnSHA512);

    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setBounds(12, 332, 900, 25);
    panel_6.add(scrollPane_2);

    InputCrypto = new JTextArea();
    InputCrypto.setToolTipText("Input sum to be compared with calculated sum");
    scrollPane_2.setViewportView(InputCrypto);

    JLabel lblLabelCalculatedSum = new JLabel("Calculated Sum :");
    lblLabelCalculatedSum.setBounds(12, 240, 235, 17);
    panel_6.add(lblLabelCalculatedSum);

    JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane_1.setBounds(12, 268, 900, 28);
    panel_6.add(scrollPane_1);

    CalculatedCrypto = new JTextArea();
    CalculatedCrypto.setToolTipText("Calclated sum");
    scrollPane_1.setViewportView(CalculatedCrypto);
    CalculatedCrypto.setEditable(false);

    JButton btnSHA384 = new JButton("SHA-384");
    btnSHA384.setToolTipText("Calculate SHA-384 sum of a file");
    btnSHA384.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha384Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA384.setBounds(282, 131, 220, 75);
    panel_6.add(btnSHA384);

    JButton btnSHA256 = new JButton("SHA-256");
    btnSHA256.setToolTipText("Calculate SHA-256 sum of a file");
    btnSHA256.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha256Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA256.setBounds(25, 131, 220, 75);
    panel_6.add(btnSHA256);

    JButton btnSHA1 = new JButton("SHA-1");
    btnSHA1.setToolTipText("Calculate SHA-1 sum of a file");
    btnSHA1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.sha1Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnSHA1.setBounds(541, 27, 220, 75);
    panel_6.add(btnSHA1);

    JButton btnMD5 = new JButton("MD5");
    btnMD5.setToolTipText("Calculate MD5 sum of a file");
    btnMD5.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            JFileChooser chooser = new JFileChooser();
            int returnVal = chooser.showOpenDialog(getParent());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = new File("");
                ApplicationStatus.setText("Calculating...");
                CalculatedCrypto.setText(DigestUtils.md5Hex(file.getAbsolutePath()));
                ApplicationStatus.setText("");
            }
        }
    });

    btnMD5.setBounds(282, 27, 220, 75);
    panel_6.add(btnMD5);

    JLabel lblInputSumTo = new JLabel("Input Sum to be compared :");
    lblInputSumTo.setBounds(12, 308, 235, 15);
    panel_6.add(lblInputSumTo);

    JButton btnCompare = new JButton("Compare");
    btnCompare.setToolTipText("Click to compare calculated sum and input sum");
    btnCompare.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (InputCrypto.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Please select algorithm and a file");
            }
            if (CalculatedCrypto.getText().equals("")) {
                JOptionPane.showMessageDialog(null, "Please input a sum to be compared");
            } else {
                if (InputCrypto.getText().equalsIgnoreCase(CalculatedCrypto.getText())) {
                    JOptionPane.showMessageDialog(null, "Both sums are matched");
                } else {
                    JOptionPane.showMessageDialog(null, "Sums are not matched!");
                }
            }
        }
    });
    btnCompare.setBounds(924, 268, 134, 89);
    panel_6.add(btnCompare);

    JButton btnClearCalculatedCrypto = new JButton("Clear");
    btnClearCalculatedCrypto.setToolTipText("Clear the calculated sum");
    btnClearCalculatedCrypto.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            CalculatedCrypto.setText("");
            InputCrypto.setText("");
        }
    });
    btnClearCalculatedCrypto.setBounds(25, 27, 220, 75);
    panel_6.add(btnClearCalculatedCrypto);

    JLabel label_2 = new JLabel("");
    label_2.setBounds(50, 0, 1038, 256);
    label_2.setIcon(new ImageIcon(Interface.class.getResource("/graphics/Interface_logo.png")));
    contentPane.add(label_2);

    new Updater();

    Thread t = new Thread(r); // Background services
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() { // Exit sequence
        public void run() {
            try {
                System.out.println("Killing ADB instance...");
                Process p1 = Runtime.getRuntime().exec("adb kill-server");
                p1.waitFor();
                System.out.println("Cleaning cache...");
                File file2 = new File(".CheckADBConnection");
                if (file2.exists() && !file2.isDirectory()) {
                    file2.delete();
                }
                File file3 = new File("su");
                if (file3.exists() && !file3.isDirectory()) {
                    file3.delete();
                }
                File file4 = new File(".logcat.txt");
                if (file4.exists() && !file4.isDirectory()) {
                    file4.delete();
                }
                File file5 = new File(".userapps.txt");
                if (file5.exists() && !file5.isDirectory()) {
                    file5.delete();
                }
                File file6 = new File(".privapps.txt");
                if (file6.exists() && !file6.isDirectory()) {
                    file6.delete();
                }
                File file7 = new File(".systemapps.txt");
                if (file7.exists() && !file7.isDirectory()) {
                    file4.delete();
                }
                System.out.println("Droid PC Suite terminated");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    });
}

From source file:eu.cassandra.training.gui.MainGUI.java

/**
 * Constructor of the Training Module GUI.
 * //from  w  w  w  .j a  v  a 2  s. c o m
 * @throws UnsupportedLookAndFeelException
 * @throws IllegalAccessException
 * @throws InstantiationException
 * @throws ClassNotFoundException
 * @throws FileNotFoundException
 */
public MainGUI() throws ClassNotFoundException, InstantiationException, IllegalAccessException,
        UnsupportedLookAndFeelException, FileNotFoundException {
    setForeground(new Color(0, 204, 51));

    // Enable the closing of the frame when pressing the x on the upper corner
    // of the window
    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            Utils.cleanFiles();
            System.exit(0);
        }
    });

    // Cleaning temporary files from the temp folder when starting the GUI.
    // Utils.cleanFiles();

    // Change the platforms look and feel to Nimbus
    LookAndFeel lnf = new javax.swing.plaf.nimbus.NimbusLookAndFeel();
    UIManager.put("NimbusLookAndFeel", Color.GREEN);
    UIManager.setLookAndFeel(lnf);

    // Setting the basic attributes of the Training Module GUI
    setTitle("Training Module (BETA)");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 1228, 799);

    // Creating the menu bar and adding the menu items
    JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);

    JMenu mnNewMenu = new JMenu("File");
    menuBar.add(mnNewMenu);

    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Utils.cleanFiles();
            System.exit(0);
        }
    });
    mnNewMenu.add(mntmExit);

    JMenu mnExit = new JMenu("Help");
    menuBar.add(mnExit);

    JMenuItem mntmManual = new JMenuItem("Manual");
    mnExit.add(mntmManual);

    JMenuItem mntmAbout = new JMenuItem("About");
    mnExit.add(mntmAbout);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);

    // Adding the tabbed pane to the content pane
    final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    GroupLayout gl_contentPane = new GroupLayout(contentPane);
    gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addComponent(tabbedPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 1202, Short.MAX_VALUE));
    gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_contentPane.createSequentialGroup()
                    .addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 736, GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(47, Short.MAX_VALUE)));

    // TABS //

    final JPanel importTab = new JPanel();
    tabbedPane.addTab("Import Data", null, importTab, null);
    tabbedPane.setDisplayedMnemonicIndexAt(0, 0);
    tabbedPane.setEnabledAt(0, true);
    importTab.setLayout(null);

    final JPanel trainingTab = new JPanel();
    tabbedPane.addTab("Train Activity Models", null, trainingTab, null);
    tabbedPane.setDisplayedMnemonicIndexAt(1, 1);
    tabbedPane.setEnabledAt(1, false);
    trainingTab.setLayout(null);

    final JPanel createResponseTab = new JPanel();

    tabbedPane.addTab("Create Response Models", null, createResponseTab, null);
    tabbedPane.setEnabledAt(2, false);
    createResponseTab.setLayout(null);

    // RESPONSE MODEL TAB //

    final JPanel responseParametersPanel = new JPanel();
    responseParametersPanel.setLayout(null);
    responseParametersPanel.setBorder(
            new TitledBorder(null, "Response Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    responseParametersPanel.setBounds(6, 6, 394, 271);
    createResponseTab.add(responseParametersPanel);

    final JPanel activityModelSelectionPanel = new JPanel();
    activityModelSelectionPanel.setLayout(null);
    activityModelSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Activity Model Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    activityModelSelectionPanel.setBounds(6, 516, 394, 192);
    createResponseTab.add(activityModelSelectionPanel);

    final JPanel responsePanel = new JPanel();
    responsePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Activity Model Change Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    responsePanel.setBounds(417, 6, 770, 385);
    createResponseTab.add(responsePanel);
    responsePanel.setLayout(new BorderLayout(0, 0));

    final JPanel pricingPreviewPanel = new JPanel();
    pricingPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Pricing Scheme Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pricingPreviewPanel.setBounds(417, 438, 770, 259);
    createResponseTab.add(pricingPreviewPanel);
    pricingPreviewPanel.setLayout(new BorderLayout(0, 0));

    final JPanel pricingSchemePanel = new JPanel();
    pricingSchemePanel.setLayout(null);
    pricingSchemePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Pricing Scheme Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pricingSchemePanel.setBounds(6, 274, 394, 243);
    createResponseTab.add(pricingSchemePanel);

    // /////////////////
    // RESPONSE TAB //
    // ////////////////

    // RESPONSE PARAMETERS //

    final JLabel lblSensitivity = new JLabel("Sensitivity");
    lblSensitivity.setBounds(10, 28, 78, 16);
    responseParametersPanel.add(lblSensitivity);

    final JSlider sensitivitySlider = new JSlider();
    sensitivitySlider.setPaintLabels(true);
    sensitivitySlider.setSnapToTicks(true);
    sensitivitySlider.setPaintTicks(true);
    sensitivitySlider.setMinorTickSpacing(10);
    sensitivitySlider.setMajorTickSpacing(10);
    sensitivitySlider.setBounds(111, 28, 214, 45);
    responseParametersPanel.add(sensitivitySlider);

    final JLabel lblAwareness = new JLabel("Awareness");
    lblAwareness.setBounds(10, 79, 78, 16);
    responseParametersPanel.add(lblAwareness);

    final JSlider awarenessSlider = new JSlider();
    awarenessSlider.setPaintLabels(true);
    awarenessSlider.setPaintTicks(true);
    awarenessSlider.setMajorTickSpacing(10);
    awarenessSlider.setMinorTickSpacing(10);
    awarenessSlider.setSnapToTicks(true);
    awarenessSlider.setBounds(111, 79, 214, 45);
    responseParametersPanel.add(awarenessSlider);

    final JLabel label_7 = new JLabel("Response Model");
    label_7.setBounds(10, 153, 103, 16);
    responseParametersPanel.add(label_7);

    final JRadioButton optimalCaseRadioButton = new JRadioButton("Optimal Case Scenario");
    responseModelButtonGroup.add(optimalCaseRadioButton);
    optimalCaseRadioButton.setBounds(111, 131, 170, 18);
    responseParametersPanel.add(optimalCaseRadioButton);

    final JRadioButton normalCaseRadioButton = new JRadioButton("Normal Case Scenario");
    normalCaseRadioButton.setSelected(true);
    responseModelButtonGroup.add(normalCaseRadioButton);
    normalCaseRadioButton.setBounds(111, 152, 170, 18);
    responseParametersPanel.add(normalCaseRadioButton);

    final JRadioButton discreteCaseRadioButton = new JRadioButton("Discrete Case Scenario");
    discreteCaseRadioButton.setSelected(true);
    responseModelButtonGroup.add(discreteCaseRadioButton);
    discreteCaseRadioButton.setBounds(111, 173, 170, 18);
    responseParametersPanel.add(discreteCaseRadioButton);

    final JButton previewResponseButton = new JButton("Preview Response Model");
    previewResponseButton.setEnabled(false);
    previewResponseButton.setBounds(24, 198, 157, 28);
    responseParametersPanel.add(previewResponseButton);

    final JButton createResponseButton = new JButton("Create Response Model");
    createResponseButton.setEnabled(false);
    createResponseButton.setBounds(191, 198, 162, 28);
    responseParametersPanel.add(createResponseButton);

    final JButton createResponseAllButton = new JButton("Create Response All");
    createResponseAllButton.setEnabled(false);
    createResponseAllButton.setBounds(111, 232, 157, 28);
    responseParametersPanel.add(createResponseAllButton);

    // SELECT ACTIVITY MODEL //

    final JLabel lblSelectedActivity = new JLabel("Selected Activity");
    lblSelectedActivity.setBounds(10, 21, 130, 16);
    activityModelSelectionPanel.add(lblSelectedActivity);

    JScrollPane activityListScrollPane = new JScrollPane();
    activityListScrollPane.setBounds(20, 39, 355, 143);
    activityModelSelectionPanel.add(activityListScrollPane);

    final JList<String> activitySelectList = new JList<String>();
    activityListScrollPane.setViewportView(activitySelectList);
    activitySelectList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    final JButton commitButton = new JButton("Commit");
    commitButton.setEnabled(false);
    commitButton.setBounds(151, 209, 89, 23);
    pricingSchemePanel.add(commitButton);

    JLabel lblBasicSchema = new JLabel("Basic Schema (Start-End-Value)");
    lblBasicSchema.setBounds(10, 18, 182, 14);
    pricingSchemePanel.add(lblBasicSchema);

    JLabel lblNewSchemastart = new JLabel("New Schema (Start-End-Value)");
    lblNewSchemastart.setBounds(197, 18, 177, 14);
    pricingSchemePanel.add(lblNewSchemastart);

    JScrollPane basicPricingSchemeScrollPane = new JScrollPane();
    basicPricingSchemeScrollPane.setBounds(10, 43, 177, 161);
    pricingSchemePanel.add(basicPricingSchemeScrollPane);

    final JTextPane basicPricingSchemePane = new JTextPane();
    basicPricingSchemeScrollPane.setViewportView(basicPricingSchemePane);
    basicPricingSchemePane.setText("00:00-23:59-0.05");

    JScrollPane newPricingScrollPane = new JScrollPane();
    newPricingScrollPane.setBounds(197, 43, 177, 161);
    pricingSchemePanel.add(newPricingScrollPane);

    final JTextPane newPricingSchemePane = new JTextPane();

    newPricingScrollPane.setViewportView(newPricingSchemePane);

    JPanel buttonPanel = new JPanel();
    buttonPanel.setBounds(682, 390, 265, 33);
    createResponseTab.add(buttonPanel);

    final JButton dailyResponseButton = new JButton("Daily Times");
    dailyResponseButton.setEnabled(false);
    buttonPanel.add(dailyResponseButton);

    final JButton startResponseButton = new JButton("Start Time");

    startResponseButton.setEnabled(false);
    buttonPanel.add(startResponseButton);

    final JPanel exportTab = new JPanel();
    tabbedPane.addTab("Export Models", null, exportTab, null);
    tabbedPane.setEnabledAt(3, false);
    exportTab.setLayout(null);

    // PANELS //

    // DATA IMPORT TAB //

    final JPanel dataFilePanel = new JPanel();
    dataFilePanel
            .setBorder(new TitledBorder(null, "Data File", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    dataFilePanel.setBounds(6, 6, 622, 284);
    importTab.add(dataFilePanel);
    dataFilePanel.setLayout(null);

    final JPanel disaggregationPanel = new JPanel();
    disaggregationPanel.setLayout(null);
    disaggregationPanel.setBorder(
            new TitledBorder(null, "Disaggregation", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    disaggregationPanel.setBounds(629, 6, 567, 284);
    importTab.add(disaggregationPanel);

    final JPanel dataReviewPanel = new JPanel();
    dataReviewPanel.setBorder(
            new TitledBorder(null, "Data Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    dataReviewPanel.setBounds(6, 293, 622, 407);
    importTab.add(dataReviewPanel);
    dataReviewPanel.setLayout(new BorderLayout(0, 0));

    final JPanel consumptionModelPanel = new JPanel();
    consumptionModelPanel.setBounds(629, 293, 567, 407);
    importTab.add(consumptionModelPanel);
    consumptionModelPanel.setBorder(
            new TitledBorder(null, "Consumption Model", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    consumptionModelPanel.setLayout(new BorderLayout(0, 0));

    // TRAINING ACTIVITY TAB //

    final JPanel trainingParametersPanel = new JPanel();
    trainingParametersPanel.setLayout(null);
    trainingParametersPanel.setBorder(
            new TitledBorder(null, "Training Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    trainingParametersPanel.setBounds(6, 6, 621, 256);
    trainingTab.add(trainingParametersPanel);

    final JPanel applianceSelectionPanel = new JPanel();
    applianceSelectionPanel.setLayout(null);
    applianceSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Appliance/Activity Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    applianceSelectionPanel.setBounds(630, 6, 557, 256);
    trainingTab.add(applianceSelectionPanel);

    final JPanel expectedPowerPanel = new JPanel();
    expectedPowerPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Expected Power Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    expectedPowerPanel.setBounds(630, 261, 557, 447);
    trainingTab.add(expectedPowerPanel);
    expectedPowerPanel.setLayout(new BorderLayout(0, 0));
    contentPane.setLayout(gl_contentPane);

    // EXPORT TAB //

    JPanel modelExportPanel = new JPanel();
    modelExportPanel.setLayout(null);
    modelExportPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Model Export Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    modelExportPanel.setBounds(10, 11, 596, 267);
    exportTab.add(modelExportPanel);

    final JPanel exportPreviewPanel = new JPanel();
    exportPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Export Model Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    exportPreviewPanel.setBounds(10, 310, 1187, 387);
    exportTab.add(exportPreviewPanel);
    exportPreviewPanel.setLayout(new BorderLayout(0, 0));

    JPanel exportButtonsPanel = new JPanel();
    exportButtonsPanel.setBounds(322, 279, 536, 33);
    exportTab.add(exportButtonsPanel);

    JPanel connectionPanel = new JPanel();
    connectionPanel.setLayout(null);
    connectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Connection Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    connectionPanel.setBounds(606, 11, 581, 267);
    exportTab.add(connectionPanel);

    // COMPONENTS //

    // IMPORT TAB //

    // DATA IMPORT //

    final JLabel lblSource = new JLabel("Data Source:");
    lblSource.setBounds(23, 47, 71, 16);
    dataFilePanel.add(lblSource);

    final JTextField pathField = new JTextField();
    pathField.setEditable(false);
    pathField.setBounds(99, 41, 405, 28);
    dataFilePanel.add(pathField);
    pathField.setColumns(10);

    final JButton dataBrowseButton = new JButton("Browse");
    dataBrowseButton.setBounds(516, 41, 87, 28);
    dataFilePanel.add(dataBrowseButton);

    final JButton resetButton = new JButton("Reset");
    resetButton.setBounds(516, 81, 87, 28);
    dataFilePanel.add(resetButton);

    final JLabel lblDataMeasurementsFrom = new JLabel("Data Measurements From:");
    lblDataMeasurementsFrom.setBounds(23, 90, 154, 16);
    dataFilePanel.add(lblDataMeasurementsFrom);

    final JRadioButton singleApplianceRadioButton = new JRadioButton("Single Appliance");
    singleApplianceRadioButton.setEnabled(false);
    dataMeasurementsButtonGroup.add(singleApplianceRadioButton);
    singleApplianceRadioButton.setBounds(242, 110, 115, 18);
    dataFilePanel.add(singleApplianceRadioButton);

    final JRadioButton installationRadioButton = new JRadioButton("Installation");
    installationRadioButton.setSelected(true);
    installationRadioButton.setEnabled(false);
    dataMeasurementsButtonGroup.add(installationRadioButton);
    installationRadioButton.setBounds(242, 89, 115, 18);
    dataFilePanel.add(installationRadioButton);

    final JLabel labelConsumptionModel = new JLabel("Consumption Model:");
    labelConsumptionModel.setBounds(23, 179, 120, 16);
    dataFilePanel.add(labelConsumptionModel);

    final JButton importDataButton = new JButton("Import Data");
    importDataButton.setEnabled(false);
    importDataButton.setBounds(23, 237, 126, 28);
    dataFilePanel.add(importDataButton);

    final JButton disaggregateButton = new JButton("Disaggregate");
    disaggregateButton.setEnabled(false);
    disaggregateButton.setBounds(216, 237, 147, 28);
    dataFilePanel.add(disaggregateButton);

    final JButton createEventsButton = new JButton("Create Events Dataset");
    createEventsButton.setEnabled(false);
    createEventsButton.setBounds(422, 237, 181, 28);
    dataFilePanel.add(createEventsButton);

    final JTextField consumptionPathField = new JTextField();
    consumptionPathField.setEnabled(false);
    consumptionPathField.setEditable(false);
    consumptionPathField.setColumns(10);
    consumptionPathField.setBounds(99, 197, 405, 28);
    dataFilePanel.add(consumptionPathField);

    final JButton consumptionBrowseButton = new JButton("Browse");
    consumptionBrowseButton.setEnabled(false);
    consumptionBrowseButton.setBounds(516, 197, 87, 28);
    dataFilePanel.add(consumptionBrowseButton);

    JLabel lblTypeOfMeasurements = new JLabel("Type of Measurements");
    lblTypeOfMeasurements.setBounds(23, 141, 154, 16);
    dataFilePanel.add(lblTypeOfMeasurements);

    final JRadioButton activePowerRadioButton = new JRadioButton("Active Power (P)");
    powerButtonGroup.add(activePowerRadioButton);
    activePowerRadioButton.setEnabled(false);
    activePowerRadioButton.setBounds(242, 140, 115, 18);
    dataFilePanel.add(activePowerRadioButton);

    final JRadioButton activeAndReactivePowerRadioButton = new JRadioButton("Active and Reactive Power (P, Q)");
    activeAndReactivePowerRadioButton.setSelected(true);
    powerButtonGroup.add(activeAndReactivePowerRadioButton);
    activeAndReactivePowerRadioButton.setEnabled(false);
    activeAndReactivePowerRadioButton.setBounds(242, 161, 262, 18);
    dataFilePanel.add(activeAndReactivePowerRadioButton);

    // //////////////////
    // DISAGGREGATION //
    // /////////////////

    final JLabel lblAppliancesDetected = new JLabel("Detected Appliances ");
    lblAppliancesDetected.setBounds(18, 33, 130, 16);
    disaggregationPanel.add(lblAppliancesDetected);

    JScrollPane scrollPane_2 = new JScrollPane();
    scrollPane_2.setBounds(145, 31, 396, 231);
    disaggregationPanel.add(scrollPane_2);

    final JList<String> detectedApplianceList = new JList<String>();
    scrollPane_2.setViewportView(detectedApplianceList);
    detectedApplianceList.setEnabled(false);
    detectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    // ////////////////
    // TRAINING TAB //
    // ////////////////

    // TRAINING PARAMETERS //

    final JLabel label_1 = new JLabel("Times Per Day");
    label_1.setBounds(19, 40, 103, 16);
    trainingParametersPanel.add(label_1);

    final JRadioButton timesHistogramRadioButton = new JRadioButton("Histogram");
    timesHistogramRadioButton.setSelected(true);
    timesDailyButtonGroup.add(timesHistogramRadioButton);
    timesHistogramRadioButton.setBounds(160, 38, 87, 18);
    trainingParametersPanel.add(timesHistogramRadioButton);

    final JRadioButton timesNormalRadioButton = new JRadioButton("Normal Distribution");
    timesNormalRadioButton.setEnabled(false);
    timesDailyButtonGroup.add(timesNormalRadioButton);
    timesNormalRadioButton.setBounds(304, 40, 137, 18);
    trainingParametersPanel.add(timesNormalRadioButton);

    JRadioButton timesGaussianRadioButton = new JRadioButton("Gaussian Mixture");
    timesGaussianRadioButton.setEnabled(false);
    timesDailyButtonGroup.add(timesGaussianRadioButton);
    timesGaussianRadioButton.setBounds(478, 38, 137, 18);
    trainingParametersPanel.add(timesGaussianRadioButton);

    final JLabel label_2 = new JLabel("Start Time");
    label_2.setBounds(19, 133, 103, 16);
    trainingParametersPanel.add(label_2);

    final JRadioButton startHistogramRadioButton = new JRadioButton("Histogram");
    startHistogramRadioButton.setSelected(true);
    startTimeButtonGroup.add(startHistogramRadioButton);
    startHistogramRadioButton.setBounds(160, 131, 87, 18);
    trainingParametersPanel.add(startHistogramRadioButton);

    final JRadioButton startNormalRadioButton = new JRadioButton("Normal Distribution");
    // startNormalRadioButton.setEnabled(false);
    startTimeButtonGroup.add(startNormalRadioButton);
    startNormalRadioButton.setBounds(304, 133, 137, 18);
    trainingParametersPanel.add(startNormalRadioButton);

    final JRadioButton startGaussianRadioButton = new JRadioButton("Gaussian Mixture");
    startGaussianRadioButton.setSelected(true);
    startTimeButtonGroup.add(startGaussianRadioButton);
    startGaussianRadioButton.setBounds(478, 131, 137, 18);
    trainingParametersPanel.add(startGaussianRadioButton);

    final JLabel label_3 = new JLabel("Duration");
    label_3.setBounds(19, 86, 103, 16);
    trainingParametersPanel.add(label_3);

    final JRadioButton durationHistogramRadioButton = new JRadioButton("Histogram");
    durationHistogramRadioButton.setSelected(true);
    durationButtonGroup.add(durationHistogramRadioButton);
    durationHistogramRadioButton.setBounds(160, 84, 87, 18);
    trainingParametersPanel.add(durationHistogramRadioButton);

    final JRadioButton durationNormalRadioButton = new JRadioButton("Normal Distribution");
    durationNormalRadioButton.setSelected(true);
    durationButtonGroup.add(durationNormalRadioButton);
    durationNormalRadioButton.setBounds(304, 86, 137, 18);
    trainingParametersPanel.add(durationNormalRadioButton);

    final JRadioButton durationGaussianRadioButton = new JRadioButton("Gaussian Mixture");
    durationButtonGroup.add(durationGaussianRadioButton);
    durationGaussianRadioButton.setBounds(478, 84, 137, 18);
    trainingParametersPanel.add(durationGaussianRadioButton);

    final JButton trainingButton = new JButton("Train");
    trainingButton.setBounds(125, 194, 115, 28);
    trainingParametersPanel.add(trainingButton);

    final JButton trainAllButton = new JButton("Train All");
    trainAllButton.setBounds(366, 194, 115, 28);
    trainingParametersPanel.add(trainAllButton);

    // APPLIANCE SELECTION //

    final JLabel label_4 = new JLabel("Selected Appliance");
    label_4.setBounds(18, 33, 130, 16);
    applianceSelectionPanel.add(label_4);

    JScrollPane scrollPane_1 = new JScrollPane();
    scrollPane_1.setBounds(128, 29, 419, 216);
    applianceSelectionPanel.add(scrollPane_1);

    final JList<String> selectedApplianceList = new JList<String>();
    scrollPane_1.setViewportView(selectedApplianceList);
    selectedApplianceList.setEnabled(false);
    selectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    // DISTRIBUTION SELECTION //

    JPanel distributionSelectionPanel = new JPanel();
    distributionSelectionPanel.setBounds(80, 261, 482, 33);
    trainingTab.add(distributionSelectionPanel);

    final JButton dailyTimesButton = new JButton("Daily Times");
    dailyTimesButton.setEnabled(false);
    distributionSelectionPanel.add(dailyTimesButton);

    final JButton durationButton = new JButton("Duration");
    durationButton.setEnabled(false);
    distributionSelectionPanel.add(durationButton);

    final JButton startTimeButton = new JButton("Start Time");
    startTimeButton.setEnabled(false);
    distributionSelectionPanel.add(startTimeButton);

    final JButton startTimeBinnedButton = new JButton("Start Time Binned");
    startTimeBinnedButton.setEnabled(false);
    distributionSelectionPanel.add(startTimeBinnedButton);

    final JPanel distributionPreviewPanel = new JPanel();
    distributionPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"),
            "Distribution Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    distributionPreviewPanel.setBounds(6, 299, 621, 409);
    trainingTab.add(distributionPreviewPanel);
    distributionPreviewPanel.setLayout(new BorderLayout(0, 0));

    // //////////////////
    // EXPORT TAB ///////
    // /////////////////

    JLabel exportModelLabel = new JLabel("Select Model");
    exportModelLabel.setBounds(10, 34, 151, 16);
    modelExportPanel.add(exportModelLabel);

    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setBounds(83, 32, 503, 212);
    modelExportPanel.add(scrollPane);

    final JList<String> exportModelList = new JList<String>();
    scrollPane.setViewportView(exportModelList);
    exportModelList.setEnabled(false);
    exportModelList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));

    // EXPORT TAB //

    final JButton exportDailyButton = new JButton("Daily Times");
    exportDailyButton.setEnabled(false);
    exportButtonsPanel.add(exportDailyButton);

    final JButton exportDurationButton = new JButton("Duration");
    exportDurationButton.setEnabled(false);
    exportButtonsPanel.add(exportDurationButton);

    final JButton exportStartButton = new JButton("Start Time");
    exportStartButton.setEnabled(false);
    exportButtonsPanel.add(exportStartButton);

    final JButton exportStartBinnedButton = new JButton("Start Time Binned");
    exportStartBinnedButton.setEnabled(false);
    exportButtonsPanel.add(exportStartBinnedButton);

    final JButton exportExpectedPowerButton = new JButton("Expected Power");
    exportExpectedPowerButton.setEnabled(false);
    exportButtonsPanel.add(exportExpectedPowerButton);

    JLabel usernameLabel = new JLabel("Username:");
    usernameLabel.setBounds(46, 27, 71, 16);
    connectionPanel.add(usernameLabel);

    final JTextField usernameTextField;
    usernameTextField = new JTextField();
    usernameTextField.setText("user");
    usernameTextField.setColumns(10);
    usernameTextField.setBounds(122, 21, 405, 28);
    connectionPanel.add(usernameTextField);

    final JButton exportButton = new JButton("Export Entity");
    exportButton.setEnabled(false);
    exportButton.setBounds(46, 178, 147, 28);
    connectionPanel.add(exportButton);

    final JButton exportAllBaseButton = new JButton("Export All Base");
    exportAllBaseButton.setEnabled(false);
    exportAllBaseButton.setBounds(203, 178, 177, 28);
    connectionPanel.add(exportAllBaseButton);

    final JButton exportAllResponseButton = new JButton("Export All Response");
    exportAllResponseButton.setEnabled(false);
    exportAllResponseButton.setBounds(390, 178, 181, 28);
    connectionPanel.add(exportAllResponseButton);

    JLabel passwordLabel = new JLabel("Password:");
    passwordLabel.setBounds(46, 62, 71, 16);
    connectionPanel.add(passwordLabel);

    JLabel UrlLabel = new JLabel("URL:");
    UrlLabel.setBounds(46, 105, 71, 16);
    connectionPanel.add(UrlLabel);

    final JTextField urlTextField;
    urlTextField = new JTextField();
    urlTextField.setText("https://160.40.50.233:8443/cassandra/api");
    urlTextField.setColumns(10);
    urlTextField.setBounds(122, 99, 405, 28);
    connectionPanel.add(urlTextField);

    final JButton connectButton = new JButton("Connect");
    connectButton.setEnabled(false);
    connectButton.setBounds(217, 138, 147, 28);
    connectionPanel.add(connectButton);

    final JPasswordField passwordField;
    passwordField = new JPasswordField();
    passwordField.setBounds(122, 60, 405, 28);
    connectionPanel.add(passwordField);

    final JTextField householdNameTextField;
    householdNameTextField = new JTextField();
    householdNameTextField.setEnabled(false);
    householdNameTextField.setBounds(166, 225, 405, 31);
    connectionPanel.add(householdNameTextField);
    householdNameTextField.setColumns(10);

    final JLabel householdNameLabel = new JLabel("Export Household Name:");
    householdNameLabel.setBounds(24, 233, 147, 14);
    connectionPanel.add(householdNameLabel);

    JButton btnOpenPlatform = new JButton("Open Platform");
    btnOpenPlatform.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            try {
                Desktop.getDesktop()
                        .browse(new URL("https://cassandra.iti.gr:8443/cassandra/app.html").toURI());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    btnOpenPlatform.setBounds(401, 138, 147, 28);
    connectionPanel.add(btnOpenPlatform);

    // //////////////////
    // ACTIONS ///////
    // /////////////////

    // IMPORT TAB //

    // DATA IMPORT ////

    dataBrowseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the browse button to
         * input the data file on the Data File panel of the Import Data tab.
         * 
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            // Opens the browse panel to find the data set file
            JFileChooser fc = new JFileChooser("./");

            // Adds a filter to the type of files acceptable for selection
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setFileFilter(new MyFilter2());

            int returnVal = fc.showOpenDialog(contentPane);

            // After choosing the file some of the options in the Data File panel
            // are unlocked
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();

                pathField.setText(file.getAbsolutePath());
                importDataButton.setEnabled(true);
                activePowerRadioButton.setEnabled(true);
                activeAndReactivePowerRadioButton.setEnabled(true);
                installationRadioButton.setEnabled(true);
                singleApplianceRadioButton.setEnabled(true);
            }

        }
    });

    consumptionBrowseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the browse button to
         * input the consumption model file on the Data File panel of the Import
         * Data tab.
         * 
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            // Opens the browse panel to find the consumption model file
            JFileChooser fc = new JFileChooser("./");

            // Adds a filter to the type of files acceptable for selection
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setFileFilter(new MyFilter());

            int returnVal = fc.showOpenDialog(contentPane);

            // After choosing the file some of the options in the Data File panel
            // are unlocked
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();

                consumptionPathField.setText(file.getAbsolutePath());
                createEventsButton.setEnabled(true);
            }

        }
    });

    resetButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the reset button
         * on the Data File panel of the Import Data tab. All the imported and
         * created entities are removed and the Training Module goes back to its
         * initial state.
         * 
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            // Cleaning the Import Data tab components
            pathField.setText("");
            consumptionPathField.setText("");
            importDataButton.setEnabled(false);
            disaggregateButton.setEnabled(false);
            createEventsButton.setEnabled(false);
            installation = new Installation();
            dataBrowseButton.setEnabled(true);
            consumptionBrowseButton.setEnabled(false);
            installationRadioButton.setEnabled(false);
            installationRadioButton.setSelected(true);
            singleApplianceRadioButton.setEnabled(false);
            activePowerRadioButton.setEnabled(false);
            activeAndReactivePowerRadioButton.setEnabled(false);
            activeAndReactivePowerRadioButton.setSelected(true);
            dataReviewPanel.removeAll();
            dataReviewPanel.updateUI();
            consumptionModelPanel.removeAll();
            consumptionModelPanel.updateUI();
            detectedApplianceList.setSelectedIndex(-1);
            detectedAppliances.clear();
            detectedApplianceList.setListData(new String[0]);
            detectedApplianceList.repaint();

            // Cleaning the Training Activity Models tab components
            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();
            expectedPowerPanel.removeAll();
            expectedPowerPanel.updateUI();
            selectedApplianceList.setSelectedIndex(-1);
            selectedAppliances.clear();
            selectedApplianceList.setListData(new String[0]);
            selectedApplianceList.repaint();
            timesHistogramRadioButton.setSelected(true);
            durationNormalRadioButton.setSelected(true);
            startGaussianRadioButton.setSelected(true);

            // Cleaning the Create Response Models tab components
            sensitivitySlider.setValue(50);
            awarenessSlider.setValue(50);
            normalCaseRadioButton.setSelected(true);
            previewResponseButton.setEnabled(false);
            createResponseButton.setEnabled(false);
            createResponseAllButton.setEnabled(false);
            pricingPreviewPanel.removeAll();
            pricingPreviewPanel.updateUI();
            responsePanel.removeAll();
            responsePanel.updateUI();
            activitySelectList.setSelectedIndex(-1);
            activityModels.clear();
            activitySelectList.setListData(new String[0]);
            activitySelectList.repaint();
            basicPricingSchemePane.setText("00:00-23:59-0.05");
            newPricingSchemePane.setText("");
            commitButton.setEnabled(false);
            dailyResponseButton.setEnabled(false);
            startResponseButton.setEnabled(false);

            // Cleaning the Export Models tab components
            exportModelList.setSelectedIndex(-1);
            exportModels.clear();
            exportModelList.setListData(new String[0]);
            exportModelList.repaint();
            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();
            exportDailyButton.setEnabled(false);
            exportDurationButton.setEnabled(false);
            exportStartButton.setEnabled(false);
            exportStartBinnedButton.setEnabled(false);
            exportExpectedPowerButton.setEnabled(false);
            exportButton.setEnabled(false);
            exportAllBaseButton.setEnabled(false);
            exportAllResponseButton.setEnabled(false);
            householdNameTextField.setEnabled(false);

            // Disabling the necessary tabs
            tabbedPane.setEnabledAt(1, false);
            tabbedPane.setEnabledAt(2, false);
            tabbedPane.setEnabledAt(3, false);

            // Clearing the arrayList in need
            tempAppliances.clear();
            tempActivities.clear();

            // Removing temporary files
            Utils.cleanFiles();
            trained = false;

        }
    });

    singleApplianceRadioButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Single Appliance
         * radio button on the Data File panel of the Import Data tab.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            consumptionPathField.setEnabled(false);
            consumptionBrowseButton.setEnabled(false);
            consumptionPathField.setText("");
        }
    });

    installationRadioButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Installation
         * radio button on the Data File panel of the Import Data tab.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            consumptionPathField.setEnabled(false);
            consumptionBrowseButton.setEnabled(false);
            consumptionPathField.setText("");
        }
    });

    importDataButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Import Data
         * button on the Data File panel of the Import Data tab.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Change the state of some components
                installationRadioButton.setEnabled(false);
                singleApplianceRadioButton.setEnabled(false);
                importDataButton.setEnabled(false);
                dataBrowseButton.setEnabled(false);
                activePowerRadioButton.setEnabled(false);
                activeAndReactivePowerRadioButton.setEnabled(false);

                // Check if both active and reactive activeOnly data set are available
                boolean power = activePowerRadioButton.isSelected();
                int parse = -1;

                // Parsing the measurements file
                try {
                    parse = Utils.parseMeasurementsFile(pathField.getText(), power);
                } catch (IOException e2) {
                    e2.printStackTrace();
                }

                // If everything is OK
                if (parse == -1) {
                    try {
                        // Creating new installation
                        installation = new Installation(pathField.getText(), power);
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }

                    // Show the measurements in the preview chart
                    ChartPanel chartPanel = null;
                    try {
                        chartPanel = installation.measurementsChart();
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                    dataReviewPanel.add(chartPanel, BorderLayout.CENTER);
                    dataReviewPanel.validate();

                    disaggregateButton.setEnabled(false);
                    createEventsButton.setEnabled(false);

                    // Enable the appropriate buttons given source of measurements
                    if (installationRadioButton.isSelected()) {
                        disaggregateButton.setEnabled(true);
                    } else if (singleApplianceRadioButton.isSelected()) {
                        consumptionPathField.setEnabled(true);
                        consumptionBrowseButton.setEnabled(true);

                    }

                    // Add installation to the export models list
                    exportModels.addElement(installation.toString());
                    exportModels.addElement(installation.getPerson().getName());
                    householdNameTextField.setText(installation.getName());

                    // Enable Export Models tab
                    exportModelList.setEnabled(true);
                    exportModelList.setModel(exportModels);
                    tabbedPane.setEnabledAt(3, true);

                }
                // In case of an error during the measurement parsing show the line of
                // error and reset settings.
                else {
                    JFrame error = new JFrame();

                    JOptionPane.showMessageDialog(error,
                            "Parsing measurements file failed. The problem seems to be in line " + parse
                                    + ".Check the selected buttons and the file provided and try again.",
                            "Inane error", JOptionPane.ERROR_MESSAGE);
                    resetButton.doClick();
                }
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    disaggregateButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Disaggregate
         * button on the Data File panel of the Import Data tab in order to
         * automatically analyse the data set and extract the appliances and
         * activities within.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Get auxiliary files containing appliances and activities which are
                // the output of the disaggregation process.
                String filename = pathField.getText();

                File file = new File(filename);

                String folder = file.getParent() + "/";

                String fileNameWithExtension = file.getName();

                String fileName = file.getName().substring(0, file.getName().length() - 4);

                filename = pathField.getText().substring(0, pathField.getText().length() - 4);
                File appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv");
                File activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv");

                if ((Constants.USE_FILES == false) || (!appliancesFile.exists() && !activitiesFile.exists())) {
                    try {
                        System.out.println("IN!!!");

                        Disaggregate dis = new Disaggregate(folder, fileNameWithExtension);

                        appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv");
                        activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv");
                    } catch (Exception e2) {
                        System.out.println("Missing File");
                        e2.printStackTrace();
                    }
                }

                // If these exist, disaggregation was successful and the procedure can
                // continue
                if (appliancesFile.exists() && activitiesFile.exists()) {

                    // Read appliance file and start appliance parsing
                    Scanner input = null;
                    try {
                        input = new Scanner(appliancesFile);
                    } catch (FileNotFoundException e1) {
                        e1.printStackTrace();
                    }
                    String nextLine;
                    String[] line;

                    while (input.hasNext()) {
                        nextLine = input.nextLine();
                        line = nextLine.split(",");

                        String name = line[1] + " " + line[0];
                        // String activity = line[1];
                        String activity = name;
                        String[] temp = line[0].split(" ");

                        String type = "";

                        if (temp.length == 1)
                            type = temp[0];
                        else {
                            for (int i = 0; i < temp.length - 1; i++)
                                type += temp[i] + " ";
                            type = type.trim();

                        }

                        boolean refFlag = activity.contains("Refrigeration");
                        boolean wmFlag = name.contains("Washing");

                        double p = 0, q = 0;
                        int distance = 0, duration = 0;

                        if (refFlag) {
                            p = Double.parseDouble(line[2]);
                            q = Double.parseDouble(line[3]);
                            duration = Integer.parseInt(line[4]);
                            distance = Integer.parseInt(line[5]);
                            // For each appliance found in the file, an temporary Appliance
                            // Entity is created.

                            tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity,
                                    p, q, duration, distance));
                        } else if (wmFlag) {
                            double[] pValues = new double[line.length / 2 - 1];
                            double[] qValues = new double[line.length / 2 - 1];
                            // For each appliance found in the file, an temporary Appliance
                            // Entity is created.

                            for (int i = 0; i < pValues.length; i++) {
                                pValues[i] = Double.parseDouble(line[2 + 2 * i]);
                                qValues[i] = Double.parseDouble(line[3 + 2 * i]);
                            }

                            tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity,
                                    pValues, qValues));
                        } else {
                            p = Double.parseDouble(line[2]);
                            q = Double.parseDouble(line[3]);
                            // For each appliance found in the file, an temporary Appliance
                            // Entity is created.

                            tempAppliances
                                    .add(new ApplianceTemp(name, installation.getName(), type, activity, p, q));
                        }
                    }

                    System.out.println("Appliances:" + tempAppliances.size());

                    input.close();

                    // Read activity file and start activity parsing

                    try {
                        input = new Scanner(activitiesFile);
                    } catch (FileNotFoundException e1) {
                        System.out.println("Problem with activity file.");
                        e1.printStackTrace();
                    }

                    while (input.hasNext()) {
                        nextLine = input.nextLine();
                        line = nextLine.split(",");

                        // System.out.println(Arrays.toString(line));
                        // String name = line[0];
                        // String activity = line[1];
                        String activity = line[1] + " " + line[0];
                        String type = line[1];
                        int start = Integer.parseInt(line[2]);
                        int end = Integer.parseInt(line[3]);

                        // Search for existing activity
                        int activityIndex = findActivity(activity);

                        // if not found, create a new one
                        if (activityIndex == -1) {
                            // System.out.println("In!");
                            ActivityTemp newActivity = new ActivityTemp(activity, type);
                            newActivity.addEvent(start, end);
                            tempActivities.add(newActivity);
                            // System.out.println(tempActivities.toString());

                        }
                        // else add data to the found activity
                        else
                            tempActivities.get(activityIndex).addEvent(start, end);
                    }

                    // This is hard copied for now
                    ArrayList<ActivityTemp> activities = findAllActivity("Refrigeration");
                    for (ActivityTemp activityTemp : activities) {
                        tempActivities.remove(activityTemp);
                        System.out.println("Refrigeration Removed");
                    }

                    int index = findActivity("Standby");
                    if (index != -1) {
                        tempActivities.remove(index);
                        System.out.println("Standby Consumption Removed");
                    }
                    // TODO Add these lines in case we want to remove activities with
                    // small sampling number

                    // System.out.println(tempActivities.size());
                    // for (int i = tempActivities.size() - 1; i >= 0; i--)
                    // if (tempActivities.get(i).getEvents().size() < threshold)
                    // tempActivities.remove(i);

                    // Create an event file for each activity, in order to be able to
                    // use
                    // it for training the behaviour models if asked from the user
                    for (int i = 0; i < tempActivities.size(); i++) {
                        // tempActivities.get(i).status();
                        try {
                            tempActivities.get(i).createEventFile();
                        } catch (IOException e1) {
                            System.out.println("Problem with creating events file.");
                            e1.printStackTrace();
                        }
                    }

                    input.close();

                    // Add each found appliance (after converting temporary appliance to
                    // normal appliance) in the installation Entity, to the detected
                    // appliance and export models list
                    for (ApplianceTemp temp : tempAppliances) {

                        Appliance tempAppliance = temp.toAppliance();

                        installation.addAppliance(tempAppliance);
                        detectedAppliances.addElement(tempAppliance.toString());
                        exportModels.addElement(tempAppliance.toString());

                    }

                    // Add appliances corresponding to each activity, remove activities
                    // without appliances and add activities to the selected activities
                    // list.
                    for (int i = tempActivities.size() - 1; i >= 0; i--) {

                        tempActivities.get(i).setAppliances(findAppliances(tempActivities.get(i)));
                        if (tempActivities.get(i).getAppliances().size() == 0) {
                            tempActivities.remove(i);
                        } else
                            selectedAppliances.addElement(tempActivities.get(i).toString());

                    }

                }
                // In case of an error.
                else {

                    int temp = 8 + ((int) (Math.random() * 2));

                    for (int i = 0; i < temp; i++) {

                        String name = "Appliance " + i;
                        String powerModel = "";
                        String reactiveModel = "";
                        int tempIndex = i % 5;
                        switch (tempIndex) {
                        case 0:
                            powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":1900,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"p\":300,\"d\":1,\"s\":0}]}]}";
                            reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":-40,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"q\":-10,\"d\":1,\"s\":0}]}]}";
                            break;
                        case 1:
                            powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 140.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 120.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            break;
                        case 2:
                            powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 95.0, \"d\" : 20, \"s\": 0.0}, {\"p\" :80.0, \"d\" : 18, \"s\": 0.0}, {\"p\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}";
                            reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 0.0, \"d\" : 20, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 18, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}";
                            break;
                        case 3:
                            powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 30.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : -5.0, \"d\" : 20, \"s\": 0.0}]}]}";
                            break;
                        case 4:
                            powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":150,\"d\":25,\"s\":0},{\"p\":2000,\"d\":13,\"s\":0},{\"p\":100,\"d\":62,\"s\":0}]}]}";
                            reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":400,\"d\":25,\"s\":0},{\"q\":200,\"d\":13,\"s\":0},{\"q\":300,\"d\":62,\"s\":0}]}]}";
                            break;
                        }

                        Appliance tempAppliance = new Appliance(name, installation.getName(), powerModel,
                                reactiveModel, "Demo/eventsAll" + tempIndex + ".csv");

                        installation.addAppliance(tempAppliance);
                        detectedAppliances.addElement(tempAppliance.toString());
                        selectedAppliances.addElement(tempAppliance.toString());
                        exportModels.addElement(tempAppliance.toString());
                    }
                }

                // Enable all appliance/activity lists
                detectedApplianceList.setEnabled(true);
                detectedApplianceList.setModel(detectedAppliances);
                detectedApplianceList.setSelectedIndex(0);

                tabbedPane.setEnabledAt(1, true);
                selectedApplianceList.setEnabled(true);
                selectedApplianceList.setModel(selectedAppliances);

                // exportModelList.setEnabled(true);
                // exportModelList.setModel(exportModels);
                // tabbedPane.setEnabledAt(3, true);

                // Disable unnecessary buttons.
                disaggregateButton.setEnabled(false);
                createEventsButton.setEnabled(false);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    createEventsButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Create Events
         * button on the Data File panel of the Import Data tab. This button is
         * used when there is a single appliance with an known consumption model
         * so that the events can be extracted automatically from the data set.
         * Used for presentation purposes only since is depricated by the
         * disaggregation function.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Parse the consumption model file
                File file = new File(consumptionPathField.getText());
                String temp = file.getName();
                temp = temp.replace(".", " ");
                String name = temp.split(" ")[0];

                Appliance appliance = null;
                try {

                    int rand = (int) (Math.random() * 5);

                    appliance = new Appliance(name, consumptionPathField.getText(),
                            consumptionPathField.getText(), "Demo/eventsAll" + rand + ".csv", installation,
                            activePowerRadioButton.isSelected());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                // Add appliance to the installation entity
                installation.addAppliance(appliance);

                // Enable all appliance/activity lists
                detectedAppliances.addElement(appliance.toString());
                selectedAppliances.addElement(appliance.toString());
                exportModels.addElement(appliance.toString());

                detectedApplianceList.setEnabled(true);
                detectedApplianceList.setModel(detectedAppliances);
                detectedApplianceList.setSelectedIndex(0);

                tabbedPane.setEnabledAt(1, true);
                selectedApplianceList.setEnabled(true);
                selectedApplianceList.setModel(selectedAppliances);

                // exportModelList.setEnabled(true);
                // exportModelList.setModel(exportModels);
                // tabbedPane.setEnabledAt(3, true);

                // Disable unnecessary buttons.
                disaggregateButton.setEnabled(false);
                createEventsButton.setEnabled(false);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    // APPLIANCE DETECTION //
    detectedApplianceList.addListSelectionListener(new ListSelectionListener() {
        /**
         * This function is called when the user selects an appliance from the
         * list of Detected Appliances on the Disaggregation panel of the Import
         * Data tab. Then the corresponding consumption model is presented in the
         * Consumption Model Preview panel.
         */
        @Override
        public void valueChanged(ListSelectionEvent e) {

            consumptionModelPanel.removeAll();
            consumptionModelPanel.updateUI();

            if (detectedAppliances.size() >= 1) {

                String selection = detectedApplianceList.getSelectedValue();

                Appliance current = installation.findAppliance(selection);

                ChartPanel chartPanel = current.consumptionGraph();

                consumptionModelPanel.add(chartPanel, BorderLayout.CENTER);
                consumptionModelPanel.validate();

            }
        }
    });

    // // TRAINING TAB //
    trainingTab.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent arg0) {
            selectedApplianceList.setSelectedIndex(0);
        }
    });

    trainingButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Train button on
         * the Training Parameters panel of the Train Activity Models tab. It
         * contains the procedure needed to create an activity model based on the
         * event set of the appliance or activity.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            responsePanel.removeAll();
            responsePanel.validate();
            pricingPreviewPanel.removeAll();
            pricingPreviewPanel.validate();
            previewResponseButton.setEnabled(false);
            createResponseButton.setEnabled(false);
            createResponseAllButton.setEnabled(false);
            dailyResponseButton.setEnabled(false);
            startResponseButton.setEnabled(false);

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Searching for existing activity or appliance.
                String selection = selectedApplianceList.getSelectedValue();
                ActivityTemp activity = null;

                if (tempActivities.size() > 0)
                    activity = tempActivities.get(findActivity(selection));

                Appliance current = installation.findAppliance(selection);

                String startTime, duration, dailyTimes;

                // Check for the selected distribution methods for training.
                if (timesHistogramRadioButton.isSelected())
                    dailyTimes = "Histogram";
                else if (timesNormalRadioButton.isSelected())
                    dailyTimes = "Normal";
                else
                    dailyTimes = "GMM";

                if (durationHistogramRadioButton.isSelected())
                    duration = "Histogram";
                else if (durationNormalRadioButton.isSelected())
                    duration = "Normal";
                else
                    duration = "GMM";

                if (startHistogramRadioButton.isSelected())
                    startTime = "Histogram";
                else if (startNormalRadioButton.isSelected())
                    startTime = "Normal";
                else
                    startTime = "GMM";

                String[] distributions = { dailyTimes, duration, startTime, "Histogram" };

                // If the selected object from the list is an appliance the training
                // procedure for the appliance begins.
                if (activity == null) {

                    try {
                        installation.getPerson().train(current, distributions);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                // If the selected object from the list is an activity the training
                // procedure for the activity begins.
                else {

                    try {
                        installation.getPerson().train(activity, distributions);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

                }

                // System.out.println("Training OK!");

                distributionPreviewPanel.removeAll();
                distributionPreviewPanel.updateUI();

                expectedPowerPanel.removeAll();
                expectedPowerPanel.updateUI();

                // Show the distribution created on the Distribution Preview Panel
                ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

                if (activityModel == null)
                    activityModel = installation.getPerson().findActivity(current);

                ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart();
                distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
                distributionPreviewPanel.validate();

                chartPanel = activityModel.createExpectedPowerChart();
                expectedPowerPanel.add(chartPanel, BorderLayout.CENTER);
                expectedPowerPanel.validate();

                // Add the Activity model to the list of trained Activity models of
                // the Create Response Models tab
                int size = activitySelectList.getModel().getSize();

                if (size > 0) {
                    activityModels = (DefaultListModel<String>) activitySelectList.getModel();
                    if (activityModels.contains(activityModel.getName()) == false)
                        activityModels.addElement(activityModel.getName());
                } else {
                    activityModels = new DefaultListModel<String>();
                    activityModels.addElement(activityModel.getName());
                    activitySelectList.setEnabled(true);
                }

                activitySelectList.setModel(activityModels);

                // Add the trained model to the export list also.
                size = exportModelList.getModel().getSize();
                if (size > 0) {
                    exportModels = (DefaultListModel<String>) exportModelList.getModel();
                    if (exportModels.contains(activityModel.getName()) == false)
                        exportModels.addElement(activityModel.getName());
                } else {
                    exportModels = new DefaultListModel<String>();
                    exportModels.addElement(activityModel.getName());
                    exportModelList.setEnabled(true);
                }

                // Enable some buttons necessary to show the results.
                dailyTimesButton.setEnabled(true);
                durationButton.setEnabled(true);
                startTimeButton.setEnabled(true);
                startTimeBinnedButton.setEnabled(true);

                exportModelList.setModel(exportModels);

                exportDailyButton.setEnabled(true);
                exportDurationButton.setEnabled(true);
                exportStartButton.setEnabled(true);
                exportStartBinnedButton.setEnabled(true);

                tabbedPane.setEnabledAt(2, true);
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
                trained = true;
            }
        }
    });

    trainAllButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Train All button on
         * the Training Parameters panel of the Train Activity Models tab. It
         * is iterating the aforementioned training procedure to each of the
         * objects on the list.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            responsePanel.removeAll();
            responsePanel.validate();
            pricingPreviewPanel.removeAll();
            pricingPreviewPanel.validate();
            previewResponseButton.setEnabled(false);
            createResponseButton.setEnabled(false);
            createResponseAllButton.setEnabled(false);
            dailyResponseButton.setEnabled(false);
            startResponseButton.setEnabled(false);

            for (int i = 0; i < selectedApplianceList.getModel().getSize(); i++) {
                selectedApplianceList.setSelectedIndex(i);
                trainingButton.doClick();
            }
        }
    });

    dailyTimesButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Daily Times button on
         * the Distribution Preview panel of the Train Activity Models tab. It
         * shows the Daily Times Distribution for the selected object from the
         * list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    startTimeBinnedButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time Binned
         * button on the Distribution Preview panel of the Train Activity
         * Models tab. It shows the Start Time Binned Distribution for the
         * selected object from the list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createStartTimeBinnedDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    startTimeButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time
         * button on the Distribution Preview panel of the Train Activity
         * Models tab. It shows the Start Time Distribution for the selected
         * object from the list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createStartTimeDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    durationButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Duration
         * button on the Distribution Preview panel of the Train Activity
         * Models tab. It shows the Duration Distribution for the selected
         * object from the list if available.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

            ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

            if (activityModel == null)
                activityModel = installation.getPerson().findActivity(current);

            ChartPanel chartPanel = activityModel.createDurationDistributionChart();
            distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            distributionPreviewPanel.validate();

        }
    });

    selectedApplianceList.addListSelectionListener(new ListSelectionListener() {
        /**
         * This function is called when the user selects an appliance or activity
         * from the list of Selected Appliances on the Appliance / Activity
         * Selection panel of the Train Activity Models tab. Then an example
         * corresponding consumption model is presented in the Consumption Model
         * Preview panel.
         */
        @Override
        public void valueChanged(ListSelectionEvent arg0) {

            ChartPanel chartPanel = null, chartPanel2 = null, chartPanel3 = null;
            expectedPowerPanel.removeAll();
            expectedPowerPanel.updateUI();
            distributionPreviewPanel.removeAll();
            distributionPreviewPanel.updateUI();

            // If there are any appliances / activities on the list
            if (selectedAppliances.size() >= 1) {

                // Find the corresponding appliance / activity and show its
                // consumption model
                String selection = selectedApplianceList.getSelectedValue();

                Appliance currentAppliance = installation.findAppliance(selection);

                ActivityModel activityModel = installation.getPerson().findActivity(selection, true);

                // If there is also an Activity model trained, show the corresponding
                // distribution charts on the Distribution Preview panel

                if (currentAppliance != null)
                    activityModel = installation.getPerson().findActivity(currentAppliance);

                if (activityModel == null)
                    activityModel = installation.getPerson().findActivity(selection, true);

                if (activityModel != null) {

                    dailyTimesButton.setEnabled(true);
                    durationButton.setEnabled(true);
                    startTimeButton.setEnabled(true);
                    startTimeBinnedButton.setEnabled(true);

                    chartPanel2 = activityModel.createDailyTimesDistributionChart();
                    distributionPreviewPanel.add(chartPanel2, BorderLayout.CENTER);
                    distributionPreviewPanel.validate();
                    distributionPreviewPanel.updateUI();

                    chartPanel3 = activityModel.createExpectedPowerChart();
                    expectedPowerPanel.add(chartPanel3, BorderLayout.CENTER);
                    expectedPowerPanel.validate();
                    expectedPowerPanel.updateUI();

                } else {
                    dailyTimesButton.setEnabled(false);
                    durationButton.setEnabled(false);
                    startTimeButton.setEnabled(false);
                    startTimeBinnedButton.setEnabled(false);
                }
            }

        }
    });

    // RESPONSE TAB //

    createResponseTab.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentHidden(ComponentEvent arg0) {
            activitySelectList.setSelectedIndex(0);

        }

        @Override
        public void componentShown(ComponentEvent arg0) {
            activitySelectList.setSelectedIndex(0);
        }
    });

    previewResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Preview Response
         * button on the Response Parameters panel of the Create Response Models
         * tab. This button is enabled after selecting activity model, response
         * type and pricing for testing and presents a preview of the response
         * model that may be extracted.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                responsePanel.removeAll();

                // Find the selected activity
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                int response = -1;

                // Check for the selected response type
                if (optimalCaseRadioButton.isSelected())
                    response = 0;
                else if (normalCaseRadioButton.isSelected())
                    response = 1;
                else
                    response = 2;

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                // Create a preview chart of the response model
                ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response,
                        basicScheme, newScheme, awareness, sensitivity);

                responsePanel.add(chartPanel, BorderLayout.CENTER);
                responsePanel.validate();

                createResponseButton.setEnabled(true);
                createResponseAllButton.setEnabled(true);
                dailyResponseButton.setEnabled(true);
                startResponseButton.setEnabled(true);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    createResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Create Response Model
         * button on the Response Parameters panel of the Create Response Models
         * tab. This button is enabled after preview results of the selected
         * activity model, response type and pricing for testing and creates the
         * response model for the user.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                exportPreviewPanel.removeAll();
                exportPreviewPanel.updateUI();

                int responseType = -1;
                String responseString = "";
                // Check for the selected response type
                if (optimalCaseRadioButton.isSelected()) {
                    responseType = 0;
                    responseString = "Optimal";
                } else if (normalCaseRadioButton.isSelected()) {
                    responseType = 1;
                    responseString = "Normal";
                } else if (discreteCaseRadioButton.isSelected()) {
                    responseType = 2;
                    responseString = "Discrete";
                }

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                // Create the response model
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                String response = "";

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                try {
                    response = installation.getPerson().createResponse(activity, responseType, basicScheme,
                            newScheme, awareness, sensitivity);
                } catch (IOException exc) {

                    exc.printStackTrace();
                }

                // Add the response model extracted to the export model list.
                int size = exportModelList.getModel().getSize();
                // System.out.println(size);

                if (size > 0) {
                    exportModels = (DefaultListModel<String>) exportModelList.getModel();

                    String response2 = "", response3 = "";
                    if (responseString.equalsIgnoreCase("Optimal")) {
                        response2 = response.replace(responseString, "Normal");
                        response3 = response.replace(responseString, "Discrete");
                    } else if (responseString.equalsIgnoreCase("Normal")) {
                        response2 = response.replace(responseString, "Optimal");
                        response3 = response.replace(responseString, "Discrete");
                    } else {
                        response2 = response.replace(responseString, "Optimal");
                        response3 = response.replace(responseString, "Normal");
                    }

                    if (exportModels.contains(response2))
                        exportModels.removeElement(response2);
                    if (exportModels.contains(response3))
                        exportModels.removeElement(response3);

                    if (exportModels.contains(response) == false)
                        exportModels.addElement(response);
                } else {
                    exportModels = new DefaultListModel<String>();
                    exportModels.addElement(response);
                    exportModelList.setEnabled(true);
                }
                exportModelList.setModel(exportModels);

                if (manyFlag == false) {

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The response model " + response + " was created successfully",
                            "Response Model Created", JOptionPane.INFORMATION_MESSAGE);
                }
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    createResponseAllButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Create Response All
         * button on the Response Parameters panel of the Create Response Models
         * tab. This is achieved by iterating the procedure above for all the
         * available activity models in the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {
            manyFlag = true;

            for (int i = 0; i < activitySelectList.getModel().getSize(); i++) {
                activitySelectList.setSelectedIndex(i);
                createResponseButton.doClick();
            }

            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success, "The response models were created successfully",
                    "Response Models Created", JOptionPane.INFORMATION_MESSAGE);

            manyFlag = false;
        }
    });

    newPricingSchemePane.addKeyListener(new KeyAdapter() {
        @Override
        public void keyTyped(KeyEvent arg0) {
            commitButton.setEnabled(true);
        }
    });

    basicPricingSchemePane.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent arg0) {
            commitButton.setEnabled(true);
        }
    });

    commitButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Commit button on the
         * Pricing Scheme panel of the Create Response Models tab. This button is
         * enabled after adding the two pricing schemes that are prerequisites for
         * the creation of a response model.
         */
        @Override
        public void actionPerformed(ActionEvent e) {

            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                boolean basicScheme = false;
                boolean newScheme = false;
                int parseBasic = 0;
                int parseNew = 0;

                pricingPreviewPanel.removeAll();

                // Check if both pricing schemes are entered
                if (basicPricingSchemePane.getText().equalsIgnoreCase("") == false)
                    basicScheme = true;

                if (newPricingSchemePane.getText().equalsIgnoreCase("") == false)
                    newScheme = true;

                // Parse the pricing schemes for errors
                if (basicScheme)
                    parseBasic = Utils.parsePricingScheme(basicPricingSchemePane.getText());

                if (newScheme)
                    parseNew = Utils.parsePricingScheme(newPricingSchemePane.getText());

                // If errors are found then present the line the error may be at
                if (parseBasic != -1) {
                    JFrame error = new JFrame();

                    JOptionPane.showMessageDialog(error,
                            "Basic Pricing Scheme is not defined correctly. Please check your input in line "
                                    + parseBasic + " and try again.",
                            "Inane error", JOptionPane.ERROR_MESSAGE);
                } else if (parseNew != -1) {
                    JFrame error = new JFrame();

                    JOptionPane.showMessageDialog(error,
                            "New Pricing Scheme is not defined correctly. Please check your input in line "
                                    + parseNew + " and try again.",
                            "Inane error", JOptionPane.ERROR_MESSAGE);
                }
                // If no errors are found make a preview chart of the two pricing
                // schemes
                else {
                    if (basicScheme && newScheme) {
                        ChartPanel chartPanel = ChartUtils.parsePricingScheme(basicPricingSchemePane.getText(),
                                newPricingSchemePane.getText());

                        pricingPreviewPanel.add(chartPanel, BorderLayout.CENTER);
                        pricingPreviewPanel.validate();

                        previewResponseButton.setEnabled(true);

                    } else {
                        JFrame error = new JFrame();

                        JOptionPane.showMessageDialog(error,
                                "You have not defined both pricing schemes.Please check your input and try again.",
                                "Inane error", JOptionPane.ERROR_MESSAGE);
                        previewResponseButton.setEnabled(false);
                    }
                }

                responsePanel.removeAll();
                responsePanel.validate();
                createResponseButton.setEnabled(false);
                createResponseAllButton.setEnabled(false);
                dailyResponseButton.setEnabled(false);
                startResponseButton.setEnabled(false);

            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    startResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the start time button on
         * the Preview Response panel of the Create Response Models tab. This
         * button is enabled after the user has pressed the Response Preview
         * button in order to see the results of his pricing scheme on a activity
         * model. It shows the changes in the start time distribution.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                responsePanel.removeAll();

                // Find the selected activity
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                int response = -1;

                // Check for the selected response type
                if (optimalCaseRadioButton.isSelected())
                    response = 0;
                else if (normalCaseRadioButton.isSelected())
                    response = 1;
                else
                    response = 2;

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                // Create a preview chart of the response model
                ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response,
                        basicScheme, newScheme, awareness, sensitivity);

                responsePanel.add(chartPanel, BorderLayout.CENTER);
                responsePanel.validate();

                createResponseButton.setEnabled(true);
                createResponseAllButton.setEnabled(true);
                dailyResponseButton.setEnabled(true);
                startResponseButton.setEnabled(true);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

        }
    });

    dailyResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the start time button on
         * the Preview Response panel of the Create Response Models tab. This
         * button is enabled after the user has pressed the Response Preview
         * button in order to see the results of his pricing scheme on a activity
         * model. It shows the changes in the daily times distribution.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                responsePanel.removeAll();

                // Find the selected activity
                ActivityModel activity = installation.getPerson()
                        .findActivity(activitySelectList.getSelectedValue(), false);

                // Parse the pricing schemes
                double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText());
                double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText());

                float awareness = (float) (awarenessSlider.getValue()) / 100;
                float sensitivity = (float) (sensitivitySlider.getValue()) / 100;

                System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity);

                // Create a preview chart of the response model
                ChartPanel chartPanel = installation.getPerson().previewDailyResponse(activity, basicScheme,
                        newScheme, awareness, sensitivity);

                responsePanel.add(chartPanel, BorderLayout.CENTER);
                responsePanel.validate();

                createResponseButton.setEnabled(true);
                createResponseAllButton.setEnabled(true);
                dailyResponseButton.setEnabled(true);
                startResponseButton.setEnabled(true);
            } finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

        }
    });

    // EXPORT TAB //

    exportTab.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentShown(ComponentEvent arg0) {
            exportModelList.setSelectedIndex(0);
        }
    });

    exportModelList.addListSelectionListener(new ListSelectionListener() {
        /**
         * This function is called when the user selects an entity from the
         * list of models on the Model Export Selection panel of the Export Models
         * tab. Then the corresponding preview of the entity model is presented in
         * the
         * Export Model Preview panel.
         */
        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            if (tabbedPane.getSelectedIndex() == 3) {
                exportPreviewPanel.removeAll();
                exportPreviewPanel.updateUI();

                // Checking if the list has any object
                if (exportModels.size() > 1) {
                    String selection = exportModelList.getSelectedValue();

                    // Check to see what type of entity is selected (Installation,
                    // Person, Appliance, Activity, Response)
                    Appliance appliance = installation.findAppliance(selection);

                    ActivityModel activity = installation.getPerson().findActivity(selection, false);

                    ResponseModel response = installation.getPerson().findResponse(selection);

                    // Create the appropriate chart for the selected entity and show it.
                    ChartPanel chartPanel = null;

                    if (selection.equalsIgnoreCase(installation.getName())) {

                        try {
                            chartPanel = installation.measurementsChart();

                            exportDailyButton.setEnabled(false);
                            exportDurationButton.setEnabled(false);
                            exportStartButton.setEnabled(false);
                            exportStartBinnedButton.setEnabled(false);
                            if (trained)
                                exportExpectedPowerButton.setEnabled(true);
                            else
                                exportExpectedPowerButton.setEnabled(false);
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }

                    } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                        chartPanel = installation.getPerson().statisticGraphs();

                        exportDailyButton.setEnabled(false);
                        exportDurationButton.setEnabled(false);
                        exportStartButton.setEnabled(false);
                        exportStartBinnedButton.setEnabled(false);
                        exportExpectedPowerButton.setEnabled(false);

                    } else if (appliance != null) {

                        chartPanel = appliance.consumptionGraph();

                        exportDailyButton.setEnabled(false);
                        exportDurationButton.setEnabled(false);
                        exportStartButton.setEnabled(false);
                        exportStartBinnedButton.setEnabled(false);
                        exportExpectedPowerButton.setEnabled(false);

                    } else if (activity != null) {

                        chartPanel = activity.createDailyTimesDistributionChart();
                        activity.status();
                        exportDailyButton.setEnabled(true);
                        exportDurationButton.setEnabled(true);
                        exportStartButton.setEnabled(true);
                        exportStartBinnedButton.setEnabled(true);
                        exportExpectedPowerButton.setEnabled(true);
                    } else if (response != null) {

                        chartPanel = response.createDailyTimesDistributionChart();

                        exportDailyButton.setEnabled(true);
                        exportDurationButton.setEnabled(true);
                        exportStartButton.setEnabled(true);
                        exportStartBinnedButton.setEnabled(true);
                        exportExpectedPowerButton.setEnabled(true);
                    }

                    exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
                    exportPreviewPanel.validate();
                }
            }
        }
    });

    exportDailyButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Daily Times
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Daily Times Distribution for the selected object from the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createDailyTimesDistributionChart();

            else
                chartPanel = response.createDailyTimesDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();
        }
    });

    exportStartBinnedButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time Binned
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Start Time Binned Distribution for the selected object from the
         * list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createStartTimeBinnedDistributionChart();

            else
                chartPanel = response.createStartTimeBinnedDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    exportStartButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Start Time
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Start Time Distribution for the selected object from the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createStartTimeDistributionChart();
            else
                chartPanel = response.createStartTimeDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    exportDurationButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Duration
         * button on the Entity Preview panel of the Export Models tab. It shows
         * the Duration Distribution for the selected object from the list.
         */
        @Override
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (activity != null)
                chartPanel = activity.createDurationDistributionChart();
            else
                chartPanel = response.createDurationDistributionChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    exportExpectedPowerButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            exportPreviewPanel.removeAll();
            exportPreviewPanel.updateUI();

            String selection = exportModelList.getSelectedValue();

            ActivityModel activity = installation.getPerson().findActivity(selection, false);

            ResponseModel response = installation.getPerson().findResponse(selection);

            ChartPanel chartPanel = null;

            if (selection.equalsIgnoreCase(installation.getName()))
                chartPanel = installation.createExpectedPowerChart();
            else if (activity != null)
                chartPanel = activity.createExpectedPowerChart();
            else
                chartPanel = response.createExpectedPowerChart();

            exportPreviewPanel.add(chartPanel, BorderLayout.CENTER);
            exportPreviewPanel.validate();

        }
    });

    connectButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Connect button on the
         * Connection Properties panel of the Export Models tab. It helps the user
         * to connect to his Cassandra Library and export the models he created
         * there.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean result = false;

            // Reads the user credentials and the server to connect to.
            try {
                APIUtilities.setUrl(urlTextField.getText());

                result = APIUtilities.sendUserCredentials(usernameTextField.getText(),
                        passwordField.getPassword());
            } catch (Exception e1) {
                e1.printStackTrace();
            }

            // If the use credentials are correct
            if (result) {
                exportButton.setEnabled(true);
                exportAllBaseButton.setEnabled(true);
                exportAllResponseButton.setEnabled(true);
                householdNameTextField.setEnabled(true);
            }
            // Else a error message appears.
            else {
                JFrame error = new JFrame();

                JOptionPane.showMessageDialog(error, "User Credentials are not correct! Please try again.",
                        "Inane error", JOptionPane.ERROR_MESSAGE);
                passwordField.setText("");
            }

        }
    });

    passwordField.addCaretListener(new CaretListener() {
        @Override
        public void caretUpdate(CaretEvent e) {
            String pass = String.valueOf(passwordField.getPassword());

            if (pass.equals("")) {
                connectButton.setEnabled(false);
            } else
                connectButton.setEnabled(true);
        }
    });

    exportButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Export button on the
         * Connection Properties panel of the Export Models tab. The entity model
         * selected from the list is then exported to the User Library in
         * Cassandra Platform.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                // Parsing the selected entity and find out what type of entity it is.
                String selection = exportModelList.getSelectedValue();

                Appliance appliance = installation.findAppliance(selection);

                ActivityModel activity = installation.getPerson().findActivity(selection, false);

                ResponseModel response = installation.getPerson().findResponse(selection);

                // If it is installation
                if (selection.equalsIgnoreCase(installation.getName())) {
                    String oldName = installation.getName();
                    installation.setName(householdNameTextField.getText());

                    try {
                        installation.setInstallationID(APIUtilities
                                .sendEntity(installation.toJSON(APIUtilities.getUserID()).toString(), "/inst"));

                    } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                        e1.printStackTrace();
                    }

                    installation.setName(oldName);

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The installation model " + installation.getName() + " was exported successfully",
                            "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is person
                else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                    try {
                        installation.getPerson().setPersonID(APIUtilities.sendEntity(
                                installation.getPerson().toJSON(APIUtilities.getUserID()).toString(), "/pers"));
                    } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The person model " + installation.getPerson().getName()
                                    + " was exported successfully",
                            "Person Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is appliance
                else if (appliance != null) {

                    try {
                        appliance.setApplianceID(APIUtilities
                                .sendEntity(appliance.toJSON(APIUtilities.getUserID()).toString(), "/app"));

                        APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod");

                    } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The appliance model " + appliance.getName() + " was exported successfully",
                            "Appliance Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is activity
                else if (activity != null) {

                    String[] applianceTemp = new String[activity.getAppliancesOf().length];
                    String activityTemp = "";
                    String durationTemp = "";
                    String dailyTemp = "";
                    String startTemp = "";

                    // For each appliance that participates in the activity
                    for (int i = 0; i < activity.getAppliancesOf().length; i++) {

                        Appliance activityAppliance = activity.getAppliancesOf()[i];

                        try {
                            // In case the appliances contained in the Activity model are
                            // not
                            // in the database, we create the object there before sending
                            // the
                            // activity model
                            if (activityAppliance.getApplianceID().equalsIgnoreCase("")) {

                                activityAppliance.setApplianceID(APIUtilities.sendEntity(
                                        activityAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app"));

                                APIUtilities.sendEntity(
                                        activityAppliance.powerConsumptionModelToJSON().toString(), "/consmod");
                            }
                            applianceTemp[i] = activityAppliance.getApplianceID();
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    }

                    try {

                        String[] appliancesID = applianceTemp;

                        // Creating the JSON of the activity model
                        activity.setActivityModelID(APIUtilities.sendEntity(
                                activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod"));

                        activityTemp = activity.getActivityModelID();

                        // Creating the JSON of the distributions
                        activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr"));

                        activity.setDailyID(activity.getDailyTimes().getDistributionID());
                        dailyTemp = activity.getDailyID();

                        activity.getDuration().setDistributionID(APIUtilities
                                .sendEntity(activity.getDuration().toJSON(activityTemp).toString(), "/distr"));

                        activity.setDurationID(activity.getDuration().getDistributionID());
                        durationTemp = activity.getDurationID();

                        activity.getStartTime().setDistributionID(APIUtilities
                                .sendEntity(activity.getStartTime().toJSON(activityTemp).toString(), "/distr"));

                        activity.setStartID(activity.getStartTime().getDistributionID());
                        startTemp = activity.getStartID();

                        // Adding the JSON of the distributions to the activity model
                        APIUtilities.updateEntity(
                                activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod",
                                activityTemp);

                    } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) {

                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The activity model " + activity.getName() + " was exported successfully",
                            "Activity Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
                // If it is response
                else if (response != null) {
                    String[] applianceTemp = new String[response.getAppliancesOf().length];

                    String responseTemp = "";
                    String durationTemp = "";
                    String dailyTemp = "";
                    String startTemp = "";

                    // For each appliance that participates in the activity
                    for (int i = 0; i < response.getAppliancesOf().length; i++) {

                        Appliance responseAppliance = response.getAppliancesOf()[i];

                        try {
                            // In case the appliances contained in the Activity model are
                            // not
                            // in the database, we create the object there before sending
                            // the
                            // activity model
                            if (responseAppliance.getApplianceID().equalsIgnoreCase("")) {

                                responseAppliance.setApplianceID(APIUtilities.sendEntity(
                                        responseAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app"));

                                APIUtilities.sendEntity(
                                        responseAppliance.powerConsumptionModelToJSON().toString(), "/consmod");
                            }
                            applianceTemp[i] = responseAppliance.getApplianceID();
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }
                    }

                    try {

                        String[] appliancesID = applianceTemp;

                        // Creating the JSON of the response
                        response.setActivityModelID(APIUtilities.sendEntity(
                                response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod"));

                        responseTemp = response.getActivityModelID();

                        // Creating the JSON of the distributions
                        response.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                response.getDailyTimes().toJSON(responseTemp).toString(), "/distr"));

                        response.setDailyID(response.getDailyTimes().getDistributionID());
                        dailyTemp = response.getDailyID();

                        response.getDuration().setDistributionID(APIUtilities
                                .sendEntity(response.getDuration().toJSON(responseTemp).toString(), "/distr"));

                        response.setDurationID(response.getDuration().getDistributionID());
                        durationTemp = response.getDurationID();

                        response.getStartTime().setDistributionID(APIUtilities
                                .sendEntity(response.getStartTime().toJSON(responseTemp).toString(), "/distr"));

                        response.setStartID(response.getStartTime().getDistributionID());
                        startTemp = response.getStartID();

                        // Adding the JSON of the distributions to the activity model
                        APIUtilities.updateEntity(
                                response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod",
                                responseTemp);

                    } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) {

                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

                    JOptionPane.showMessageDialog(success,
                            "The response model " + response.getName() + " was exported successfully",
                            "Response Model Exported", JOptionPane.INFORMATION_MESSAGE);

                }
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }
        }
    });

    exportAllBaseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Export All Base
         * button on the Connection Properties panel of the Export Models tab. The
         * export procedure above is iterated through all the entities available
         * on the list except for the response models.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                for (int i = 0; i < exportModelList.getModel().getSize(); i++) {
                    exportModelList.setSelectedIndex(i);

                    String selection = exportModelList.getSelectedValue();

                    Appliance appliance = installation.findAppliance(selection);

                    ActivityModel activity = installation.getPerson().findActivity(selection, false);

                    ResponseModel response = installation.getPerson().findResponse(selection);

                    if (selection.equalsIgnoreCase(installation.getName())) {

                        String oldName = installation.getName();

                        try {

                            installation.setName(householdNameTextField.getText() + " Base");

                            installation.setInstallationID(APIUtilities.sendEntity(
                                    installation.toJSON(APIUtilities.getUserID()).toString(), "/inst"));

                            installation.setName(oldName);
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                        try {
                            installation.getPerson().setPersonID(APIUtilities.sendEntity(installation
                                    .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers"));
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (appliance != null) {

                        try {
                            appliance.setApplianceID(APIUtilities.sendEntity(
                                    appliance.toJSON(installation.getInstallationID().toString()).toString(),
                                    "/app"));

                            APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(),
                                    "/consmod");

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (activity != null) {

                        String[] applianceTemp = new String[activity.getAppliancesOf().length];

                        String personTemp = "";
                        String activityTemp = "";
                        String durationTemp = "";
                        String dailyTemp = "";
                        String startTemp = "";

                        // For each appliance that participates in the activity
                        for (int j = 0; j < activity.getAppliancesOf().length; j++) {

                            Appliance activityAppliance = activity.getAppliancesOf()[j];
                            applianceTemp[j] = activityAppliance.getApplianceID();
                        }

                        personTemp = installation.getPerson().getPersonID();

                        try {

                            activity.setActivityID(APIUtilities
                                    .sendEntity(activity.activityToJSON(personTemp).toString(), "/act"));

                            String[] appliancesID = applianceTemp;

                            activity.setActivityModelID(APIUtilities
                                    .sendEntity(activity.toJSON(appliancesID).toString(), "/actmod"));
                            activityTemp = activity.getActivityModelID();

                            activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                    activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr"));
                            activity.setDailyID(activity.getDailyTimes().getDistributionID());
                            dailyTemp = activity.getDailyID();

                            activity.getDuration().setDistributionID(APIUtilities.sendEntity(
                                    activity.getDuration().toJSON(activityTemp).toString(), "/distr"));

                            activity.setDurationID(activity.getDuration().getDistributionID());
                            durationTemp = activity.getDurationID();

                            activity.getStartTime().setDistributionID(APIUtilities.sendEntity(
                                    activity.getStartTime().toJSON(activityTemp).toString(), "/distr"));

                            activity.setStartID(activity.getStartTime().getDistributionID());
                            startTemp = activity.getStartID();

                            APIUtilities.updateEntity(activity.toJSON(appliancesID).toString(), "/actmod",
                                    activityTemp);

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (response != null) {

                    }
                }

            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success, "The installation model " + installation.getName()
                    + " for the base pricing scheme and all the entities contained within were exported successfully",
                    "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE);

        }
    });

    exportAllResponseButton.addActionListener(new ActionListener() {
        /**
         * This function is called when the user presses the Export All Base
         * button on the Connection Properties panel of the Export Models tab. The
         * export procedure above is iterated through all the entities available
         * on the list except for the activity models.
         */
        @Override
        public void actionPerformed(ActionEvent e) {
            Component root = SwingUtilities.getRoot((JButton) e.getSource());

            try {

                root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

                for (int i = 0; i < exportModelList.getModel().getSize(); i++) {
                    exportModelList.setSelectedIndex(i);

                    String selection = exportModelList.getSelectedValue();

                    Appliance appliance = installation.findAppliance(selection);

                    ActivityModel activity = installation.getPerson().findActivity(selection, false);

                    ResponseModel response = installation.getPerson().findResponse(selection);

                    if (selection.equalsIgnoreCase(installation.getName())) {

                        String oldName = installation.getName();

                        try {

                            installation.setName(householdNameTextField.getText() + " Response");

                            installation.setInstallationID(APIUtilities.sendEntity(
                                    installation.toJSON(APIUtilities.getUserID()).toString(), "/inst"));

                            installation.setName(oldName);

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) {

                        try {
                            installation.getPerson().setPersonID(APIUtilities.sendEntity(installation
                                    .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers"));
                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (appliance != null) {

                        try {
                            appliance.setApplianceID(APIUtilities.sendEntity(
                                    appliance.toJSON(installation.getInstallationID().toString()).toString(),
                                    "/app"));

                            APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(),
                                    "/consmod");

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }

                    } else if (activity != null) {

                    } else if (response != null) {
                        String[] applianceTemp = new String[response.getAppliancesOf().length];

                        String personTemp = "";
                        String responseTemp = "";
                        String durationTemp = "";
                        String dailyTemp = "";
                        String startTemp = "";

                        // For each appliance that participates in the activity
                        for (int j = 0; j < response.getAppliancesOf().length; j++) {

                            Appliance responseAppliance = response.getAppliancesOf()[j];

                            applianceTemp[j] = responseAppliance.getApplianceID();
                        }
                        personTemp = installation.getPerson().getPersonID();

                        try {

                            response.setActivityID(APIUtilities
                                    .sendEntity(response.activityToJSON(personTemp).toString(), "/act"));

                            String[] appliancesID = applianceTemp;

                            response.setActivityModelID(APIUtilities
                                    .sendEntity(response.toJSON(appliancesID).toString(), "/actmod"));
                            responseTemp = response.getActivityModelID();

                            response.getDailyTimes().setDistributionID(APIUtilities.sendEntity(
                                    response.getDailyTimes().toJSON(responseTemp).toString(), "/distr"));
                            response.setDailyID(response.getDailyTimes().getDistributionID());
                            dailyTemp = response.getDailyID();

                            response.getDuration().setDistributionID(APIUtilities.sendEntity(
                                    response.getDuration().toJSON(responseTemp).toString(), "/distr"));

                            response.setDurationID(response.getDuration().getDistributionID());
                            durationTemp = response.getDurationID();

                            response.getStartTime().setDistributionID(APIUtilities.sendEntity(
                                    response.getStartTime().toJSON(responseTemp).toString(), "/distr"));

                            response.setStartID(response.getStartTime().getDistributionID());
                            startTemp = response.getStartID();

                            APIUtilities.updateEntity(response.toJSON(appliancesID).toString(), "/actmod",
                                    responseTemp);

                        } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }

            finally {
                root.setCursor(Cursor.getDefaultCursor());
            }

            JFrame success = new JFrame();

            JOptionPane.showMessageDialog(success, "The installation model " + installation.getName()
                    + " for the new pricing scheme and all the entities contained within were exported successfully",
                    "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE);
        }
    });
}

From source file:net.sourceforge.msscodefactory.cffreeswitch.v2_4.CFFreeSwitchSwing.CFFreeSwitchSwingPbxIvrMenuAttrJPanel.java

public void doLayout() {
    JLabel label;
    JComponent compo;/*from  ww w  .  jav  a2  s.  c  om*/
    CFJReferenceEditor reference;
    Dimension dim;
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 1024;
    Dimension jpsz = getSize();
    int usefieldwidth = jpsz.width - 215;

    label = getSwingLabelContainerTenant();
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceContainerTenant();
    reference.setBounds(fieldx, y, usefieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelMenuId();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorMenuId();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelName();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorName();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelGreetLong();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorGreetLong();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelGreetShort();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorGreetShort();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelInvalidSound();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorInvalidSound();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelExitSound();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorExitSound();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelTimeout();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorTimeout();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelInterDigitTimeout();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorInterDigitTimeout();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelMaxFailures();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorMaxFailures();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelMaxTimeouts();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorMaxTimeouts();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

    label = getSwingLabelDigitLen();
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDigitLen();
    dim = compo.getMaximumSize();
    if (dim.width < usefieldwidth) {
        compo.setBounds(fieldx, y, dim.width, height);
    } else {
        compo.setBounds(fieldx, y, fieldwidth, height);
    }
    y = y + vspacing;

}

From source file:atlas.kingj.roi.FrmMain.java

/**
 * Initialize the contents of the frame.
 *//*  w ww.  j a  va2 s .  c o m*/
private void initialize() {

    frmTitanRoiCalculator = new JFrame();
    frmTitanRoiCalculator.addWindowListener(new FrmTitanRoiCalculatorWindowListener());
    frmTitanRoiCalculator.setResizable(false);
    frmTitanRoiCalculator.setTitle("Titan Production Calculator");
    try {
        frmTitanRoiCalculator.setIconImage(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/logo.png")));//Toolkit.getDefaultToolkit().getImage(FrmMain.class.getResource("/atlas/logo.png")));
    } catch (NullPointerException e) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    frmTitanRoiCalculator.setBounds(100, 100, 800, 600);
    frmTitanRoiCalculator.setLocationRelativeTo(null);
    frmTitanRoiCalculator.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);//JFrame.EXIT_ON_CLOSE);

    JMenuBar menuBar = new JMenuBar();
    frmTitanRoiCalculator.setJMenuBar(menuBar);

    JMenu mnFile = new JMenu("File");
    mnFile.setMnemonic('F');
    menuBar.add(mnFile);

    mntmOpen = new JMenuItem("Open");
    mntmOpen.setMnemonic('O');
    mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
    mntmOpen.addActionListener(new MntmOpenActionListener());
    mnFile.add(mntmOpen);

    mntmSave = new JMenuItem("Save");
    mntmSave.setMnemonic('S');
    mntmSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
    mntmSave.addActionListener(new MntmSaveActionListener());
    mnFile.add(mntmSave);

    JMenuItem mntmExit = new JMenuItem("Exit");
    mntmExit.setMnemonic('X');
    mntmExit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            SaveAndClose();
        }
    });

    mntmSaveAll = new JMenuItem("Save All");
    mntmSaveAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            SaveAll();
        }
    });

    mntmOpenAll = new JMenuItem("Open All");
    mntmOpenAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            OpenAll();
        }
    });
    mnFile.add(mntmOpenAll);
    mntmSaveAll.setMnemonic('V');
    mnFile.add(mntmSaveAll);

    mnExport = new JMenu("Export");
    mnFile.add(mnExport);

    mntmSpreadsheet = new JMenuItem("Spreadsheet");
    mntmSpreadsheet.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ResetStatusLabel();

            fc = new OpenSaveFileChooser();
            fc.setFileFilter(new XLSfilter());
            fc.type = 3;

            int returnVal = fc.showSaveDialog(frmTitanRoiCalculator);
            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();

                String path = file.getAbsolutePath();

                String extension = ".xls";

                if (!path.endsWith(extension)) {
                    file = new File(path + extension);
                }

                StatusDialog a = new StatusDialog("Generating spreadsheet...");

                SaveFileWorker worker = new SaveFileWorker(file, a, false);

                worker.execute();

                a.setLocationRelativeTo(frmTitanRoiCalculator);
                a.setVisible(true);

                if (FileSaveError)
                    ShowMessage("File save error");
                else if (FileSaveWarning)
                    ShowMessage("File saved, but possible errors.");
                else
                    ShowMessageSuccess("File saved.");

            }
        }
    });
    mnExport.add(mntmSpreadsheet);
    mnFile.add(mntmExit);

    JMenu mnView = new JMenu("View");
    mnView.setMnemonic('V');
    menuBar.add(mnView);

    RoiData = new ROIData();

    mntmUnitConverter = new JMenuItem("Unit Converter");
    mntmUnitConverter.setMnemonic('C');
    mntmUnitConverter.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_MASK));
    mntmUnitConverter.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            new UnitConverter();
        }
    });
    mnView.add(mntmUnitConverter);

    mnSettings = new JMenu("Settings");
    mnSettings.setMnemonic('E');
    menuBar.add(mnSettings);

    mnUnits = new JMenu("Units");
    mnUnits.setMnemonic('U');
    mnSettings.add(mnUnits);

    rdbtnmntmImperial = new JRadioButtonMenuItem("Imperial");
    rdbtnmntmImperial.setMnemonic('I');
    rdbtnmntmImperial.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, InputEvent.CTRL_MASK));
    rdbtnmntmImperial.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (metric) {
                // Change units from metric to imperial
                ChangeUnits();
            }
        }
    });
    mnUnits.add(rdbtnmntmImperial);

    rdbtnmntmMetric = new JRadioButtonMenuItem("Metric");
    rdbtnmntmMetric.setMnemonic('M');
    rdbtnmntmMetric.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.CTRL_MASK));
    rdbtnmntmMetric.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!metric) {
                // Change units from imperial to metric
                ChangeUnits();
            }
        }
    });
    rdbtnmntmMetric.setSelected(true);
    mnUnits.add(rdbtnmntmMetric);

    btnsUnits.add(rdbtnmntmMetric);
    btnsUnits.add(rdbtnmntmImperial);

    JMenuItem mntmOptions_1 = new JMenuItem("Options");
    mntmOptions_1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.CTRL_MASK));
    mntmOptions_1.setMnemonic('O');
    mntmOptions_1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            Machine machine = null;
            if (listMachines.getSelectedIndex() > -1)
                machine = (Machine) listMachines.getSelectedValue();
            OptionDialog options = new OptionDialog(environment, machine);
            options.setLocationRelativeTo(frmTitanRoiCalculator);
            options.addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosed(WindowEvent e) {
                    UpdateAnalysis();
                }
            });
            options.setVisible(true);
        }
    });

    mnTimings = new JMenu("Timings");
    mnSettings.add(mnTimings);

    mntmSaveToFile = new JMenuItem("Save to File");
    mntmSaveToFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            OperatorTimings times = environment.timings;

            fc = new OpenSaveFileChooser();
            fc.setFileFilter(new OBJfilter(3));
            fc.type = 1;

            int returnVal = fc.showSaveDialog(frmTitanRoiCalculator);
            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();

                String path = file.getAbsolutePath();

                String extension = ".ser";

                if (!path.endsWith(extension)) {
                    file = new File(path + extension);
                }

                try {
                    FileOutputStream fout = new FileOutputStream(file);
                    ObjectOutputStream oos = new ObjectOutputStream(fout);
                    oos.writeObject(times);
                    oos.close();
                    ShowMessageSuccess("File saved.");
                } catch (Exception e1) {
                    JOptionPane.showMessageDialog(frmTitanRoiCalculator, "Error writing file.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    });
    mnTimings.add(mntmSaveToFile);

    mntmLoadFromFile = new JMenuItem("Load from File");
    mntmLoadFromFile.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            fc = new OpenSaveFileChooser();
            fc.setFileFilter(new OBJfilter(3));
            fc.type = 1;

            int returnVal = fc.showOpenDialog(frmTitanRoiCalculator);
            if (returnVal == JFileChooser.APPROVE_OPTION) {

                File file = fc.getSelectedFile();

                try {
                    FileInputStream fin = new FileInputStream(file);
                    ObjectInputStream ois = new ObjectInputStream(fin);
                    environment.timings = (OperatorTimings) ois.readObject();
                    ois.close();

                    ShowMessageSuccess("File loaded.");

                } catch (Exception e1) {
                    ShowMessage("File error.");
                }
            }
        }
    });
    mnTimings.add(mntmLoadFromFile);
    mnSettings.add(mntmOptions_1);

    JMenu mnHelp = new JMenu("Help");
    mnHelp.setMnemonic('H');
    menuBar.add(mnHelp);

    JMenuItem mntmInstructions = new JMenuItem("Instructions");
    mntmInstructions.setMnemonic('I');
    mntmInstructions.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            InstructDialog instructions = new InstructDialog();
            instructions.setLocationRelativeTo(frmTitanRoiCalculator);
            instructions.setVisible(true);
        }
    });
    mnHelp.add(mntmInstructions);

    JMenuItem mntmAbout = new JMenuItem("About");
    mntmAbout.setMnemonic('A');
    mntmAbout.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            AboutDialog about = new AboutDialog();
            about.setLocationRelativeTo(frmTitanRoiCalculator);
            about.setVisible(true);
        }
    });
    mnHelp.add(mntmAbout);

    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    tabbedPane.addChangeListener(TabChangeListener);
    frmTitanRoiCalculator.getContentPane().add(tabbedPane, BorderLayout.CENTER);

    pnlMachine = new JPanel();
    tabbedPane.addTab("Machine Selection", null, pnlMachine, "Add and configure machine setups");
    tabbedPane.setEnabledAt(0, true);
    pnlMachine.setLayout(null);

    grpMachines = new JPanel();
    grpMachines.setFont(new Font("Tahoma", Font.PLAIN, 11));
    grpMachines.setBounds(20, 72, 182, 256);
    grpMachines.setBorder(
            new TitledBorder(null, "Machine Type", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlMachine.add(grpMachines);
    grpMachines.setLayout(null);

    try {
        rdbtnER610 = new JRadioButton(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/er610.png"))));
        rdbtnER610.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/er610_dis.png"))));
        rdbtnER610.setDisabledSelectedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/er610_dis.png"))));
        rdbtnER610.setEnabled(false);
        rdbtnER610.setToolTipText("Titan ER610");
    } catch (NullPointerException e1) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    rdbtnER610.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            rdbtnClick("ER610");
            UpdateMachine();
            listMachines.repaint();
        }
    });
    rdbtnER610.setSelected(true);
    rdbtnER610.setBounds(13, 24, 155, 40);
    try {
        rdbtnER610.setPressedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/er610_down.png"))));
        rdbtnER610.setRolloverEnabled(true);
        rdbtnER610.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/er610_over.png"))));
        rdbtnER610.setSelectedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/er610_select.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    grpMachines.add(rdbtnER610);

    try {
        rdbtnSR9DS = new JRadioButton(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9ds.png"))));
        rdbtnSR9DS.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9ds_dis.png"))));
        rdbtnSR9DS.setEnabled(false);
        rdbtnSR9DS.setToolTipText("Titan SR9-DS");
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    rdbtnSR9DS.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            rdbtnClick("SR9DS");
            UpdateMachine();
            listMachines.repaint();
        }
    });

    try {
        rdbtnSR9DS.setPressedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9ds_down.png"))));
        rdbtnSR9DS.setRolloverEnabled(true);
        rdbtnSR9DS.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9ds_over.png"))));
        rdbtnSR9DS.setSelectedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9ds_select.png"))));
        rdbtnSR9DS.setBounds(13, 68, 155, 40);
        grpMachines.add(rdbtnSR9DS);

        rdbtnSR9DT = new JRadioButton(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9dt.png"))));
        rdbtnSR9DT.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9dt_dis.png"))));
        rdbtnSR9DT.setEnabled(false);
        rdbtnSR9DT.setToolTipText("Titan SR9-DT");
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    rdbtnSR9DT.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            rdbtnClick("SR9DT");
            UpdateMachine();
            listMachines.repaint();
        }
    });
    rdbtnSR9DT.setBounds(13, 112, 155, 40);
    try {
        rdbtnSR9DT.setPressedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9dt_down.png"))));
        rdbtnSR9DT.setRolloverEnabled(true);
        rdbtnSR9DT.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9dt_over.png"))));
        rdbtnSR9DT.setSelectedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr9dt_select.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    grpMachines.add(rdbtnSR9DT);

    try {
        rdbtnSR800 = new JRadioButton(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr800.png"))));
        rdbtnSR800.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr800_dis.png"))));
        rdbtnSR800.setEnabled(false);
        rdbtnSR800.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                rdbtnClick("SR800");
                UpdateMachine();
                listMachines.repaint();
            }
        });
        rdbtnSR800.setPressedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr800_down.png"))));
        rdbtnSR800.setRolloverEnabled(true);
        rdbtnSR800.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr800_over.png"))));
        rdbtnSR800.setSelectedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/sr800_select.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    rdbtnSR800.setToolTipText("Titan SR800");
    rdbtnSR800.setRolloverEnabled(true);
    rdbtnSR800.setBounds(13, 156, 155, 40);
    grpMachines.add(rdbtnSR800);

    try {
        rdbtnCustom = new JRadioButton(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/custom.png"))));
        rdbtnCustom.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/custom_dis.png"))));
        rdbtnCustom.setEnabled(false);
        rdbtnCustom.setPressedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/custom_down.png"))));
        rdbtnCustom.setRolloverEnabled(true);
        rdbtnCustom.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/custom_over.png"))));
        rdbtnCustom.setSelectedIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/custom_select.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    rdbtnCustom.setToolTipText("Custom Machine");
    rdbtnCustom.setRolloverEnabled(true);
    rdbtnCustom.setBounds(13, 200, 155, 40);
    grpMachines.add(rdbtnCustom);
    rdbtnCustom.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            rdbtnClick("Custom");
            UpdateMachine();
            ResetStatusLabel();
            listMachines.repaint();
        }
    });

    rdbtnsMachines.add(rdbtnER610);
    rdbtnsMachines.add(rdbtnSR9DS);
    rdbtnsMachines.add(rdbtnSR9DT);
    rdbtnsMachines.add(rdbtnSR800);
    rdbtnsMachines.add(rdbtnCustom);

    grpVariants = new JPanel();
    grpVariants.setFont(new Font("Tahoma", Font.PLAIN, 11));
    grpVariants.setBounds(20, 339, 482, 112);
    grpVariants
            .setBorder(new TitledBorder(null, "Variants", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlMachine.add(grpVariants);
    grpVariants.setLayout(null);

    cmbCorepos = new JComboBox();
    cmbCorepos.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbCorepos.setToolTipText("Set the core positioning system");
    cmbCorepos.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
        }
    });
    cmbCorepos.setEnabled(false);
    cmbCorepos.setBounds(104, 70, 122, 20);
    grpVariants.add(cmbCorepos);
    cmbCorepos.setModel(new DefaultComboBoxModel(new String[] { "Manual", "Laser" }));

    lblCorePositioning = new JLabel("Core Positioning:");
    lblCorePositioning.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblCorePositioning.setToolTipText("Set the core positioning system");
    lblCorePositioning.setEnabled(false);
    lblCorePositioning.setHorizontalAlignment(SwingConstants.RIGHT);
    lblCorePositioning.setBounds(12, 73, 88, 14);
    grpVariants.add(lblCorePositioning);

    lblKnifeControl = new JLabel("Knife Control:");
    lblKnifeControl.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblKnifeControl.setToolTipText("Set the type of knife positioning system");
    lblKnifeControl.setEnabled(false);
    lblKnifeControl.setHorizontalAlignment(SwingConstants.RIGHT);
    lblKnifeControl.setBounds(22, 48, 78, 14);
    grpVariants.add(lblKnifeControl);

    cmbKnives = new JComboBox();
    cmbKnives.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbKnives.setToolTipText("Set the type of knife positioning system");
    cmbKnives.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
        }
    });
    cmbKnives.setEnabled(false);
    cmbKnives.setBounds(104, 45, 122, 20);
    grpVariants.add(cmbKnives);
    cmbKnives.setModel(new DefaultComboBoxModel(new String[] { "Manual", "Auto" }));

    cmbUnloader = new JComboBox();
    cmbUnloader.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbUnloader.setToolTipText("Set the unloader type");
    cmbUnloader.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
        }
    });
    cmbUnloader.setEnabled(false);
    cmbUnloader.setBounds(350, 20, 122, 20);
    grpVariants.add(cmbUnloader);
    cmbUnloader.setModel(new DefaultComboBoxModel(new String[] { "Manual", "Pneumatic", "Electric" }));

    lblUnloader = new JLabel("Unloader:");
    lblUnloader.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblUnloader.setToolTipText("Set the unloader type");
    lblUnloader.setEnabled(false);
    lblUnloader.setHorizontalAlignment(SwingConstants.RIGHT);
    lblUnloader.setBounds(259, 23, 87, 14);
    grpVariants.add(lblUnloader);

    cmbSpeed = new JComboBox();
    cmbSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbSpeed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (formReady)
                UpdateMachine();
        }
    });
    cmbSpeed.setEnabled(false);
    cmbSpeed.setToolTipText("Machine top speed in metres/min");
    cmbSpeed.setBounds(104, 20, 122, 20);
    grpVariants.add(cmbSpeed);
    cmbSpeed.setModel(new DefaultComboBoxModel(new String[] { "450", "550" }));

    lblSpeed = new JLabel("Speed:");
    lblSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblSpeed.setToolTipText("Machine top speed in metres/min");
    lblSpeed.setEnabled(false);
    lblSpeed.setHorizontalAlignment(SwingConstants.RIGHT);
    lblSpeed.setBounds(54, 23, 46, 14);
    grpVariants.add(lblSpeed);

    cmbUnwindDrive = new JComboBox();
    cmbUnwindDrive.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbUnwindDrive.setToolTipText("Unwind drive type");
    cmbUnwindDrive.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
        }
    });
    cmbUnwindDrive.setEnabled(false);
    cmbUnwindDrive.setBounds(350, 45, 122, 20);
    grpVariants.add(cmbUnwindDrive);
    cmbUnwindDrive.setModel(new DefaultComboBoxModel(new String[] { "Single", "Double" }));

    lblUnwindDrive = new JLabel("Unwind Drive:");
    lblUnwindDrive.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblUnwindDrive.setToolTipText("Unwind drive type");
    lblUnwindDrive.setEnabled(false);
    lblUnwindDrive.setHorizontalAlignment(SwingConstants.RIGHT);
    lblUnwindDrive.setBounds(259, 48, 87, 14);
    grpVariants.add(lblUnwindDrive);

    lblRewindControlLoop = new JLabel("Rewind Control Loop:");
    lblRewindControlLoop.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblRewindControlLoop.setToolTipText("Rewind control loop type");
    lblRewindControlLoop.setEnabled(false);
    lblRewindControlLoop.setHorizontalAlignment(SwingConstants.RIGHT);
    lblRewindControlLoop.setBounds(224, 73, 122, 14);
    grpVariants.add(lblRewindControlLoop);

    cmbRewindCtrl = new JComboBox();
    cmbRewindCtrl.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbRewindCtrl.setToolTipText("Rewind control loop type");
    cmbRewindCtrl.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
        }
    });
    cmbRewindCtrl.setEnabled(false);
    cmbRewindCtrl.setBounds(350, 70, 122, 20);
    grpVariants.add(cmbRewindCtrl);
    cmbRewindCtrl.setModel(new DefaultComboBoxModel(new String[] { "Open", "Closed" }));

    listModel = new DefaultListModel();
    jobModel = new DefaultListModel();
    scheduleModel = new DefaultListModel();
    listModel.removeAllElements();
    /*listMachines.setModel(new AbstractListModel() {
       String[] values = new String[] {"ER610: My test 1", "SR9-DS: this is another test", "SR9-DT: third test", "ER610:  test 2", "ER610: bla bla", "SR9-DS: this is another test", "SR9-DT: hello", "SR9-DT: third test"};
       public int getSize() {
    return values.length;
       }
       public Object getElementAt(int index) {
    return values[index];
       }
    });*/

    JLabel lblMachines = new JLabel("Machines");
    lblMachines.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblMachines.setBounds(522, 19, 85, 14);
    pnlMachine.add(lblMachines);

    btnMachDelete = new JButton("");
    try {
        btnMachDelete
                .setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete.png"))));
        btnMachDelete.setRolloverEnabled(true);
        btnMachDelete.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete_over.png"))));
        btnMachDelete.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnMachDelete.setToolTipText("Delete machine");
    btnMachDelete.setEnabled(false);
    btnMachDelete.addActionListener(new DeleteButtonListener());
    btnMachDelete.setBounds(651, 460, 36, 36);
    pnlMachine.add(btnMachDelete);

    btnMachUp = new JButton("");
    btnMachUp.setToolTipText("Move machine up");
    btnMachUp.setEnabled(false);
    try {
        btnMachUp.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up.png"))));
        btnMachUp.setRolloverEnabled(true);
        btnMachUp.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up_over.png"))));
        btnMachUp.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnMachUp.addActionListener(new UpListener());
    btnMachUp.setBounds(700, 463, 30, 30);
    pnlMachine.add(btnMachUp);

    btnMachDown = new JButton("");
    btnMachDown.setToolTipText("Move machine down");
    btnMachDown.setEnabled(false);
    try {
        btnMachDown.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down.png"))));
        btnMachDown.setRolloverEnabled(true);
        btnMachDown.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down_over.png"))));
        btnMachDown.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnMachDown.addActionListener(new DownListener());
    btnMachDown.setBounds(737, 463, 30, 30);
    pnlMachine.add(btnMachDown);

    btnMachReset = new JButton("Reset");
    btnMachReset.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnMachReset.setEnabled(false);
    btnMachReset.setToolTipText("Reset the form");
    btnMachReset.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ResetForm();
        }
    });

    btnMachReset.setBounds(20, 460, 100, 36);
    pnlMachine.add(btnMachReset);
    /*txtMachName.addKeyListener(new KeyAdapter() {
       @Override
       public void keyPressed(KeyEvent e) {
    int key = e.getKeyCode();  
    if (e.getKeyCode() == KeyEvent.VK_ENTER)  
       btnAddMachine.doClick();
       }
    });*/

    btnNewMachine = new JButton("Add New");
    btnNewMachine.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnNewMachine.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            formReady = false;

            ResetStatusLabel();

            int index = listMachines.getSelectedIndex();
            int size = listModel.getSize();

            if (size >= Consts.MACH_LIST_LIMIT) { // Max list size
                ShowMessage(
                        "Maximum number of machines allocated. Please delete before attempting to add more.");
                return;
            }

            String newName = getUniqueName("Machine");
            txtMachName.setText(newName);
            machine = new Machine(newName);
            machNames.add(newName.toLowerCase());

            //If no selection or if item in last position is selected,
            //add the new one to end of list, and select new one.
            if (index == -1 || (index + 1 == size)) {

                listModel.addElement(machine);
                listMachines.setSelectedIndex(size);

                RoiData.energies.add(RoiData.new EnergyData());
                RoiData.maintenance.add(RoiData.new MaintData());
                listCompare.addSelectionInterval(size, size);

                //Otherwise insert the new one after the current selection,
                //and select new one.
            } else {
                int[] sel = listCompare.getSelectedIndices();
                int[] selection = new int[sel.length + 1];
                System.arraycopy(sel, 0, selection, 0, sel.length);
                listCompare.setSelectedIndices(new int[] {});
                listModel.insertElementAt(machine, index + 1);

                boolean max = false;
                for (int i = 0; i < selection.length; i++) {
                    if (selection[i] >= index + 1 && !max) {
                        if (i < selection.length - 1)
                            System.arraycopy(selection, i, selection, i + 1, selection.length - i - 1);
                        selection[i] = index + 1;
                        max = true;
                    } else if (selection[i] >= index + 1)
                        selection[i] = selection[i] + 1;
                }
                RoiData.energies.add(index + 1, RoiData.new EnergyData());
                RoiData.maintenance.add(index + 1, RoiData.new MaintData());
                listCompare.setSelectedIndices(selection);
                //listCompareRoi.setSelectedIndices(selection);
                listMachines.setSelectedIndex(index + 1);
                //listCompare.addSelectionInterval(index + 1, index + 1);
            }

            ResetStatusLabel();
            //UpdateForm();  already triggered in listchanged
            formReady = true;
            txtMachName.requestFocusInWindow();
        }
    });
    try {
        btnNewMachine
                .setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/plus.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnNewMachine.setToolTipText("Add new machine");
    btnNewMachine.setBounds(522, 460, 110, 36);
    pnlMachine.add(btnNewMachine);

    grpOptions = new JPanel();
    grpOptions.setFont(new Font("Tahoma", Font.PLAIN, 11));
    grpOptions.setBounds(212, 72, 290, 256);
    pnlMachine.add(grpOptions);
    grpOptions.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Options",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    grpOptions.setLayout(null);

    chckbxFlag = new JCheckBox("Flag Detection");
    chckbxFlag.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxFlag.setToolTipText("Whether an automatic flag detection system is used");
    chckbxFlag.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxFlag.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxFlag.setEnabled(false);
    chckbxFlag.setBounds(155, 104, 109, 23);
    grpOptions.add(chckbxFlag);

    chckbxSpliceTable = new JCheckBox("Splice Table");
    chckbxSpliceTable.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxSpliceTable.setToolTipText("Whether a splice table is fitted");
    chckbxSpliceTable.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxSpliceTable.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxSpliceTable.setEnabled(false);
    chckbxSpliceTable.setBounds(22, 104, 109, 23);
    grpOptions.add(chckbxSpliceTable);

    chckbxAlignmentGuide = new JCheckBox("Alignment Guide");
    chckbxAlignmentGuide.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxAlignmentGuide.setToolTipText("Whether an alignment guide is fitted");
    chckbxAlignmentGuide.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxAlignmentGuide.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxAlignmentGuide.setEnabled(false);
    chckbxAlignmentGuide.setBounds(22, 130, 127, 23);
    grpOptions.add(chckbxAlignmentGuide);

    chckbxRollConditioning = new JCheckBox("Roll Conditioning");
    chckbxRollConditioning.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxRollConditioning.setToolTipText("Whether the machine supports roll conditioning");
    chckbxRollConditioning.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxRollConditioning.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxRollConditioning.setEnabled(false);
    chckbxRollConditioning.setBounds(22, 156, 127, 23);
    grpOptions.add(chckbxRollConditioning);

    chckbxTurretSupport = new JCheckBox("Turret Support");
    chckbxTurretSupport.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxTurretSupport.setToolTipText("For dual turret machines: extra turret support");
    chckbxTurretSupport.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxTurretSupport.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxTurretSupport.setEnabled(false);
    chckbxTurretSupport.setBounds(22, 182, 127, 23);
    grpOptions.add(chckbxTurretSupport);

    chckbxAutostripping = new JCheckBox("Autostripping");
    chckbxAutostripping.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxAutostripping.setToolTipText("Whether an autostripping feature is present for reel unloading");
    chckbxAutostripping.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxAutostripping.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxAutostripping.setEnabled(false);
    chckbxAutostripping.setBounds(22, 208, 97, 23);
    grpOptions.add(chckbxAutostripping);

    chckbxExtraRewind = new JCheckBox("850mm Rewind");
    chckbxExtraRewind.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxExtraRewind.setToolTipText("Extra wide 850mm max diameter rewind support");
    chckbxExtraRewind.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxExtraRewind.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxExtraRewind.setEnabled(false);
    chckbxExtraRewind.setBounds(155, 208, 109, 23);
    grpOptions.add(chckbxExtraRewind);

    chckbxAutoCutoff = new JCheckBox("Auto Cut-off");
    chckbxAutoCutoff.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxAutoCutoff.setToolTipText("Whether the web is cut automatically when a run completes");
    chckbxAutoCutoff.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxAutoCutoff.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxAutoCutoff.setEnabled(false);
    chckbxAutoCutoff.setBounds(155, 130, 109, 23);
    grpOptions.add(chckbxAutoCutoff);

    chckbxAutoTapeCore = new JCheckBox("Auto Tape Core");
    chckbxAutoTapeCore.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxAutoTapeCore.setToolTipText("Whether new reels are automatically taped before a run begins");
    chckbxAutoTapeCore.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxAutoTapeCore.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxAutoTapeCore.setEnabled(false);
    chckbxAutoTapeCore.setBounds(155, 156, 109, 23);
    grpOptions.add(chckbxAutoTapeCore);

    chckbxAutoTapeTail = new JCheckBox("Auto Tape Tail");
    chckbxAutoTapeTail.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxAutoTapeTail.setToolTipText("Whether the tails of completed reels are automatically taped down");
    chckbxAutoTapeTail.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (formReady)
                UpdateMachine();
            if (!chckbxAutoTapeTail.isSelected())
                chckbxSelectAll.setSelected(false);
            else
                UpdateSelectAllChckbx();
        }
    });
    chckbxAutoTapeTail.setEnabled(false);
    chckbxAutoTapeTail.setBounds(155, 182, 109, 23);
    grpOptions.add(chckbxAutoTapeTail);

    txtMachName = new JTextField();
    txtMachName.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtMachName.selectAll();
        }
    });
    txtMachName.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateMachineName();
        }

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateMachineName();
        }
    });
    txtMachName.setEnabled(false);
    txtMachName.setBounds(125, 35, 137, 28);
    grpOptions.add(txtMachName);
    txtMachName.getDocument().addDocumentListener(new DocumentListener() {
        public void changedUpdate(DocumentEvent e) {
        }

        public void removeUpdate(DocumentEvent e) {
            // text was deleted
        }

        public void insertUpdate(DocumentEvent e) {
            // text was inserted
        }
    });

    txtMachName.setToolTipText("Enter a name to refer to this particular machine by");
    txtMachName.setFont(new Font("Tahoma", Font.BOLD, 12));
    txtMachName.setColumns(10);

    lblMachName = new JLabel("Machine name:");
    lblMachName.setToolTipText("Enter a name to refer to this particular machine by");
    lblMachName.setEnabled(false);
    lblMachName.setBounds(26, 36, 91, 24);
    grpOptions.add(lblMachName);
    lblMachName.setFont(new Font("Tahoma", Font.PLAIN, 13));

    chckbxSelectAll = new JCheckBox("Select All");
    chckbxSelectAll.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxSelectAll.setToolTipText("Select all available options");
    chckbxSelectAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chckbxSelectAll.isSelected()) {
                if (chckbxAlignmentGuide.isEnabled())
                    chckbxAlignmentGuide.setSelected(true);
                if (chckbxAutoCutoff.isEnabled())
                    chckbxAutoCutoff.setSelected(true);
                if (chckbxAutostripping.isEnabled())
                    chckbxAutostripping.setSelected(true);
                if (chckbxAutoTapeCore.isEnabled())
                    chckbxAutoTapeCore.setSelected(true);
                if (chckbxAutoTapeTail.isEnabled())
                    chckbxAutoTapeTail.setSelected(true);
                if (chckbxExtraRewind.isEnabled())
                    chckbxExtraRewind.setSelected(true);
                if (chckbxFlag.isEnabled())
                    chckbxFlag.setSelected(true);
                if (chckbxRollConditioning.isEnabled())
                    chckbxRollConditioning.setSelected(true);
                if (chckbxSpliceTable.isEnabled())
                    chckbxSpliceTable.setSelected(true);
                if (chckbxTurretSupport.isEnabled())
                    chckbxTurretSupport.setSelected(true);
            } else {
                chckbxAlignmentGuide.setSelected(false);
                chckbxAutoCutoff.setSelected(false);
                chckbxAutostripping.setSelected(false);
                chckbxAutoTapeCore.setSelected(false);
                chckbxAutoTapeTail.setSelected(false);
                chckbxExtraRewind.setSelected(false);
                chckbxFlag.setSelected(false);
                chckbxRollConditioning.setSelected(false);
                chckbxSpliceTable.setSelected(false);
                chckbxTurretSupport.setSelected(false);
            }

            if (formReady)
                UpdateMachine();
        }
    });
    chckbxSelectAll.setEnabled(false);
    chckbxSelectAll.setBounds(22, 78, 97, 23);
    grpOptions.add(chckbxSelectAll);

    lblMachineConfiguration = new JLabel("Machine Configuration");
    lblMachineConfiguration.setFont(new Font("Tahoma", Font.BOLD, 18));
    lblMachineConfiguration.setBounds(29, 18, 269, 22);
    pnlMachine.add(lblMachineConfiguration);

    lblAddNewMachines = new JLabel(
            "Add new machines to the list on the right, then configure their options and variants below");
    lblAddNewMachines.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblAddNewMachines.setBounds(29, 45, 433, 14);
    pnlMachine.add(lblAddNewMachines);

    btnCustomMachine = new JButton("Custom Machine Options");
    btnCustomMachine.setEnabled(false);
    btnCustomMachine.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnCustomMachine.setBounds(322, 460, 180, 36);
    pnlMachine.add(btnCustomMachine);
    btnCustomMachine.setToolTipText("Edit settings for a custom machine type");

    scrollPane = new JScrollPane();
    scrollPane.setBorder(null);
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setBounds(522, 44, 245, 405);
    pnlMachine.add(scrollPane);

    panel_6 = new JPanel();
    panel_6.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, new Color(192, 192, 192), null, null, null));
    panel_6.setBackground(Color.WHITE);
    panel_6.setToolTipText("Select a machine to edit options, re-order, or delete");
    scrollPane.setViewportView(panel_6);
    panel_6.setLayout(new BorderLayout(0, 0));

    //Create the list and put it in a scroll pane.
    listMachines = new JList(listModel);
    panel_6.add(listMachines, BorderLayout.NORTH);
    listMachines.addListSelectionListener(new MachineListSelectionListener());
    listMachines.setCellRenderer(new MachineListRenderer());

    listMachines.setBorder(null);
    listMachines.setToolTipText("Select a machine to edit options, re-order, or delete");
    listMachines.setFont(new Font("Tahoma", Font.PLAIN, 13));
    listMachines.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    btnOverrideDefaultAcceleration = new JButton("Override Default Acceleration");
    btnOverrideDefaultAcceleration.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnOverrideDefaultAcceleration
            .setToolTipText("Set new values for the acceleration/deceleration of this machine");
    btnOverrideDefaultAcceleration.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try { // check list selected
                listMachines.getSelectedIndex();
            } catch (Exception e2) {
                return;
            }
            Machine currMachine = (Machine) listMachines.getSelectedValue();
            AccelDecel dialog = new AccelDecel(currMachine);
            dialog.setLocationRelativeTo(frmTitanRoiCalculator);
            dialog.setVisible(true);
        }
    });
    btnOverrideDefaultAcceleration.setEnabled(false);
    btnOverrideDefaultAcceleration.setBounds(130, 460, 182, 36);
    pnlMachine.add(btnOverrideDefaultAcceleration);

    btnCustomMachine.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ResetStatusLabel();
            //rdbtnOther.doClick();
            MachineBuilder newmach = new MachineBuilder(machine);
            newmach.setLocationRelativeTo(frmTitanRoiCalculator);
            newmach.setVisible(true);
        }
    });

    pnlJob = new JPanel();
    tabbedPane.addTab("Job Selection", null, pnlJob, "Add and configure machine jobs");
    tabbedPane.setEnabledAt(1, true);
    pnlJob.setLayout(null);

    JPanel pnlMaterials = new JPanel();
    pnlMaterials.setBounds(280, 72, 227, 124);
    pnlMaterials.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Material Settings",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlJob.add(pnlMaterials);
    pnlMaterials.setLayout(null);

    Material[] materials = { new Material("Custom", 1.0, 20), new Material("Aluminium", 2.7, 40),
            new Material("Board", 1.3, 80), new Material("Cellophane", 1.5, 20),
            new Material("HDPE/BOPE", 0.94, 20), new Material("Laminate", 1.0, 20),
            new Material("LDPE/BOPE", 0.91, 20), new Material("LLDPE", 0.9, 20),
            new Material("MDPE", 0.925, 20), new Material("Nylon", 1.12, 20),
            new Material("Polypropylene", 0.91, 20), new Material("Polystyrene", 1.04, 20),
            new Material("Paper", 0.8, 100), new Material("PEEK", 1.3, 20), new Material("Polyester", 1.4, 20),
            new Material("PLA", 1.24, 20), new Material("Polyolefin", 0.92, 20),
            new Material("PSA Label", 1.1, 20), new Material("PVC", 1.36, 20),
            new Material("Shrink label", 0.91, 20), new Material("Tri. Lam.", 1.1, 20) };

    cmbMaterials = new JComboBox(materials);
    cmbMaterials.setMaximumRowCount(20);
    cmbMaterials.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            if (jobFormReady) {
                Material m = (Material) cmbMaterials.getSelectedItem();
                if (!(m.name.equals("Custom"))) {
                    jobFormReady = false;
                    txtThickness.setText(Double.toString(roundTwoDecimals(m.getThickness())));
                    if (lblGsm.getText().equals("(gsm)"))
                        txtDensity.setText(Double.toString(roundTwoDecimals(m.getDensity())));
                    else
                        txtDensity
                                .setText(Double.toString(roundTwoDecimals(m.getDensity() * m.getThickness())));
                    if (!metric) {
                        txtThickness
                                .setText(Double.toString(roundTwoDecimals(Core.MicroToMil(m.getThickness()))));
                    }
                    jobFormReady = true;
                }
                UpdateJob();
            }
        }
    });
    cmbMaterials.setEnabled(false);
    cmbMaterials.setSelectedIndex(0);
    cmbMaterials.setToolTipText("Choose a preset material");
    cmbMaterials.setBounds(81, 26, 117, 22);
    pnlMaterials.add(cmbMaterials);

    lblPresets = new JLabel("Presets:");
    lblPresets.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPresets.setToolTipText("Choose a preset material");
    lblPresets.setEnabled(false);
    lblPresets.setBounds(37, 29, 40, 15);
    pnlMaterials.add(lblPresets);

    lblThickness_1 = new JLabel("Thickness:");
    lblThickness_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblThickness_1.setToolTipText("Material thickness");
    lblThickness_1.setEnabled(false);
    lblThickness_1.setHorizontalAlignment(SwingConstants.RIGHT);
    lblThickness_1.setBounds(7, 61, 70, 14);
    pnlMaterials.add(lblThickness_1);

    lblDensity_1 = new JLabel("Density:");
    lblDensity_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblDensity_1.setToolTipText("Material density (per volume, not area)");
    lblDensity_1.setEnabled(false);
    lblDensity_1.setHorizontalAlignment(SwingConstants.RIGHT);
    lblDensity_1.setBounds(31, 86, 46, 14);
    pnlMaterials.add(lblDensity_1);

    txtThickness = new JTextField();
    txtThickness.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtThickness.selectAll();
        }
    });
    txtThickness.setEnabled(false);
    txtThickness.getDocument().addDocumentListener(new JobInputChangeListener());

    txtThickness.setToolTipText("Material thickness");
    txtThickness.setText("20");
    txtThickness.setBounds(81, 58, 86, 20);
    pnlMaterials.add(txtThickness);
    txtThickness.setColumns(10);

    txtDensity = new JTextField();
    txtDensity.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtDensity.selectAll();
        }
    });
    txtDensity.setEnabled(false);
    txtDensity.getDocument().addDocumentListener(new JobInputChangeListener());

    txtDensity.setToolTipText("Material density (per volume, not area)");
    txtDensity.setText("0.92");
    txtDensity.setBounds(81, 83, 86, 20);
    pnlMaterials.add(txtDensity);
    txtDensity.setColumns(10);

    lblmicro0 = new JLabel("(\u00B5m)");
    lblmicro0.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblmicro0.setEnabled(false);
    lblmicro0.setBounds(177, 61, 46, 14);
    pnlMaterials.add(lblmicro0);

    lblgm3 = new JLabel("(g/cm  )");
    lblgm3.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblgm3.setEnabled(false);
    lblgm3.setBounds(177, 86, 46, 14);
    pnlMaterials.add(lblgm3);

    label_3 = new JLabel("3");
    label_3.setEnabled(false);
    label_3.setFont(new Font("Tahoma", Font.PLAIN, 8));
    label_3.setBounds(204, 83, 14, 14);
    pnlMaterials.add(label_3);

    JPanel pnlJobs = new JPanel();
    pnlJobs.setBounds(20, 168, 250, 283);
    pnlJobs.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Rewind Settings",
            TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
    pnlJob.add(pnlJobs);
    pnlJobs.setLayout(null);

    lblTargetRewindLength = new JLabel("Rewind Output:");
    lblTargetRewindLength.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblTargetRewindLength.setToolTipText("Quantity of rewind output");
    lblTargetRewindLength.setEnabled(false);
    lblTargetRewindLength.setHorizontalAlignment(SwingConstants.RIGHT);
    lblTargetRewindLength.setBounds(17, 197, 88, 14);
    pnlJobs.add(lblTargetRewindLength);

    lblSlitWidth = new JLabel("Slit Width:");
    lblSlitWidth.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblSlitWidth.setToolTipText("Width of each output reel");
    lblSlitWidth.setEnabled(false);
    lblSlitWidth.setHorizontalAlignment(SwingConstants.RIGHT);
    lblSlitWidth.setBounds(46, 60, 59, 14);
    pnlJobs.add(lblSlitWidth);

    lblSlitCount = new JLabel("Reel Count:");
    lblSlitCount.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblSlitCount.setToolTipText("Number of reels per set at the output");
    lblSlitCount.setEnabled(false);
    lblSlitCount.setHorizontalAlignment(SwingConstants.RIGHT);
    lblSlitCount.setBounds(46, 33, 59, 14);
    pnlJobs.add(lblSlitCount);

    lblTrimtotal = new JLabel("Trim (total):");
    lblTrimtotal.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblTrimtotal.setToolTipText("The trim resulting from the given slit widths");
    lblTrimtotal.setEnabled(false);
    lblTrimtotal.setHorizontalAlignment(SwingConstants.RIGHT);
    lblTrimtotal.setBounds(20, 114, 85, 14);
    pnlJobs.add(lblTrimtotal);

    txtSlits = new JTextField();
    txtSlits.setToolTipText("Number of reels per set at the output");
    txtSlits.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtSlits.selectAll();
        }
    });
    txtSlits.getDocument().addDocumentListener(new JobInputChangeListener());
    txtSlits.setEnabled(false);

    txtSlits.setText("1");
    txtSlits.setBounds(109, 30, 86, 20);
    pnlJobs.add(txtSlits);
    txtSlits.setColumns(10);

    txtSlitWidth = new JTextField();
    txtSlitWidth.setToolTipText("Width of each output reel");
    txtSlitWidth.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtSlitWidth.selectAll();
        }
    });
    txtSlitWidth.getDocument().addDocumentListener(new JobInputChangeListener());
    txtSlitWidth.setEnabled(false);

    txtSlitWidth.setText("1350");
    txtSlitWidth.setBounds(109, 58, 86, 20);
    pnlJobs.add(txtSlitWidth);
    txtSlitWidth.setColumns(10);

    txtRewindAmount = new JTextField();
    txtRewindAmount.setToolTipText("Quantity of rewind output");
    txtRewindAmount.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtRewindAmount.selectAll();
        }
    });
    txtRewindAmount.getDocument().addDocumentListener(new JobInputChangeListener());
    txtRewindAmount.setEnabled(false);
    txtRewindAmount.setName("RewindLength");

    txtRewindAmount.setText("1000");
    txtRewindAmount.setBounds(109, 194, 86, 20);
    pnlJobs.add(txtRewindAmount);
    txtRewindAmount.setColumns(10);

    lblTrim = new JLabel("0 mm");
    lblTrim.setToolTipText("The trim resulting from the given slit widths");
    lblTrim.setEnabled(false);
    lblTrim.setBounds(111, 114, 65, 14);
    pnlJobs.add(lblTrim);

    cmbRewindCore = new JComboBox();
    cmbRewindCore.setToolTipText("Core diameter of rewind reels");
    ((JTextField) cmbRewindCore.getEditor().getEditorComponent()).getDocument()
            .addDocumentListener(new DocumentListener() {
                @Override
                public void removeUpdate(DocumentEvent arg0) {
                    UpdateJob();
                }

                @Override
                public void insertUpdate(DocumentEvent arg0) {
                    UpdateJob();
                }

                @Override
                public void changedUpdate(DocumentEvent arg0) {
                }
            });
    /*cmbRewindCore.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent e) {
    UpdateJob(jobIndex);
       }
    });*/
    cmbRewindCore.setEnabled(false);

    cmbRewindCore.setModel(new DefaultComboBoxModel(Consts.REWIND_CORE_MM));
    cmbRewindCore.setSelectedIndex(1);
    cmbRewindCore.setBounds(109, 137, 87, 20);
    pnlJobs.add(cmbRewindCore);
    cmbRewindCore.setEditable(true);

    lblRewindCoremm = new JLabel("Rewind Core:");
    lblRewindCoremm.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblRewindCoremm.setToolTipText("Core diameter of rewind reels");
    lblRewindCoremm.setEnabled(false);
    lblRewindCoremm.setBounds(40, 140, 65, 14);
    pnlJobs.add(lblRewindCoremm);

    lblPer_1 = new JLabel("per:");
    lblPer_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPer_1.setToolTipText("Set whether rewind output is measured per reel or per set");
    lblPer_1.setEnabled(false);
    lblPer_1.setBounds(85, 248, 20, 14);
    pnlJobs.add(lblPer_1);

    cmbJobDomain = new JComboBox();
    cmbJobDomain.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateSetReel();
            //UpdateJob();
        }
    });
    cmbJobDomain.setEnabled(false);
    cmbJobDomain.setToolTipText("Set whether rewind output is measured per reel or per set");
    cmbJobDomain.setModel(new DefaultComboBoxModel(new String[] { "Reel", "Set" }));
    cmbJobDomain.setBounds(109, 246, 95, 20);
    pnlJobs.add(cmbJobDomain);

    lblmm3 = new JLabel("(mm)");
    lblmm3.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblmm3.setEnabled(false);
    lblmm3.setBounds(205, 61, 27, 14);
    pnlJobs.add(lblmm3);

    lblmm2 = new JLabel("(mm)");
    lblmm2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblmm2.setEnabled(false);
    lblmm2.setBounds(206, 140, 27, 14);
    pnlJobs.add(lblmm2);

    pnlUnwinds = new JPanel();
    pnlUnwinds.setLayout(null);
    pnlUnwinds.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Unwind Settings",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlUnwinds.setBounds(280, 207, 227, 162);
    pnlJob.add(pnlUnwinds);

    lblUnwindLength = new JLabel("Unwind Size:");
    lblUnwindLength.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblUnwindLength.setToolTipText("Quantity of material per mother roll");
    lblUnwindLength.setEnabled(false);
    lblUnwindLength.setHorizontalAlignment(SwingConstants.RIGHT);
    lblUnwindLength.setBounds(21, 104, 66, 14);
    pnlUnwinds.add(lblUnwindLength);

    txtUnwindAmount = new JTextField();
    txtUnwindAmount.setToolTipText("Quantity of material per mother roll");
    txtUnwindAmount.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            txtUnwindAmount.selectAll();
        }
    });
    txtUnwindAmount.getDocument().addDocumentListener(new JobInputChangeListener());
    txtUnwindAmount.setEnabled(false);
    txtUnwindAmount.setName("UnwindLength");
    txtUnwindAmount.setText("10000");
    txtUnwindAmount.setBounds(92, 100, 86, 20);
    pnlUnwinds.add(txtUnwindAmount);
    txtUnwindAmount.setColumns(10);

    lblWebWidthmm = new JLabel("Web Width:");
    lblWebWidthmm.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblWebWidthmm.setToolTipText("Width of mother rolls");
    lblWebWidthmm.setEnabled(false);
    lblWebWidthmm.setBounds(31, 29, 57, 14);
    pnlUnwinds.add(lblWebWidthmm);

    lblUnwindCoremm = new JLabel("Unwind Core:");
    lblUnwindCoremm.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblUnwindCoremm.setToolTipText("Core diameter of mother rolls");
    lblUnwindCoremm.setEnabled(false);
    lblUnwindCoremm.setBounds(22, 54, 66, 14);
    pnlUnwinds.add(lblUnwindCoremm);

    cmbUnwindCore = new JComboBox();
    cmbUnwindCore.setToolTipText("Core diameter of mother rolls");
    ((JTextField) cmbUnwindCore.getEditor().getEditorComponent()).getDocument()
            .addDocumentListener(new DocumentListener() {
                @Override
                public void removeUpdate(DocumentEvent arg0) {
                    UpdateJob();
                }

                @Override
                public void insertUpdate(DocumentEvent arg0) {
                    UpdateJob();
                }

                @Override
                public void changedUpdate(DocumentEvent arg0) {
                }
            });
    cmbUnwindCore.setEnabled(false);

    cmbUnwindCore.setModel(new DefaultComboBoxModel(new String[] { "76", "152", "254" }));
    cmbUnwindCore.setBounds(92, 51, 86, 20);
    pnlUnwinds.add(cmbUnwindCore);
    cmbUnwindCore.setEditable(true);

    lblmm0 = new JLabel("(mm)");
    lblmm0.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblmm0.setEnabled(false);
    lblmm0.setBounds(189, 29, 32, 14);
    pnlUnwinds.add(lblmm0);

    lblmm1 = new JLabel("(mm)");
    lblmm1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblmm1.setEnabled(false);
    lblmm1.setBounds(189, 53, 32, 14);
    pnlUnwinds.add(lblmm1);

    pnlEnviron = new JPanel();
    tabbedPane.addTab("Job Scheduling", null, pnlEnviron, "Edit the schedule of jobs to be analysed");
    tabbedPane.setEnabledAt(2, true);
    pnlEnviron.setLayout(null);

    JPanel pnlShifts = new JPanel();
    pnlShifts.setLayout(null);
    pnlShifts.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Shift Options",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlShifts.setBounds(20, 72, 287, 162);
    pnlEnviron.add(pnlShifts);

    JLabel lblShiftLength = new JLabel("Shift Length:");
    lblShiftLength.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblShiftLength.setToolTipText("Hours per working shift");
    lblShiftLength.setHorizontalAlignment(SwingConstants.RIGHT);
    lblShiftLength.setBounds(15, 28, 108, 14);
    pnlShifts.add(lblShiftLength);

    JLabel lblDayLength = new JLabel("Day Length:");
    lblDayLength.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblDayLength.setToolTipText("Working hours per day");
    lblDayLength.setHorizontalAlignment(SwingConstants.RIGHT);
    lblDayLength.setBounds(29, 78, 94, 14);
    pnlShifts.add(lblDayLength);

    JLabel lblShiftsDay = new JLabel("Shifts per Day:");
    lblShiftsDay.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblShiftsDay.setToolTipText("Shifts per day");
    lblShiftsDay.setHorizontalAlignment(SwingConstants.RIGHT);
    lblShiftsDay.setBounds(15, 53, 108, 14);
    pnlShifts.add(lblShiftsDay);

    JLabel lblDays = new JLabel("Days per Year:");
    lblDays.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblDays.setToolTipText("Days per year");
    lblDays.setHorizontalAlignment(SwingConstants.RIGHT);
    lblDays.setBounds(0, 106, 123, 14);
    pnlShifts.add(lblDays);

    txtShiftLength = new JTextField();
    txtShiftLength.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateShifts();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateShifts();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }
    });
    txtShiftLength.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            txtShiftLength.selectAll();
        }
    });
    txtShiftLength.setToolTipText("Hours per working shift");

    txtShiftLength.setText("8");
    txtShiftLength.setBounds(133, 25, 86, 20);
    pnlShifts.add(txtShiftLength);
    txtShiftLength.setColumns(10);

    txtShiftCount = new JTextField();
    txtShiftCount.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateShifts();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateShifts();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }
    });
    txtShiftCount.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtShiftCount.selectAll();
        }
    });
    txtShiftCount.setToolTipText("Shifts per day");

    txtShiftCount.setText("3");
    txtShiftCount.setBounds(133, 50, 86, 20);
    pnlShifts.add(txtShiftCount);
    txtShiftCount.setColumns(10);

    txtDaysYear = new JTextField();
    txtDaysYear.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateShifts();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateShifts();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }
    });
    txtDaysYear.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtDaysYear.selectAll();
        }
    });
    txtDaysYear.setToolTipText("Days per year");

    txtDaysYear.setText("250");
    txtDaysYear.setBounds(133, 103, 86, 20);
    pnlShifts.add(txtDaysYear);
    txtDaysYear.setColumns(10);

    lblDayLength2 = new JLabel("24 hours");
    lblDayLength2.setToolTipText("Working hours per day");
    lblDayLength2.setBounds(133, 78, 86, 14);
    pnlShifts.add(lblDayLength2);

    lblHoursYear = new JLabel("Hours per Year:");
    lblHoursYear.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblHoursYear.setToolTipText("Working hours per year");
    lblHoursYear.setBounds(47, 131, 76, 14);
    pnlShifts.add(lblHoursYear);

    lblHoursYear2 = new JLabel("6000 hours");
    lblHoursYear2.setToolTipText("Working hours per year");
    lblHoursYear2.setBounds(133, 131, 86, 14);
    pnlShifts.add(lblHoursYear2);

    lblHrs = new JLabel("hrs");
    lblHrs.setBounds(229, 28, 46, 14);
    pnlShifts.add(lblHrs);

    btnAddAll = new JButton("Add All");
    btnAddAll.setToolTipText("Add all jobs to the schedule in order");
    btnAddAll.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnAddAll.setEnabled(false);
    try {
        btnAddAll.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/plus.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnAddAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < jobModel.getSize(); ++i) {
                listJobsAvail.setSelectedIndex(i);
                btnAddJob.doClick();
            }
        }
    });
    btnAddAll.setBounds(327, 460, 110, 36);
    pnlEnviron.add(btnAddAll);

    btnAddJob = new JButton("");
    btnAddJob.setToolTipText("Add this job to the schedule");
    btnAddJob.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //AddToSchedule(listJobsAvail.getSelectedValue());

            ResetStatusLabel();

            int index = listSchedule.getSelectedIndex();
            //int source_index = listJobsAvail.getSelectedIndex();
            Job sel = (Job) listJobsAvail.getSelectedValue();
            JobItem j = environment.getSchedule().new JobItem(sel, 0, sel.getTotWeight(), sel.getTotLength());
            int size = scheduleModel.getSize();

            // no limit now there are scroll bars
            /* if(size >= Consts.JOB_LIST_LIMIT){    // Max list size
              ShowMessage("Maximum number of jobs scheduled. Please delete before attempting to add more.");
              return;
            }*/

            //If no selection or if item in last position is selected,
            //add the new one to end of list, and select new one.
            if (index == -1 || (index + 1 == size)) {

                scheduleModel.addElement(sel);
                listSchedule.setSelectedIndex(size);
                environment.getSchedule().addJob(j);

                //Otherwise insert the new one after the current selection,
                //and select new one.
            } else {
                scheduleModel.insertElementAt(sel, index + 1);
                listSchedule.setSelectedIndex(index + 1);
                environment.getSchedule().insertJob(j, index + 1);
            }

            btnClearSchedule.setEnabled(true);
        }
    });
    btnAddJob.setEnabled(false);
    try {
        btnAddJob.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/add_job.png"))));
        btnAddJob.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/add_job_dis.png"))));
        btnAddJob.setRolloverEnabled(true);
        btnAddJob.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/add_job_over.png"))));
    } catch (NullPointerException e111) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnAddJob.setBounds(521, 178, 54, 54);
    pnlEnviron.add(btnAddJob);

    btnRemoveJob = new JButton("");
    btnRemoveJob.setToolTipText("Remove job from schedule");
    btnRemoveJob.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ResetStatusLabel();

            // Uncomment this code to allow jobs to be saved back after removal from schedule
            /*if(listSchedule.getSelectedIndex() > -1){
               Job j = (Job) listSchedule.getSelectedValue();
               String name = j.getName().toLowerCase();
               if(!jobNames.contains(name) && !jobModel.contains(j)){
                  if(jobModel.size() < Consts.JOB_LIST_LIMIT){
             jobNames.add(name);
             jobFormReady = true;
             int index = -1;
             if(listJobsAvail.getSelectedIndex() > -1)
                index = listJobsAvail.getSelectedIndex();
             if(index < 0){
                jobModel.addElement(j);
                listJobsAvail.setSelectedIndex(jobModel.size()-1);
                listJobs.setSelectedIndex(jobModel.size()-1);
             }else{
                jobModel.insertElementAt(j, index+1);
                listJobsAvail.setSelectedIndex(index+1);
                listJobs.setSelectedIndex(index+1);
             }
                  }
               }
            }*/

            ListSelectionModel lsm = listSchedule.getSelectionModel();
            int firstSelected = lsm.getMinSelectionIndex();
            int lastSelected = lsm.getMaxSelectionIndex();
            scheduleModel.removeRange(firstSelected, lastSelected);
            environment.getSchedule().remove(firstSelected);

            int size = scheduleModel.size();

            if (size == 0) {
                //List is empty: disable delete, up, and down buttons.
                btnClearSchedule.setEnabled(false);
                btnUpSchedule.setEnabled(false);
                btnDownSchedule.setEnabled(false);
                listSchedule.clearSelection();
                btnRemoveJob.setEnabled(false);
                btnViewSchedule.setEnabled(false);
            } else {
                //Adjust the selection.
                if (firstSelected == scheduleModel.getSize()) {
                    //Removed item in last position.
                    firstSelected--;
                }
                listSchedule.setSelectedIndex(firstSelected);

                if (size == 21) { // No longer full list
                    ResetStatusLabel();
                }

            }
        }
    });
    btnRemoveJob.setEnabled(false);
    try {
        btnRemoveJob
                .setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/del_job.png"))));
        btnRemoveJob.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/del_job_dis.png"))));
        btnRemoveJob.setRolloverEnabled(true);
        btnRemoveJob.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/del_job_over.png"))));
    } catch (NullPointerException e111) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnRemoveJob.setBounds(520, 243, 54, 54);
    pnlEnviron.add(btnRemoveJob);

    lblJobSchedule_1 = new JLabel("Job Schedule");
    lblJobSchedule_1.setFont(new Font("Tahoma", Font.BOLD, 18));
    lblJobSchedule_1.setBounds(29, 18, 269, 22);
    pnlEnviron.add(lblJobSchedule_1);

    lblScheduleJobsTo = new JLabel("Schedule jobs to the right, then set shift options below");
    lblScheduleJobsTo.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblScheduleJobsTo.setBounds(29, 45, 279, 14);
    pnlEnviron.add(lblScheduleJobsTo);

    lblAvailableJobs_1 = new JLabel("Available Jobs");
    lblAvailableJobs_1.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblAvailableJobs_1.setBounds(327, 19, 137, 14);
    pnlEnviron.add(lblAvailableJobs_1);

    lblJobSchedule_2 = new JLabel("Job Schedule");
    lblJobSchedule_2.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblJobSchedule_2.setBounds(577, 19, 110, 14);
    pnlEnviron.add(lblJobSchedule_2);

    panel = new JPanel();
    panel.setLayout(null);
    panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Schedule Options",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel.setBounds(20, 245, 287, 104);
    pnlEnviron.add(panel);

    btnViewSchedule = new JButton("View Schedule Diagram");
    btnViewSchedule.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnViewSchedule.setToolTipText("View chart of schedule timings");
    btnViewSchedule.setEnabled(false);
    btnViewSchedule.setBounds(33, 27, 170, 29);
    panel.add(btnViewSchedule);

    chckbxSimulateScheduleStart = new JCheckBox("Ignore machine config & knife positioning times");
    chckbxSimulateScheduleStart.setFont(new Font("Tahoma", Font.PLAIN, 11));
    chckbxSimulateScheduleStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (!initialising)
                environment.StartStopTimes = !chckbxSimulateScheduleStart.isSelected();
        }
    });
    chckbxSimulateScheduleStart.setToolTipText(
            "WARNING:  Use ONLY when you wish to model the output of a single job over a long time period \u2013 such that the initial set-up time has no material impact on the production volume");
    chckbxSimulateScheduleStart.setBounds(30, 62, 251, 18);
    panel.add(chckbxSimulateScheduleStart);

    lblhoverForInfo = new JLabel("(hover for info)");
    lblhoverForInfo.setToolTipText(
            "WARNING:  Use ONLY when you wish to model the output of a single job over a long time period \u2013 such that the initial set-up time has no material impact on the production volume");
    lblhoverForInfo.setForeground(Color.GRAY);
    lblhoverForInfo.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblhoverForInfo.setBounds(34, 80, 147, 14);
    panel.add(lblhoverForInfo);

    btnUpSchedule = new JButton("");
    btnUpSchedule.setToolTipText("Move job earlier in schedule");
    btnUpSchedule.addActionListener(new ScheduleUpListener());
    try {
        btnUpSchedule.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up.png"))));
        btnUpSchedule.setRolloverEnabled(true);
        btnUpSchedule.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up_over.png"))));
        btnUpSchedule.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnUpSchedule.setEnabled(false);
    btnUpSchedule.setBounds(700, 463, 30, 30);
    pnlEnviron.add(btnUpSchedule);

    btnDownSchedule = new JButton("");
    btnDownSchedule.setToolTipText("Move job later in schedule");
    btnDownSchedule.addActionListener(new ScheduleDownListener());
    try {
        btnDownSchedule
                .setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down.png"))));
        btnDownSchedule.setRolloverEnabled(true);
        btnDownSchedule.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down_over.png"))));
        btnDownSchedule.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnDownSchedule.setEnabled(false);
    btnDownSchedule.setBounds(737, 463, 30, 30);
    pnlEnviron.add(btnDownSchedule);

    btnClearSchedule = new JButton("Clear");
    btnClearSchedule.setToolTipText("Clear all jobs from the schedule");
    btnClearSchedule.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnClearSchedule.setEnabled(false);
    try {
        btnClearSchedule
                .setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete.png"))));
        btnClearSchedule.setRolloverEnabled(true);
        btnClearSchedule.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete_over.png"))));
        btnClearSchedule.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnClearSchedule.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scheduleModel.removeAllElements();
            environment.getSchedule().empty();
        }
    });
    btnClearSchedule.setBounds(577, 460, 110, 36);
    pnlEnviron.add(btnClearSchedule);
    //listSchedule.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
    //listSchedule.setBounds(577, 44, 190, 405);
    //pnlEnviron.add(listSchedule);
    btnViewSchedule.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ScheduleChart ch = new ScheduleChart(environment.getSchedule());
            ch.pack();
            try {
                ch.setIconImage(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/logo.png")));
            } catch (NullPointerException e11) {
                System.out.println("Image load error");
            } catch (IOException e) {
                e.printStackTrace();
            }
            ch.setLocationRelativeTo(frmTitanRoiCalculator);
            ch.setVisible(true);
        }
    });

    scrlSchedule = new JScrollPane();
    scrlSchedule.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrlSchedule.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    scrlSchedule.setBounds(577, 44, 190, 405);
    scrlSchedule.getVerticalScrollBar().setUnitIncrement(16);
    pnlEnviron.add(scrlSchedule);

    panel_8 = new JPanel();
    panel_8.setToolTipText("Select job to re-order or remove from schedule");
    panel_8.setBackground(Color.WHITE);
    panel_8.setBorder(null);
    scrlSchedule.setViewportView(panel_8);
    panel_8.setLayout(new BorderLayout(0, 0));

    listSchedule = new JList(scheduleModel);
    panel_8.add(listSchedule, BorderLayout.NORTH);
    listSchedule.setToolTipText("Select job to re-order or remove from schedule");
    listSchedule.addListSelectionListener(new ScheduleSelectionListener());
    listSchedule.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    listSchedule.setCellRenderer(new JobListRenderer());

    panel_5 = new JPanel();
    panel_5.setLayout(null);
    panel_5.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Notes",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel_5.setBounds(20, 360, 287, 136);
    pnlEnviron.add(panel_5);

    lblToViewAnalysis = new JLabel("To view analysis for 1 job only, add just that job");
    lblToViewAnalysis.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblToViewAnalysis.setBounds(24, 24, 241, 14);
    panel_5.add(lblToViewAnalysis);

    lblToTheSchedule = new JLabel("to the schedule.");
    lblToTheSchedule.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblToTheSchedule.setBounds(24, 38, 241, 14);
    panel_5.add(lblToTheSchedule);

    lblToModelMaintenance = new JLabel("To model maintenance or other downtime, edit the");
    lblToModelMaintenance.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblToModelMaintenance.setBounds(24, 59, 253, 14);
    panel_5.add(lblToModelMaintenance);

    lblShiftOptionsAbove = new JLabel("shift options above. This will affect annual output,");
    lblShiftOptionsAbove.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblShiftOptionsAbove.setBounds(24, 73, 253, 14);
    panel_5.add(lblShiftOptionsAbove);

    lblButNotThe = new JLabel("but not the rates or efficiencies. For these, use the");
    lblButNotThe.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblButNotThe.setBounds(24, 87, 253, 14);
    panel_5.add(lblButNotThe);

    lbladvancedTabIn = new JLabel("'advanced' tab in the options menu box.");
    lbladvancedTabIn.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lbladvancedTabIn.setBounds(24, 101, 253, 14);
    panel_5.add(lbladvancedTabIn);

    scrollPane_2 = new JScrollPane();
    scrollPane_2.setBorder(null);
    scrollPane_2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane_2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane_2.setBounds(327, 44, 190, 405);
    pnlEnviron.add(scrollPane_2);

    panel_9 = new JPanel();
    panel_9.setToolTipText("Select job to be added");
    scrollPane_2.setViewportView(panel_9);
    panel_9.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    panel_9.setBackground(Color.WHITE);
    panel_9.setLayout(new BorderLayout(0, 0));

    listJobsAvail = new JList(jobModel);
    panel_9.add(listJobsAvail, BorderLayout.NORTH);
    listJobsAvail.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "add");
    listJobsAvail.getActionMap().put("add", new AddScheduleBtn());
    listJobsAvail.setToolTipText("Select job to be added");
    listJobsAvail.addListSelectionListener(new JobAvailSelectionListener());
    listJobsAvail.setCellRenderer(new JobListRenderer());
    listJobsAvail.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    listJobsAvail.setBorder(null);

    pnlCompare = new JPanel();
    tabbedPane.addTab("Productivity Comparison", null, pnlCompare, "Productivity comparison data & graphs");
    tabbedPane.setEnabledAt(3, true);
    pnlCompare.setLayout(null);

    pnlResults = new JPanel();
    pnlResults.setBorder(
            new TitledBorder(null, "Numerical Results", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlResults.setBounds(20, 72, 479, 134);
    pnlCompare.add(pnlResults);
    pnlResults.setLayout(null);

    lblOutputLength = new JLabel("Output length over time period:");
    lblOutputLength.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblOutputLength.setEnabled(false);
    lblOutputLength.setToolTipText("Quantity produced");
    lblOutputLength.setBounds(220, 54, 152, 14);
    pnlResults.add(lblOutputLength);

    lblOutputWeight = new JLabel("Output weight over time period:");
    lblOutputWeight.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblOutputWeight.setEnabled(false);
    lblOutputWeight.setToolTipText("Quantity produced");
    lblOutputWeight.setBounds(220, 79, 162, 14);
    pnlResults.add(lblOutputWeight);

    cmbTimeRef = new JComboBox();
    cmbTimeRef.setEnabled(false);
    cmbTimeRef.setToolTipText("Select a time range to display results over");
    cmbTimeRef.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // Refresh analyses
            UpdateNumericalAnalysis();
        }
    });
    cmbTimeRef.setModel(
            new DefaultComboBoxModel(new String[] { "Schedule", "Year", "Hour", "Shift", "Day"/*, "Week"*/ }));
    cmbTimeRef.setBounds(247, 98, 125, 24);
    pnlResults.add(cmbTimeRef);

    lblPer = new JLabel("Per:");
    lblPer.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPer.setEnabled(false);
    lblPer.setBounds(220, 103, 20, 14);
    pnlResults.add(lblPer);

    lblAverageMmin = new JLabel("Average rate:");
    lblAverageMmin.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblAverageMmin.setEnabled(false);
    lblAverageMmin.setToolTipText("Average quantity processed");
    lblAverageMmin.setBounds(20, 54, 95, 14);
    pnlResults.add(lblAverageMmin);

    lblNumericsWeight = new JLabel("0.0 tons");
    lblNumericsWeight.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblNumericsWeight.setEnabled(false);
    lblNumericsWeight.setToolTipText("Quantity produced");
    lblNumericsWeight.setBounds(380, 79, 89, 14);
    pnlResults.add(lblNumericsWeight);

    lblNumericsLength = new JLabel("0.0 metres");
    lblNumericsLength.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblNumericsLength.setEnabled(false);
    lblNumericsLength.setToolTipText("Quantity produced");
    lblNumericsLength.setBounds(380, 54, 89, 14);
    pnlResults.add(lblNumericsLength);

    lblNumericsRate = new JLabel("0.0 m/hr");
    lblNumericsRate.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblNumericsRate.setEnabled(false);
    lblNumericsRate.setToolTipText("Average quantity processed");
    lblNumericsRate.setBounds(128, 54, 82, 14);
    pnlResults.add(lblNumericsRate);

    lblEfficiency = new JLabel("Machine running:");
    lblEfficiency.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblEfficiency.setEnabled(false);
    lblEfficiency.setToolTipText("Proportion of total time for which the machine is running");
    lblEfficiency.setBounds(20, 104, 95, 14);
    pnlResults.add(lblEfficiency);

    cmbMachines = new JComboBox();
    cmbMachines.setMaximumRowCount(15);
    cmbMachines.setFont(new Font("Tahoma", Font.BOLD, 11));
    cmbMachines.setEnabled(false);
    cmbMachines.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateNumericalAnalysis();
        }
    });
    cmbMachines.setToolTipText("Select machine");
    cmbMachines.setBounds(128, 20, 244, 24);
    pnlResults.add(cmbMachines);

    lblMachine = new JLabel("Select Machine:");
    lblMachine.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblMachine.setEnabled(false);
    lblMachine.setToolTipText("Select machine");
    lblMachine.setBounds(20, 25, 77, 14);
    pnlResults.add(lblMachine);

    lblNumericsEff = new JLabel("0.0 %");
    lblNumericsEff.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblNumericsEff.setEnabled(false);
    lblNumericsEff.setToolTipText("Machine efficiency");
    lblNumericsEff.setBounds(128, 104, 65, 14);
    pnlResults.add(lblNumericsEff);

    lblscheduletimelbl = new JLabel("Time to run schedule:");
    lblscheduletimelbl.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblscheduletimelbl.setToolTipText("Time to run schedule");
    lblscheduletimelbl.setEnabled(false);
    lblscheduletimelbl.setBounds(20, 79, 103, 14);
    pnlResults.add(lblscheduletimelbl);

    lblscheduletime = new JLabel("0.0 hr");
    lblscheduletime.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblscheduletime.setToolTipText("Time to run schedule");
    lblscheduletime.setEnabled(false);
    lblscheduletime.setBounds(128, 79, 77, 14);
    pnlResults.add(lblscheduletime);

    pnlROI = new JPanel();
    tabbedPane.addTab("Return on Investment", (Icon) null, pnlROI,
            "Return on investment comparison and analysis");
    pnlROI.setLayout(null);
    tabbedPane.setEnabledAt(4, true);

    lblProductivityComparison = new JLabel("Productivity Comparison");
    lblProductivityComparison.setFont(new Font("Tahoma", Font.BOLD, 18));
    lblProductivityComparison.setBounds(29, 18, 269, 22);
    pnlCompare.add(lblProductivityComparison);

    lblSelectMultipleMachines = new JLabel(
            "Select multiple machines from the list on the right, then compare them below");
    lblSelectMultipleMachines.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblSelectMultipleMachines.setBounds(29, 45, 433, 14);
    pnlCompare.add(lblSelectMultipleMachines);

    label_2 = new JLabel("Machines");
    label_2.setFont(new Font("Tahoma", Font.BOLD, 12));
    label_2.setBounds(522, 19, 85, 14);
    pnlCompare.add(label_2);

    pnlProdGraph = new JPanel();
    pnlProdGraph.setBounds(20, 222, 479, 274);
    pnlCompare.add(pnlProdGraph);
    pnlProdGraph.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Graphical Results",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    pnlProdGraph.setLayout(null);

    btnShowGraph = new JButton("Open Graph");
    btnShowGraph.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnShowGraph.setToolTipText("Open graph in new window");
    btnShowGraph.setEnabled(false);
    btnShowGraph.setBounds(366, 51, 99, 39);
    pnlProdGraph.add(btnShowGraph);

    btnSaveToFile = new JButton("Save to File");
    btnSaveToFile.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnSaveToFile.setToolTipText("Save image to disk");
    btnSaveToFile.setEnabled(false);
    btnSaveToFile.addActionListener(SaveActionListener);
    btnSaveToFile.setBounds(366, 97, 99, 24);
    pnlProdGraph.add(btnSaveToFile);

    pnlPreview = new JPanel();
    pnlPreview.setBackground(Color.WHITE);
    pnlPreview.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    pnlPreview.setBounds(21, 51, 335, 205);
    pnlProdGraph.add(pnlPreview);
    pnlPreview.setLayout(null);
    pnlGraph = new ChartPanel(chart);
    pnlGraph.setBounds(2, 2, 331, 201);
    //pnlGraph.setPreferredSize(new java.awt.Dimension(243, 171));
    pnlPreview.add(pnlGraph);
    try {
        picLabel = new JLabel(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/no_preview.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    picLabel.setBounds(2, 2, 331, 201);
    pnlPreview.add(picLabel);
    pnlGraph.setVisible(false);

    lblPreview = new JLabel("Graph Preview");
    lblPreview.setForeground(Color.DARK_GRAY);
    lblPreview.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblPreview.setEnabled(false);
    lblPreview.setBounds(21, 24, 99, 16);
    pnlProdGraph.add(lblPreview);

    lblType = new JLabel("Graph Type:");
    lblType.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblType.setEnabled(false);
    lblType.setToolTipText("Choose measurement type");
    lblType.setBounds(184, 26, 65, 14);
    pnlProdGraph.add(lblType);

    btnShowTimings = new JButton("Machine Runs");
    btnShowTimings.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnShowTimings.setToolTipText("Show timing diagram for a single machine run");
    btnShowTimings.setEnabled(false);
    btnShowTimings.addActionListener(new BtnShowTimingsActionListener());
    btnShowTimings.setBounds(366, 201, 99, 24);
    pnlProdGraph.add(btnShowTimings);

    btnDowntime = new JButton("Productivity");
    btnDowntime.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnDowntime.setToolTipText("View productivity breakdown charts for the selected machines");
    btnDowntime.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ShowTimingBreakdown();
        }
    });
    btnDowntime.setEnabled(false);
    btnDowntime.setBounds(366, 232, 99, 24);
    pnlProdGraph.add(btnDowntime);

    lblbreakdown1 = new JLabel("Show timing");
    lblbreakdown1.setEnabled(false);
    lblbreakdown1.setBounds(370, 166, 99, 14);
    pnlProdGraph.add(lblbreakdown1);

    lblbreakdown2 = new JLabel("breakdown for:");
    lblbreakdown2.setEnabled(false);
    lblbreakdown2.setBounds(370, 182, 99, 14);
    pnlProdGraph.add(lblbreakdown2);

    panel_3 = new JPanel();
    panel_3.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel_3.setBounds(522, 459, 245, 37);
    pnlCompare.add(panel_3);
    panel_3.setLayout(null);

    btnNone = new JButton("None");
    btnNone.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnNone.setEnabled(false);
    btnNone.setBounds(172, 7, 57, 23);
    panel_3.add(btnNone);
    btnNone.setToolTipText("Clear machine selection");

    btnAll = new JButton("All");
    btnAll.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnAll.setEnabled(false);
    btnAll.setBounds(105, 7, 57, 23);
    panel_3.add(btnAll);
    btnAll.setToolTipText("Select all machines");

    lblSelect = new JLabel("Select:");
    lblSelect.setEnabled(false);
    lblSelect.setBounds(37, 11, 46, 14);
    panel_3.add(lblSelect);

    scrollPane_3 = new JScrollPane();
    scrollPane_3.setBorder(null);
    scrollPane_3.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane_3.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane_3.setBounds(522, 44, 245, 405);
    pnlCompare.add(scrollPane_3);

    panel_10 = new JPanel();
    panel_10.setToolTipText(
            "Click a machine to select it. Select multiple machines to compare their performance under the chosen job schedule.");
    panel_10.setBackground(Color.WHITE);
    scrollPane_3.setViewportView(panel_10);
    panel_10.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    panel_10.setLayout(new BorderLayout(0, 0));

    listCompare = new JList(listModel);
    panel_10.add(listCompare, BorderLayout.NORTH);
    listCompare.setCellRenderer(new MachineListRenderer());
    listCompare.setToolTipText(
            "Click a machine to select it. Select multiple machines to compare their performance under the chosen job schedule.");
    listCompare.setBorder(null);
    listCompare.addListSelectionListener(new MultiSelectionListener());

    btnAll.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int[] count = new int[listModel.size()];
            for (int i = 0; i < listModel.size(); ++i)
                count[i] = i;
            listCompare.setSelectedIndices(count);
        }
    });
    btnNone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            listCompare.clearSelection();
        }
    });
    btnShowGraph.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            // TODO base on cmbGraphType: or not if just using chart

            /*PieChart test = new PieChart("title","this is a pie chart");
            test.pack();
            test.setVisible(true);
            test.setLocationRelativeTo(null);*/
            JFrame popGraph = new JFrame();

            JFreeChart chartBig = null;
            try {
                chartBig = (JFreeChart) chart.clone();
            } catch (CloneNotSupportedException e) {
                e.printStackTrace();
            }
            //chartBig.setTitle("Productivity Comparison");

            ChartPanel cpanel = new ChartPanel(chartBig);
            cpanel.setPreferredSize(new java.awt.Dimension(500, 300));
            popGraph.setContentPane(cpanel);
            try {
                popGraph.setIconImage(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/logo.png")));
            } catch (NullPointerException e11) {
                System.out.println("Image load error");
            } catch (IOException e) {
                e.printStackTrace();
            }
            popGraph.setTitle("Productivity Graph");
            popGraph.setSize(450, 300);

            popGraph.pack();
            popGraph.setVisible(true);
            popGraph.setLocationRelativeTo(frmTitanRoiCalculator);
        }
    });

    cmbGraphType = new JComboBox();
    cmbGraphType.setMaximumRowCount(10);
    cmbGraphType.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbGraphType.setEnabled(false);
    cmbGraphType.setToolTipText("Choose measurement type");
    cmbGraphType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // Refresh analyses
            UpdateGraph();
        }
    });
    cmbGraphType.setModel(new DefaultComboBoxModel(new String[] { "Schedule Time", "Length per Hour",
            "Weight per Hour", "Length per Year", "Weight per Year", "Run Percentage" }));
    cmbGraphType.setSelectedIndex(0);
    cmbGraphType.setBounds(251, 21, 105, 24);
    pnlProdGraph.add(cmbGraphType);

    lblReturnOnInvestment = new JLabel("Return on Investment");
    lblReturnOnInvestment.setFont(new Font("Tahoma", Font.BOLD, 18));
    lblReturnOnInvestment.setBounds(29, 18, 269, 22);
    pnlROI.add(lblReturnOnInvestment);

    lblSelectMultipleMachines_1 = new JLabel(
            "Select multiple machines from the list on the right, then compare them below");
    lblSelectMultipleMachines_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblSelectMultipleMachines_1.setBounds(29, 45, 433, 14);
    pnlROI.add(lblSelectMultipleMachines_1);

    lblCompareroiList = new JLabel("Machines");
    lblCompareroiList.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblCompareroiList.setBounds(522, 19, 85, 14);
    pnlROI.add(lblCompareroiList);

    panel_4 = new JPanel();
    panel_4.setLayout(null);
    panel_4.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel_4.setBounds(522, 459, 245, 37);
    pnlROI.add(panel_4);

    btnROIselectnone = new JButton("None");
    btnROIselectnone.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnROIselectnone.setEnabled(false);
    btnROIselectnone.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            listCompareRoi.clearSelection();
        }
    });
    btnROIselectnone.setToolTipText("Clear machine selection");
    btnROIselectnone.setBounds(172, 7, 57, 23);
    panel_4.add(btnROIselectnone);

    btnROIselectall = new JButton("All");
    btnROIselectall.setFont(new Font("Tahoma", Font.PLAIN, 11));
    btnROIselectall.setEnabled(false);
    btnROIselectall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int[] count = new int[listModel.size()];
            for (int i = 0; i < listModel.size(); ++i)
                count[i] = i;
            listCompareRoi.setSelectedIndices(count);
        }
    });
    btnROIselectall.setToolTipText("Select all machines");
    btnROIselectall.setBounds(105, 7, 57, 23);
    panel_4.add(btnROIselectall);

    lblROIselect = new JLabel("Select:");
    lblROIselect.setEnabled(false);
    lblROIselect.setBounds(37, 11, 46, 14);
    panel_4.add(lblROIselect);

    tabsROI = new JTabbedPane(JTabbedPane.TOP);
    tabsROI.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent arg0) {
            try {
                ResetStatusLabel();
            } catch (NullPointerException e) {
                // Form is still initialising
                return;
            }

            int tab = tabsROI.getSelectedIndex();
            switch (tab) {
            case 0:
                UpdateROIProd();
                break;
            case 1:
                UpdateROIEnergy();
                break;
            case 2:
                UpdateROIMaint();
                break;
            case 3:
                UpdateROIWaste();
                break;
            }
        }
    });
    tabsROI.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
    tabsROI.setBounds(29, 72, 470, 424);
    pnlROI.add(tabsROI);

    pnlProdROI = new JPanel();
    pnlProdROI.setBackground(Color.WHITE);
    tabsROI.addTab("Productivity", null, pnlProdROI, "ROI based on productivity");
    pnlProdROI.setLayout(null);

    lblThisToolIlllustrates = new JLabel(
            "This tool illlustrates the long-term financial benfits of particular machines and options in");
    lblThisToolIlllustrates.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblThisToolIlllustrates.setForeground(Color.GRAY);
    lblThisToolIlllustrates.setBounds(10, 11, 439, 14);
    pnlProdROI.add(lblThisToolIlllustrates);

    lblInTermsOf = new JLabel("terms of productivity gains.");
    lblInTermsOf.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblInTermsOf.setForeground(Color.GRAY);
    lblInTermsOf.setBounds(10, 27, 317, 14);
    pnlProdROI.add(lblInTermsOf);

    pnlGraphProd = new JPanel();
    pnlGraphProd.setBackground(Color.WHITE);
    pnlGraphProd.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    pnlGraphProd.setBounds(10, 100, 439, 230);
    pnlProdROI.add(pnlGraphProd);
    pnlGraphProd.setLayout(null);

    pnlGraphProdInner = new ChartPanel(null);
    pnlGraphProdInner.setBounds(2, 2, 435, 226);
    //pnlGraphProd.add(pnlGraphProdInner);

    try {
        lblNoGraph = new JLabel(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/no_preview.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    lblNoGraph.setBounds(2, 2, 435, 226);
    pnlGraphProd.add(lblNoGraph);

    lblSellingPrice = new JLabel("Selling price:");
    lblSellingPrice.setEnabled(false);
    lblSellingPrice.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblSellingPrice.setBounds(10, 52, 60, 14);
    pnlProdROI.add(lblSellingPrice);

    txtsellingprice = new JTextField();
    txtsellingprice.setToolTipText("Average selling price of the material per unit weight");
    txtsellingprice.setEnabled(false);
    txtsellingprice.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            txtsellingprice.selectAll();
        }
    });
    txtsellingprice.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateROIValue();
        }

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateROIValue();
        }

    });
    txtsellingprice.setFont(new Font("Tahoma", Font.PLAIN, 11));
    txtsellingprice.setBounds(90, 49, 65, 20);
    pnlProdROI.add(txtsellingprice);
    txtsellingprice.setColumns(10);

    lblPerTonne = new JLabel("per tonne");
    lblPerTonne.setEnabled(false);
    lblPerTonne.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPerTonne.setBounds(160, 52, 70, 14);
    pnlProdROI.add(lblPerTonne);

    lblContribution = new JLabel("Contribution:");
    lblContribution.setEnabled(false);
    lblContribution.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblContribution.setBounds(10, 75, 70, 14);
    pnlProdROI.add(lblContribution);

    txtcontribution = new JTextField();
    txtcontribution.setToolTipText("Contribution percentage");
    txtcontribution.setEnabled(false);
    txtcontribution.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtcontribution.selectAll();
        }
    });
    txtcontribution.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent e) {
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateROIValue();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateROIValue();
        }
    });
    txtcontribution.setFont(new Font("Tahoma", Font.PLAIN, 11));
    txtcontribution.setBounds(90, 73, 65, 20);
    pnlProdROI.add(txtcontribution);
    txtcontribution.setColumns(10);

    lblpercent = new JLabel("%");
    lblpercent.setEnabled(false);
    lblpercent.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblpercent.setBounds(160, 76, 11, 14);
    pnlProdROI.add(lblpercent);

    lblValueAddedlbl = new JLabel("Value added:");
    lblValueAddedlbl.setEnabled(false);
    lblValueAddedlbl.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblValueAddedlbl.setBounds(279, 52, 70, 14);
    pnlProdROI.add(lblValueAddedlbl);

    lblvalueadded = new JLabel("\u00A30.00 / tonne");
    lblvalueadded.setToolTipText("Value added per unit weight");
    lblvalueadded.setEnabled(false);
    lblvalueadded.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblvalueadded.setBounds(279, 71, 170, 20);
    pnlProdROI.add(lblvalueadded);

    cmbMarg1 = new JComboBox();
    cmbMarg1.setToolTipText("Old machine");
    cmbMarg1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateROIProd();
        }
    });
    cmbMarg1.setEnabled(false);
    cmbMarg1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMarg1.setBounds(10, 359, 111, 20);
    pnlProdROI.add(cmbMarg1);

    cmbMarg2 = new JComboBox();
    cmbMarg2.setToolTipText("New machine");
    cmbMarg2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateROIProd();
        }
    });
    cmbMarg2.setEnabled(false);
    cmbMarg2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMarg2.setBounds(141, 359, 111, 20);
    pnlProdROI.add(cmbMarg2);

    lblMarginalImprovement = new JLabel("\u00A30.00 per annum");
    lblMarginalImprovement.setToolTipText("Marginal improvement");
    lblMarginalImprovement.setEnabled(false);
    lblMarginalImprovement.setFont(new Font("Tahoma", Font.BOLD, 13));
    lblMarginalImprovement.setBounds(279, 358, 170, 20);
    pnlProdROI.add(lblMarginalImprovement);

    lblSelectMachines = new JLabel("Select 2 machines to view the marginal improvement between them:");
    lblSelectMachines.setForeground(Color.GRAY);
    lblSelectMachines.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblSelectMachines.setBounds(10, 338, 412, 14);
    pnlProdROI.add(lblSelectMachines);

    lblpound1 = new JLabel("\u00A3");
    lblpound1.setEnabled(false);
    lblpound1.setBounds(80, 52, 11, 14);
    pnlProdROI.add(lblpound1);

    lblTo = new JLabel("to");
    lblTo.setForeground(Color.GRAY);
    lblTo.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblTo.setBounds(125, 362, 16, 14);
    pnlProdROI.add(lblTo);

    label = new JLabel("=");
    label.setForeground(Color.GRAY);
    label.setFont(new Font("Tahoma", Font.BOLD, 13));
    label.setBounds(259, 362, 11, 14);
    pnlProdROI.add(label);

    pnlEnergy = new JPanel();
    pnlEnergy.setBackground(Color.WHITE);
    tabsROI.addTab("Energy Efficiency", null, pnlEnergy, "ROI based on machine power usage");
    pnlEnergy.setLayout(null);

    lblThisToolHighlights = new JLabel(
            "This tool highlights power consumption differences between machines, and the resulting");
    lblThisToolHighlights.setForeground(Color.GRAY);
    lblThisToolHighlights.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblThisToolHighlights.setBounds(10, 11, 439, 14);
    pnlEnergy.add(lblThisToolHighlights);

    lblImpactOnFinancial = new JLabel("impact on financial returns.");
    lblImpactOnFinancial.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblImpactOnFinancial.setForeground(Color.GRAY);
    lblImpactOnFinancial.setBounds(10, 27, 439, 14);
    pnlEnergy.add(lblImpactOnFinancial);

    rdbtnAveragePower = new JRadioButton("Average power");
    rdbtnAveragePower.setToolTipText("Select \"average power\" input type");
    rdbtnAveragePower.setFont(new Font("Tahoma", Font.PLAIN, 11));
    rdbtnAveragePower.setEnabled(false);
    rdbtnAveragePower.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            ClearPowerTxts();
            txtaveragepower.setEnabled(true);
            txthourlyusage.setEnabled(false);
            txtannualusage.setEnabled(false);
            lblKw.setEnabled(true);
            lblKwh.setEnabled(false);
            lblKwh_1.setEnabled(false);
            txtaveragepower.requestFocusInWindow();
            UpdateEnergyData();
        }
    });
    rdbtnAveragePower.setSelected(true);
    rdbtnAveragePower.setBackground(Color.WHITE);
    rdbtnAveragePower.setBounds(349, 44, 109, 23);
    pnlEnergy.add(rdbtnAveragePower);

    rdbtnHourlyUsage = new JRadioButton("Hourly usage");
    rdbtnHourlyUsage.setToolTipText("Select \"hourly usage\" input type");
    rdbtnHourlyUsage.setFont(new Font("Tahoma", Font.PLAIN, 11));
    rdbtnHourlyUsage.setEnabled(false);
    rdbtnHourlyUsage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ClearPowerTxts();
            txtaveragepower.setEnabled(false);
            txthourlyusage.setEnabled(true);
            txtannualusage.setEnabled(false);
            lblKw.setEnabled(false);
            lblKwh.setEnabled(true);
            lblKwh_1.setEnabled(false);
            txthourlyusage.requestFocusInWindow();
            UpdateEnergyData();
        }
    });
    rdbtnHourlyUsage.setBackground(Color.WHITE);
    rdbtnHourlyUsage.setBounds(349, 70, 109, 23);
    pnlEnergy.add(rdbtnHourlyUsage);

    rdbtnAnnualUsage = new JRadioButton("Annual usage");
    rdbtnAnnualUsage.setToolTipText("Select \"annual usage\" input type");
    rdbtnAnnualUsage.setFont(new Font("Tahoma", Font.PLAIN, 11));
    rdbtnAnnualUsage.setEnabled(false);
    rdbtnAnnualUsage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ClearPowerTxts();
            txtaveragepower.setEnabled(false);
            txthourlyusage.setEnabled(false);
            txtannualusage.setEnabled(true);
            lblKw.setEnabled(false);
            lblKwh.setEnabled(false);
            lblKwh_1.setEnabled(true);
            txtannualusage.requestFocusInWindow();
            UpdateEnergyData();
        }
    });
    rdbtnAnnualUsage.setBackground(Color.WHITE);
    rdbtnAnnualUsage.setBounds(349, 97, 109, 23);
    pnlEnergy.add(rdbtnAnnualUsage);

    rdbtnsPower.add(rdbtnAveragePower);
    rdbtnsPower.add(rdbtnHourlyUsage);
    rdbtnsPower.add(rdbtnAnnualUsage);

    lblEnergyCostl = new JLabel("Energy cost:");
    lblEnergyCostl.setEnabled(false);
    lblEnergyCostl.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblEnergyCostl.setBounds(10, 101, 72, 14);
    pnlEnergy.add(lblEnergyCostl);

    lblpound2 = new JLabel("\u00A3");
    lblpound2.setEnabled(false);
    lblpound2.setFont(new Font("Tahoma", Font.PLAIN, 12));
    lblpound2.setBounds(91, 100, 13, 14);
    pnlEnergy.add(lblpound2);

    txtenergycost = new JTextField();
    txtenergycost.setToolTipText("Raw energy cost, per kWh");
    txtenergycost.setEnabled(false);
    txtenergycost.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            txtenergycost.selectAll();
        }
    });
    txtenergycost.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateROIEnergy();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateROIEnergy();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }
    });
    txtenergycost.setFont(new Font("Tahoma", Font.PLAIN, 12));
    txtenergycost.setBounds(102, 98, 74, 20);
    pnlEnergy.add(txtenergycost);
    txtenergycost.setColumns(10);

    lblPerKwh = new JLabel("per kWh");
    lblPerKwh.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPerKwh.setEnabled(false);
    lblPerKwh.setBounds(179, 101, 46, 14);
    pnlEnergy.add(lblPerKwh);

    txtaveragepower = new JTextField();
    txtaveragepower.setToolTipText("Average power in kW");
    txtaveragepower.setEnabled(false);
    txtaveragepower.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateEnergyData();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateEnergyData();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }
    });
    txtaveragepower.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtaveragepower.selectAll();
        }
    });
    txtaveragepower.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
            if (txtLimitRunSpeed.contains(arg0.getPoint())) {
                if (!txtaveragepower.isEnabled()) {
                    rdbtnAveragePower.doClick();
                }
            }
        }
    });
    txtaveragepower.setBounds(233, 47, 86, 20);
    pnlEnergy.add(txtaveragepower);
    txtaveragepower.setColumns(10);

    txthourlyusage = new JTextField();
    txthourlyusage.setToolTipText("Average hourly energy usage");
    txthourlyusage.setEnabled(false);
    txthourlyusage.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateEnergyData();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateEnergyData();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txthourlyusage.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txthourlyusage.selectAll();
        }
    });
    txthourlyusage.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
            if (txtLimitRunSpeed.contains(arg0.getPoint())) {
                if (!txthourlyusage.isEnabled())
                    rdbtnHourlyUsage.doClick();
            }
        }
    });
    txthourlyusage.setColumns(10);
    txthourlyusage.setBounds(233, 73, 86, 20);
    pnlEnergy.add(txthourlyusage);

    txtannualusage = new JTextField();
    txtannualusage.setToolTipText("Average annual energy usage");
    txtannualusage.setEnabled(false);
    txtannualusage.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateEnergyData();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateEnergyData();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txtannualusage.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtannualusage.selectAll();
        }
    });
    txtannualusage.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
            if (txtLimitRunSpeed.contains(arg0.getPoint())) {
                if (!txtannualusage.isEnabled())
                    rdbtnAnnualUsage.doClick();
            }
        }
    });
    txtannualusage.setColumns(10);
    txtannualusage.setBounds(233, 99, 86, 20);
    pnlEnergy.add(txtannualusage);

    cmbMachineEnergy = new JComboBox();
    cmbMachineEnergy.setEnabled(false);
    cmbMachineEnergy.setToolTipText("Select machine to edit");
    cmbMachineEnergy.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateEnergyView();
        }
    });
    cmbMachineEnergy.setBounds(69, 46, 152, 23);
    pnlEnergy.add(cmbMachineEnergy);

    lblMachine_1 = new JLabel("Machine:");
    lblMachine_1.setEnabled(false);
    lblMachine_1.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblMachine_1.setBounds(10, 50, 59, 14);
    pnlEnergy.add(lblMachine_1);

    lblKw = new JLabel("kW");
    lblKw.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblKw.setEnabled(false);
    lblKw.setBounds(323, 50, 15, 14);
    pnlEnergy.add(lblKw);

    lblKwh = new JLabel("kWh");
    lblKwh.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblKwh.setEnabled(false);
    lblKwh.setBounds(323, 76, 26, 14);
    pnlEnergy.add(lblKwh);

    lblKwh_1 = new JLabel("MWh");
    lblKwh_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblKwh_1.setEnabled(false);
    lblKwh_1.setBounds(323, 102, 26, 14);
    pnlEnergy.add(lblKwh_1);

    pnlGraphEnergy = new JPanel();
    pnlGraphEnergy.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    pnlGraphEnergy.setBackground(Color.WHITE);
    pnlGraphEnergy.setBounds(10, 126, 439, 226);
    pnlEnergy.add(pnlGraphEnergy);
    pnlGraphEnergy.setLayout(null);
    try {
        lblNoGraph2 = new JLabel(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/no_preview.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    lblNoGraph2.setBounds(2, 2, 435, 222);
    pnlGraphEnergy.add(lblNoGraph2);

    lblPleaseSetPower = new JLabel("Please set power usage for each machine");
    lblPleaseSetPower.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPleaseSetPower.setEnabled(false);
    lblPleaseSetPower.setForeground(Color.GRAY);
    lblPleaseSetPower.setBounds(10, 74, 215, 14);
    pnlEnergy.add(lblPleaseSetPower);

    lblMarginalEnergy = new JLabel("\u00A30.00 per annum");
    lblMarginalEnergy.setToolTipText("Marginal improvement");
    lblMarginalEnergy.setFont(new Font("Tahoma", Font.BOLD, 13));
    lblMarginalEnergy.setEnabled(false);
    lblMarginalEnergy.setBounds(279, 358, 170, 20);
    pnlEnergy.add(lblMarginalEnergy);

    label_4 = new JLabel("=");
    label_4.setForeground(Color.GRAY);
    label_4.setFont(new Font("Tahoma", Font.BOLD, 13));
    label_4.setBounds(259, 362, 11, 14);
    pnlEnergy.add(label_4);

    cmbMargEnergy2 = new JComboBox();
    cmbMargEnergy2.setToolTipText("New machine");
    cmbMargEnergy2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateROIEnergy();
        }
    });
    cmbMargEnergy2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMargEnergy2.setEnabled(false);
    cmbMargEnergy2.setBounds(141, 359, 111, 20);
    pnlEnergy.add(cmbMargEnergy2);

    label_5 = new JLabel("to");
    label_5.setForeground(Color.GRAY);
    label_5.setFont(new Font("Tahoma", Font.BOLD, 11));
    label_5.setBounds(125, 362, 16, 14);
    pnlEnergy.add(label_5);

    cmbMargEnergy1 = new JComboBox();
    cmbMargEnergy1.setToolTipText("Old machine");
    cmbMargEnergy1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateROIEnergy();
        }
    });
    cmbMargEnergy1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMargEnergy1.setEnabled(false);
    cmbMargEnergy1.setBounds(10, 359, 111, 20);
    pnlEnergy.add(cmbMargEnergy1);

    pnlMaint = new JPanel();
    pnlMaint.setBackground(Color.WHITE);
    tabsROI.addTab("Maintenance", null, pnlMaint, "ROI based on maintenance costs");
    tabsROI.setMnemonicAt(2, 65);
    pnlMaint.setLayout(null);

    lblThisToolDemonstrates_1 = new JLabel(
            "This tool demonstrates the maintenance reduction benefits of machines.");
    lblThisToolDemonstrates_1.setBounds(10, 11, 421, 14);
    lblThisToolDemonstrates_1.setForeground(Color.GRAY);
    lblThisToolDemonstrates_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    pnlMaint.add(lblThisToolDemonstrates_1);

    lblMaintenanceHoursPer = new JLabel("Annual downtime:");
    lblMaintenanceHoursPer.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblMaintenanceHoursPer.setEnabled(false);
    lblMaintenanceHoursPer.setBounds(10, 64, 86, 14);
    pnlMaint.add(lblMaintenanceHoursPer);

    lblRepairCostsPer = new JLabel("Labour costs per hour:");
    lblRepairCostsPer.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblRepairCostsPer.setEnabled(false);
    lblRepairCostsPer.setBounds(255, 36, 111, 14);
    pnlMaint.add(lblRepairCostsPer);

    lblPartsCostsPer = new JLabel("Parts costs per year:");
    lblPartsCostsPer.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPartsCostsPer.setEnabled(false);
    lblPartsCostsPer.setBounds(255, 64, 101, 14);
    pnlMaint.add(lblPartsCostsPer);

    cmbMachinesmaintenance = new JComboBox();
    cmbMachinesmaintenance.setEnabled(false);
    cmbMachinesmaintenance.setToolTipText("Please set maintenance costs for each machine");
    cmbMachinesmaintenance.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ViewMaintCosts();
        }
    });
    cmbMachinesmaintenance.setBounds(79, 30, 152, 23);
    pnlMaint.add(cmbMachinesmaintenance);

    txtmaintenancehours = new JTextField();
    txtmaintenancehours.setToolTipText("Hours per year for which machine is not running due to maintenance");
    txtmaintenancehours.setEnabled(false);
    txtmaintenancehours.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtmaintenancehours.selectAll();
        }
    });
    txtmaintenancehours.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateMaintCosts();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateMaintCosts();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txtmaintenancehours.setBounds(106, 61, 67, 20);
    pnlMaint.add(txtmaintenancehours);
    txtmaintenancehours.setColumns(10);

    txtmaintenanceperhour = new JTextField();
    txtmaintenanceperhour.setToolTipText("Hourly labour costs for maintenance");
    txtmaintenanceperhour.setEnabled(false);
    txtmaintenanceperhour.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtmaintenanceperhour.selectAll();
        }
    });
    txtmaintenanceperhour.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateMaintCosts();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateMaintCosts();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txtmaintenanceperhour.setColumns(10);
    txtmaintenanceperhour.setBounds(382, 33, 67, 20);
    pnlMaint.add(txtmaintenanceperhour);

    txtmaintenanceparts = new JTextField();
    txtmaintenanceparts.setToolTipText("Annual cost of maintenance parts for this machine");
    txtmaintenanceparts.setEnabled(false);
    txtmaintenanceparts.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtmaintenanceparts.selectAll();
        }
    });
    txtmaintenanceparts.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateMaintCosts();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateMaintCosts();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txtmaintenanceparts.setColumns(10);
    txtmaintenanceparts.setBounds(382, 61, 67, 20);
    pnlMaint.add(txtmaintenanceparts);

    lbltotalmaintcost = new JLabel("\u00A30.00 / year");
    lbltotalmaintcost.setToolTipText("Total annual spend on maintenance for this machine (labour + parts)");
    lbltotalmaintcost.setForeground(Color.GRAY);
    lbltotalmaintcost.setEnabled(false);
    lbltotalmaintcost.setHorizontalAlignment(SwingConstants.LEFT);
    lbltotalmaintcost.setFont(new Font("Tahoma", Font.BOLD, 11));
    lbltotalmaintcost.setBounds(344, 87, 105, 14);
    pnlMaint.add(lbltotalmaintcost);

    lblpound10 = new JLabel("\u00A3");
    lblpound10.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblpound10.setEnabled(false);
    lblpound10.setBounds(373, 36, 11, 14);
    pnlMaint.add(lblpound10);

    lblpound11 = new JLabel("\u00A3");
    lblpound11.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblpound11.setEnabled(false);
    lblpound11.setBounds(373, 64, 11, 14);
    pnlMaint.add(lblpound11);

    pnlGraphMaint = new JPanel();
    pnlGraphMaint.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    pnlGraphMaint.setBackground(Color.WHITE);
    pnlGraphMaint.setBounds(10, 110, 439, 242);
    pnlMaint.add(pnlGraphMaint);
    pnlGraphMaint.setLayout(null);
    try {
        lblNoGraph3 = new JLabel(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/no_preview.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    lblNoGraph3.setBounds(2, 2, 435, 238);
    pnlGraphMaint.add(lblNoGraph3);

    cmbMargMaint1 = new JComboBox();
    cmbMargMaint1.setToolTipText("Old machine");
    cmbMargMaint1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateROIMaint();
        }
    });
    cmbMargMaint1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMargMaint1.setEnabled(false);
    cmbMargMaint1.setBounds(10, 359, 111, 20);
    pnlMaint.add(cmbMargMaint1);

    label_8 = new JLabel("to");
    label_8.setForeground(Color.GRAY);
    label_8.setFont(new Font("Tahoma", Font.BOLD, 11));
    label_8.setBounds(125, 362, 16, 14);
    pnlMaint.add(label_8);

    cmbMargMaint2 = new JComboBox();
    cmbMargMaint2.setToolTipText("New machine");
    cmbMargMaint2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateROIMaint();
        }
    });
    cmbMargMaint2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMargMaint2.setEnabled(false);
    cmbMargMaint2.setBounds(141, 359, 111, 20);
    pnlMaint.add(cmbMargMaint2);

    label_9 = new JLabel("=");
    label_9.setForeground(Color.GRAY);
    label_9.setFont(new Font("Tahoma", Font.BOLD, 13));
    label_9.setBounds(259, 362, 11, 14);
    pnlMaint.add(label_9);

    lblMarginalMaint = new JLabel("\u00A30.00 per annum");
    lblMarginalMaint.setToolTipText("Marginal improvement");
    lblMarginalMaint.setFont(new Font("Tahoma", Font.BOLD, 13));
    lblMarginalMaint.setEnabled(false);
    lblMarginalMaint.setBounds(279, 358, 170, 20);
    pnlMaint.add(lblMarginalMaint);

    lblProdLoss = new JLabel("\u00A30.00 / year");
    lblProdLoss.setToolTipText("Loss in production value due to downtime");
    lblProdLoss.setForeground(Color.GRAY);
    lblProdLoss.setEnabled(false);
    lblProdLoss.setHorizontalAlignment(SwingConstants.LEFT);
    lblProdLoss.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblProdLoss.setBounds(106, 87, 125, 14);
    pnlMaint.add(lblProdLoss);

    lblHrs_1 = new JLabel("hrs");
    lblHrs_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblHrs_1.setEnabled(false);
    lblHrs_1.setBounds(180, 64, 16, 14);
    pnlMaint.add(lblHrs_1);

    label_10 = new JLabel("Machine:");
    label_10.setEnabled(false);
    label_10.setFont(new Font("Tahoma", Font.BOLD, 11));
    label_10.setBounds(10, 34, 59, 14);
    pnlMaint.add(label_10);

    label_11 = new JLabel("=");
    label_11.setEnabled(false);
    label_11.setForeground(Color.GRAY);
    label_11.setFont(new Font("Tahoma", Font.BOLD, 13));
    label_11.setBounds(88, 87, 11, 14);
    pnlMaint.add(label_11);

    label_12 = new JLabel("=");
    label_12.setEnabled(false);
    label_12.setForeground(Color.GRAY);
    label_12.setFont(new Font("Tahoma", Font.BOLD, 13));
    label_12.setBounds(323, 87, 11, 14);
    pnlMaint.add(label_12);

    lblAnnualTotal = new JLabel("Annual total");
    lblAnnualTotal.setEnabled(false);
    lblAnnualTotal.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblAnnualTotal.setBounds(255, 87, 67, 14);
    pnlMaint.add(lblAnnualTotal);

    lblProductionLoss = new JLabel("Production loss");
    lblProductionLoss.setEnabled(false);
    lblProductionLoss.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblProductionLoss.setBounds(10, 87, 77, 14);
    pnlMaint.add(lblProductionLoss);

    pnlWaste = new JPanel();
    pnlWaste.setBackground(Color.WHITE);
    tabsROI.addTab("Waste Reduction", null, pnlWaste, "ROI based on waste reduction");
    pnlWaste.setLayout(null);

    lblThisToolDemonstrates = new JLabel(
            "This tool demonstrates the waste reduction capabilities of particular machines.");
    lblThisToolDemonstrates.setForeground(Color.GRAY);
    lblThisToolDemonstrates.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblThisToolDemonstrates.setBounds(10, 11, 439, 14);
    pnlWaste.add(lblThisToolDemonstrates);

    lblWasteSavedPer_1 = new JLabel("Waste saved per splice due to flag detection camera:");
    lblWasteSavedPer_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblWasteSavedPer_1.setEnabled(false);
    lblWasteSavedPer_1.setBounds(10, 39, 256, 14);
    pnlWaste.add(lblWasteSavedPer_1);

    txtwastesavedflags = new JTextField();
    txtwastesavedflags.setToolTipText("Saving per splice");
    txtwastesavedflags.setEnabled(false);
    txtwastesavedflags.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtwastesavedflags.selectAll();
        }
    });
    txtwastesavedflags.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateROIWaste();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateROIWaste();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txtwastesavedflags.setBounds(286, 36, 86, 20);
    pnlWaste.add(txtwastesavedflags);
    txtwastesavedflags.setColumns(10);

    lblM_1 = new JLabel("m");
    lblM_1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblM_1.setEnabled(false);
    lblM_1.setBounds(378, 39, 46, 14);
    pnlWaste.add(lblM_1);

    lblWasteSavedPer_2 = new JLabel("Waste saved per mother roll due to alignment guide:");
    lblWasteSavedPer_2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblWasteSavedPer_2.setEnabled(false);
    lblWasteSavedPer_2.setBounds(10, 64, 256, 14);
    pnlWaste.add(lblWasteSavedPer_2);

    txtwastesavedguide = new JTextField();
    txtwastesavedguide.setToolTipText("Saving per mother roll");
    txtwastesavedguide.setEnabled(false);
    txtwastesavedguide.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            UpdateROIWaste();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            UpdateROIWaste();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
        }
    });
    txtwastesavedguide.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtwastesavedguide.selectAll();
        }
    });
    txtwastesavedguide.setBounds(286, 61, 86, 20);
    pnlWaste.add(txtwastesavedguide);
    txtwastesavedguide.setColumns(10);

    lblM_2 = new JLabel("m");
    lblM_2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblM_2.setEnabled(false);
    lblM_2.setBounds(378, 64, 46, 14);
    pnlWaste.add(lblM_2);

    pnlGraphWaste = new JPanel();
    pnlGraphWaste.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    pnlGraphWaste.setBackground(Color.WHITE);
    pnlGraphWaste.setBounds(10, 90, 439, 262);
    pnlWaste.add(pnlGraphWaste);
    pnlGraphWaste.setLayout(null);
    try {
        lblNoGraph4 = new JLabel(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/no_preview.png"))));
    } catch (IOException e2) {
        e2.printStackTrace();
    }
    lblNoGraph4.setBounds(2, 2, 435, 258);
    pnlGraphWaste.add(lblNoGraph4);

    cmbMargWaste1 = new JComboBox();
    cmbMargWaste1.setToolTipText("Old machine");
    cmbMargWaste1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateROIWaste();
        }
    });
    cmbMargWaste1.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMargWaste1.setEnabled(false);
    cmbMargWaste1.setBounds(10, 359, 111, 20);
    pnlWaste.add(cmbMargWaste1);

    label_1 = new JLabel("to");
    label_1.setForeground(Color.GRAY);
    label_1.setFont(new Font("Tahoma", Font.BOLD, 11));
    label_1.setBounds(125, 362, 16, 14);
    pnlWaste.add(label_1);

    cmbMargWaste2 = new JComboBox();
    cmbMargWaste2.setToolTipText("New machine");
    cmbMargWaste2.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateROIWaste();
        }
    });
    cmbMargWaste2.setFont(new Font("Tahoma", Font.PLAIN, 11));
    cmbMargWaste2.setEnabled(false);
    cmbMargWaste2.setBounds(141, 359, 111, 20);
    pnlWaste.add(cmbMargWaste2);

    label_6 = new JLabel("=");
    label_6.setForeground(Color.GRAY);
    label_6.setFont(new Font("Tahoma", Font.BOLD, 13));
    label_6.setBounds(259, 362, 11, 14);
    pnlWaste.add(label_6);

    lblMarginalWaste = new JLabel("0.00m per annum");
    lblMarginalWaste.setToolTipText("Marginal improvement");
    lblMarginalWaste.setFont(new Font("Tahoma", Font.BOLD, 13));
    lblMarginalWaste.setEnabled(false);
    lblMarginalWaste.setBounds(279, 355, 170, 16);
    pnlWaste.add(lblMarginalWaste);

    lblMarginalWasteValue = new JLabel("(\u00A30.00 per annum)");
    lblMarginalWasteValue.setToolTipText("Marginal improvement value");
    lblMarginalWasteValue.setForeground(Color.GRAY);
    lblMarginalWasteValue.setFont(new Font("Tahoma", Font.BOLD, 11));
    lblMarginalWasteValue.setBounds(279, 370, 170, 16);
    pnlWaste.add(lblMarginalWasteValue);

    machNames = new HashSet<String>();
    jobNames = new HashSet<String>();

    lblStatus = new JLabel(" Ready.");
    lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 12));
    frmTitanRoiCalculator.getContentPane().add(lblStatus, BorderLayout.SOUTH);

    lblmmin = new JLabel("(m/min)");
    lblmmin.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblmmin.setEnabled(false);
    lblmmin.setBounds(206, 168, 44, 14);
    pnlJobs.add(lblmmin);

    objfilter = new OBJfilter(1);

    // labels for unit conversion
    labs = new JLabel[7];
    labs[0] = lblmm0;
    labs[1] = lblmm1;
    labs[2] = lblmm2;
    labs[3] = lblgm3;
    labs[4] = lblmm3;
    labs[5] = lblmicro0;

    lblGsm = new JLabel("(gsm)");
    lblGsm.setToolTipText("Switch the input type for density between gsm and g/cc");
    lblGsm.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblGsm.setEnabled(false);
    lblGsm.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
            if (lblGsm.isEnabled() && lblGsm.contains(arg0.getPoint())) {
                jobFormReady = false;
                try {
                    //double oldval = Double.parseDouble(txtDensity.getText());
                    //double thickness = Double.parseDouble(txtThickness.getText());
                    double oldval = ((Job) listJobs.getSelectedValue()).getDensity();
                    double thickness = ((Job) listJobs.getSelectedValue()).getThickness();
                    if (lblGsm.getText().equals("(gsm)")) {
                        lblGsm.setText("(g/cc)");
                        label_3.setVisible(false);
                        lblgm3.setText("(gsm)");
                        txtDensity.setText(Double.toString(roundTwoDecimals(oldval * thickness)));
                        ((Job) listJobs.getSelectedValue()).gsm = true;
                    } else {
                        lblGsm.setText("(gsm)");
                        label_3.setVisible(true);
                        lblgm3.setText("(g/cm  )");
                        txtDensity.setText(Double.toString(roundTwoDecimals(oldval)));
                        ((Job) listJobs.getSelectedValue()).gsm = false;
                    }
                } catch (Exception e) {
                    lblGsm.setText("(gsm)");
                    label_3.setVisible(true);
                    lblgm3.setText("(g/cm  )");
                    txtDensity.setText("0.92");
                }
                jobFormReady = true;

            }
        }

        @Override
        public void mouseEntered(MouseEvent arg0) {
            lblGsm.setForeground(new Color(0, 0, 128));
        }

        @Override
        public void mouseExited(MouseEvent e) {
            lblGsm.setForeground(Color.black);
        }
    });
    lblGsm.setForeground(new Color(0, 0, 0));
    lblGsm.setCursor(new Cursor(Cursor.HAND_CURSOR));
    lblGsm.setBounds(177, 102, 46, 14);
    pnlMaterials.add(lblGsm);

    lblOr = new JLabel("or:");
    lblOr.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblOr.setEnabled(false);
    lblOr.setBounds(155, 102, 14, 14);
    pnlMaterials.add(lblOr);
    labs[6] = lblmmin;

    cmbUnwindType = new JComboBox();
    cmbUnwindType.setToolTipText("Type of measure to use for the unwind quantity above");
    cmbUnwindType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateUnwindAmount();
        }
    });
    cmbUnwindType.setEnabled(false);
    cmbUnwindType
            .setModel(new DefaultComboBoxModel(new String[] { "Length (m)", "Weight (kg)", "Diameter (mm)" }));
    cmbUnwindType.setBounds(92, 124, 95, 20);
    pnlUnwinds.add(cmbUnwindType);

    txtWebWidth = new JTextField();
    txtWebWidth.setToolTipText("Width of mother rolls");
    txtWebWidth.setText("1350");
    txtWebWidth.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            txtWebWidth.selectAll();
        }
    });
    txtWebWidth.setEnabled(false);
    txtWebWidth.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateJob();
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateJob();
        }

        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }
    });
    txtWebWidth.setBounds(92, 26, 86, 20);
    pnlUnwinds.add(txtWebWidth);
    txtWebWidth.setColumns(10);

    lblAverageFlags = new JLabel("Average Flags:");
    lblAverageFlags.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblAverageFlags.setToolTipText("The average number of flags in each mother roll");
    lblAverageFlags.setEnabled(false);
    lblAverageFlags.setBounds(14, 79, 75, 14);
    pnlUnwinds.add(lblAverageFlags);

    txtFlagCount = new JTextField();
    txtFlagCount.setToolTipText("The average number of flags in each mother roll");
    txtFlagCount.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent arg0) {
            txtFlagCount.selectAll();
        }
    });
    txtFlagCount.getDocument().addDocumentListener(new JobInputChangeListener());
    txtFlagCount.setEnabled(false);
    txtFlagCount.setText("1");
    txtFlagCount.setBounds(92, 76, 43, 20);
    pnlUnwinds.add(txtFlagCount);
    txtFlagCount.setColumns(10);

    lblPerRoll = new JLabel("per roll");
    lblPerRoll.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblPerRoll.setEnabled(false);
    lblPerRoll.setBounds(140, 79, 46, 14);
    pnlUnwinds.add(lblPerRoll);

    txtLimitRunSpeed = new JTextField();
    txtLimitRunSpeed.setToolTipText(
            "Override for top machine speed (may be required for particular materials or environments)");
    txtLimitRunSpeed.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseReleased(MouseEvent arg0) {
            if (txtLimitRunSpeed.contains(arg0.getPoint())) {
                txtLimitRunSpeed.setEnabled(true);
                chckbxLimitRunSpeed.setSelected(true);
                txtLimitRunSpeed.requestFocusInWindow();
                txtLimitRunSpeed.selectAll();
                UpdateJob();
            }
        }
    });
    txtLimitRunSpeed.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            if (txtLimitRunSpeed.isEnabled()) {
                txtLimitRunSpeed.selectAll();
                chckbxLimitRunSpeed.setSelected(true);
            }
        }
    });
    txtLimitRunSpeed.getDocument().addDocumentListener(new JobInputChangeListener());
    txtLimitRunSpeed.setEnabled(false);

    txtLimitRunSpeed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            chckbxLimitRunSpeed.setSelected(true);
        }
    });
    txtLimitRunSpeed.setText("800");
    txtLimitRunSpeed.setColumns(10);
    txtLimitRunSpeed.setBounds(130, 165, 65, 20);
    pnlJobs.add(txtLimitRunSpeed);

    cmbRewindType = new JComboBox();
    cmbRewindType.setToolTipText("Type of measure to use for rewind output above");
    cmbRewindType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateRewindAmount();
            //UpdateJob();
        }
    });
    cmbRewindType.setEnabled(false);
    cmbRewindType
            .setModel(new DefaultComboBoxModel(new String[] { "Length (m)", "Weight (kg)", "Diameter (mm)" }));
    cmbRewindType.setBounds(109, 218, 95, 20);
    pnlJobs.add(cmbRewindType);

    chckbxLimitRunSpeed = new JCheckBox("");
    chckbxLimitRunSpeed.setToolTipText(
            "Override for top machine speed (may be required for particular materials or environments)");
    chckbxLimitRunSpeed.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (chckbxLimitRunSpeed.isSelected()) {
                txtLimitRunSpeed.setEnabled(true);
                txtLimitRunSpeed.requestFocusInWindow();
                txtLimitRunSpeed.selectAll();
            } else {
                txtLimitRunSpeed.setEnabled(false);
            }

            UpdateJob();
        }
    });
    chckbxLimitRunSpeed.setEnabled(false);
    chckbxLimitRunSpeed.setBounds(105, 164, 20, 20);
    pnlJobs.add(chckbxLimitRunSpeed);

    lblLimitRunSpeed = new JLabel("Speed Limit:");
    lblLimitRunSpeed.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblLimitRunSpeed.setToolTipText(
            "Override for top machine speed (may be required for particular materials or environments)");
    lblLimitRunSpeed.setEnabled(false);
    lblLimitRunSpeed.setBounds(47, 168, 59, 14);
    pnlJobs.add(lblLimitRunSpeed);

    lblKnifeType = new JLabel("Knife Type:");
    lblKnifeType.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblKnifeType.setToolTipText("Select knife type for this job");
    lblKnifeType.setEnabled(false);
    lblKnifeType.setHorizontalAlignment(SwingConstants.RIGHT);
    lblKnifeType.setBounds(46, 89, 59, 14);
    pnlJobs.add(lblKnifeType);

    cmbKnifeType = new JComboBox();
    cmbKnifeType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            UpdateJob();
        }
    });
    cmbKnifeType.setModel(new DefaultComboBoxModel(new String[] { "Razor in Air", "Rotary Shear" }));
    cmbKnifeType.setToolTipText("Select knife type for this job");
    cmbKnifeType.setEnabled(false);
    cmbKnifeType.setBounds(109, 86, 95, 20);
    pnlJobs.add(cmbKnifeType);

    tabbedPane.setMnemonicAt(0, KeyEvent.VK_M);
    tabbedPane.setMnemonicAt(1, KeyEvent.VK_J);
    tabbedPane.setMnemonicAt(2, KeyEvent.VK_S);
    tabbedPane.setMnemonicAt(3, KeyEvent.VK_P);
    tabbedPane.setMnemonicAt(4, KeyEvent.VK_R);

    tabsROI.setMnemonicAt(0, KeyEvent.VK_D);
    tabsROI.setMnemonicAt(1, KeyEvent.VK_N);
    tabsROI.setMnemonicAt(3, KeyEvent.VK_W);

    scrollPane_4 = new JScrollPane();
    scrollPane_4.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane_4.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane_4.setBorder(null);
    scrollPane_4.setBounds(522, 44, 245, 405);
    pnlROI.add(scrollPane_4);

    panel_11 = new JPanel();
    panel_11.setToolTipText(
            "Click a machine to select it. Select two or more machines to compare their ROI measures.");
    scrollPane_4.setViewportView(panel_11);
    panel_11.setBackground(Color.WHITE);
    panel_11.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    panel_11.setLayout(new BorderLayout(0, 0));

    listCompareRoi = new JList(listModel);
    panel_11.add(listCompareRoi, BorderLayout.NORTH);
    listCompareRoi.setToolTipText(
            "Click a machine to select it. Select two or more machines to compare their ROI measures.");
    listCompareRoi.setBorder(null);
    listCompareRoi.setSelectionModel(new DefaultListSelectionModel() {
        private static final long serialVersionUID = 1L;

        boolean gestureStarted = false;

        @Override
        public void setSelectionInterval(int index0, int index1) {
            if (!gestureStarted) {
                if (isSelectedIndex(index0)) {
                    super.removeSelectionInterval(index0, index1);
                } else {
                    super.addSelectionInterval(index0, index1);
                }
            }
            gestureStarted = true;
        }

        @Override
        public void setValueIsAdjusting(boolean isAdjusting) {
            if (isAdjusting == false) {
                gestureStarted = false;
            }
        }

    });
    listCompareRoi.addListSelectionListener(new ROIListSelectionListener());
    listCompareRoi.setCellRenderer(new MachineListRenderer());
    listCompare.setSelectionModel(listCompareRoi.getSelectionModel());

    btnJobUp = new JButton("");
    btnJobUp.setToolTipText("Move job up");
    btnJobUp.addActionListener(new JobUpListener());
    try {
        btnJobUp.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up.png"))));
        btnJobUp.setRolloverEnabled(true);
        btnJobUp.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up_over.png"))));
        btnJobUp.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/up_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnJobUp.setEnabled(false);
    btnJobUp.setBounds(700, 463, 30, 30);
    pnlJob.add(btnJobUp);

    btnJobDown = new JButton("");
    btnJobDown.setToolTipText("Move job down");
    btnJobDown.addActionListener(new JobDownListener());
    try {
        btnJobDown.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down.png"))));
        btnJobDown.setRolloverEnabled(true);
        btnJobDown.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down_over.png"))));
        btnJobDown.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/down_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnJobDown.setEnabled(false);
    btnJobDown.setBounds(737, 463, 30, 30);
    pnlJob.add(btnJobDown);

    btnNewJob = new JButton("Add New");
    btnNewJob.setFont(new Font("Tahoma", Font.BOLD, 11));
    btnNewJob.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            jobFormReady = false;
            ResetStatusLabel();

            EnableJobForm();

            // new
            ResetJobForm();
            lblGsm.setText("(gsm)");
            label_3.setVisible(true);
            lblgm3.setText("(g/cm  )");
            txtDensity.setText("0.92");

            btnJobDelete.setEnabled(true);

            btnAddAll.setEnabled(true);

            /*if(listJobs.getSelectedIndex() == 0)
               btnJobUp.setEnabled(false);
            else
               btnJobUp.setEnabled(true);
                    
            if(listJobs.getSelectedIndex() == jobModel.getSize()-1)
               btnJobDown.setEnabled(false);
            else
               btnJobDown.setEnabled(true);*/

            int index = listJobs.getSelectedIndex();
            int size = jobModel.getSize();

            if (size >= Consts.JOB_LIST_LIMIT) { // Max list size
                ShowMessage("Maximum number of jobs allocated. Please delete before attempting to add more.");
                return;
            }

            String newName = getUniqueJobName("Job");
            txtJobName.setText(newName);
            job = new Job(newName);
            jobNames.add(newName.toLowerCase());

            //If no selection or if item in last position is selected,
            //add the new one to end of list, and select new one.
            if (index == -1 || (index + 1 == size)) {

                jobModel.addElement(job);
                listJobs.setSelectedIndex(size);
                listJobsAvail.setSelectedIndex(size);
                if (size > 0)
                    btnJobUp.setEnabled(true);

                //Otherwise insert the new one after the current selection,
                //and select new one.
            } else {
                jobModel.insertElementAt(job, index + 1);
                listJobs.setSelectedIndex(index + 1);
                listJobsAvail.setSelectedIndex(index + 1);
            }

            // TODO don't reset form, or add copy button

            ResetStatusLabel();
            jobFormReady = true;

            UpdateJob();
            txtJobName.requestFocusInWindow();
        }
    });
    try {
        btnNewJob.setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/plus.png"))));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnNewJob.setToolTipText("Add new job");
    btnNewJob.setBounds(522, 460, 110, 36);
    pnlJob.add(btnNewJob);

    lblJobConfiguration = new JLabel("Job Configuration");
    lblJobConfiguration.setFont(new Font("Tahoma", Font.BOLD, 18));
    lblJobConfiguration.setBounds(29, 18, 269, 22);
    pnlJob.add(lblJobConfiguration);

    btnJobDelete = new JButton("");
    btnJobDelete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ResetStatusLabel();

            Job selected = (Job) listJobs.getSelectedValue();
            jobNames.remove(selected.getName().toLowerCase());

            ListSelectionModel lsm = listJobs.getSelectionModel();
            int firstSelected = lsm.getMinSelectionIndex();
            int lastSelected = lsm.getMaxSelectionIndex();
            jobModel.removeRange(firstSelected, lastSelected);

            int size = jobModel.size();

            if (size == 0) {
                //List is empty: disable delete, up, and down buttons.
                /*btnJobDelete.setEnabled(false);
                btnJobUp.setEnabled(false);
                btnJobDown.setEnabled(false);*/

            } else {
                //Adjust the selection.
                if (firstSelected == jobModel.getSize()) {
                    //Removed item in last position.
                    firstSelected--;
                }
                listJobs.setSelectedIndex(firstSelected);

                if (size == 21) { // No longer full list
                    ResetStatusLabel();
                }

                job = (Job) listJobs.getSelectedValue();
            }
        }
    });

    try {
        btnJobDelete
                .setIcon(new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete.png"))));
        btnJobDelete.setRolloverEnabled(true);
        btnJobDelete.setRolloverIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete_over.png"))));
        btnJobDelete.setDisabledIcon(
                new ImageIcon(ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/delete_dis.png"))));
    } catch (NullPointerException e11) {
        System.out.println("Image load error");
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    btnJobDelete.setToolTipText("Delete job");
    btnJobDelete.setRolloverEnabled(true);
    btnJobDelete.setEnabled(false);
    btnJobDelete.setBounds(651, 460, 36, 36);
    pnlJob.add(btnJobDelete);

    lblAddNewJobs = new JLabel(
            "Add new jobs to the list on the right, then configure unwind, rewind and material settings below");
    lblAddNewJobs.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblAddNewJobs.setBounds(29, 45, 483, 14);
    pnlJob.add(lblAddNewJobs);

    lblJobs = new JLabel("Jobs");
    lblJobs.setFont(new Font("Tahoma", Font.BOLD, 12));
    lblJobs.setBounds(522, 19, 85, 14);
    pnlJob.add(lblJobs);

    panel_1 = new JPanel();
    panel_1.setLayout(null);
    panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Total Output",
            TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel_1.setBounds(280, 380, 227, 116);
    pnlJob.add(panel_1);

    lblTargetOutputFor = new JLabel("Target output for job:");
    lblTargetOutputFor.setEnabled(false);
    lblTargetOutputFor.setBounds(30, 22, 129, 14);
    panel_1.add(lblTargetOutputFor);

    txtTargetTotal = new JTextField();
    txtTargetTotal.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtTargetTotal.selectAll();
        }
    });
    txtTargetTotal.getDocument().addDocumentListener(new JobInputChangeListener());
    txtTargetTotal.setToolTipText("Total output quantity for this job");
    txtTargetTotal.setText("10000");
    txtTargetTotal.setEnabled(false);
    txtTargetTotal.setColumns(10);
    txtTargetTotal.setBounds(30, 43, 118, 20);

    panel_1.add(txtTargetTotal);

    cmbTargetTotal = new JComboBox();
    cmbTargetTotal.setToolTipText("Type of measure to use for output quantity above");
    cmbTargetTotal.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            UpdateTotalsAmount();
        }
    });
    cmbTargetTotal.setModel(
            new DefaultComboBoxModel(new String[] { "Length (m)", "Weight (kg)", "Weight (tonnes)" }));
    cmbTargetTotal.setEnabled(false);
    cmbTargetTotal.setBounds(30, 67, 118, 20);
    panel_1.add(cmbTargetTotal);

    lblCounts = new JLabel("0 reel(s), 0 set(s), 0 mother(s)");
    lblCounts.setFont(new Font("Tahoma", Font.PLAIN, 11));
    lblCounts.setForeground(Color.GRAY);
    lblCounts.setBounds(30, 92, 187, 14);
    panel_1.add(lblCounts);

    panel_2 = new JPanel();
    panel_2.setLayout(null);
    panel_2.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Name", TitledBorder.LEADING,
            TitledBorder.TOP, null, new Color(0, 0, 0)));
    panel_2.setBounds(20, 72, 250, 83);
    pnlJob.add(panel_2);

    txtJobName = new JTextField();
    txtJobName.addFocusListener(new FocusAdapter() {
        @Override
        public void focusGained(FocusEvent e) {
            txtJobName.selectAll();
        }
    });
    txtJobName.setBounds(90, 30, 145, 28);
    panel_2.add(txtJobName);
    txtJobName.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void changedUpdate(DocumentEvent arg0) {
        }

        @Override
        public void insertUpdate(DocumentEvent arg0) {
            UpdateJobName();
        }

        @Override
        public void removeUpdate(DocumentEvent arg0) {
            UpdateJobName();
        }
    });
    txtJobName.setToolTipText("Set the name of this job");
    txtJobName.setFont(new Font("Tahoma", Font.BOLD, 12));
    txtJobName.setEnabled(false);
    txtJobName.setColumns(10);

    lblJobName = new JLabel("Job name:");
    lblJobName.setToolTipText("Set the name of this job");
    lblJobName.setEnabled(false);
    lblJobName.setBounds(22, 31, 60, 24);
    panel_2.add(lblJobName);
    lblJobName.setFont(new Font("Tahoma", Font.PLAIN, 13));

    btnResetJobs = new JButton("Reset");
    btnResetJobs.setBounds(20, 460, 100, 36);
    pnlJob.add(btnResetJobs);
    btnResetJobs.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ResetJobForm();
            UpdateJob();
        }
    });
    btnResetJobs.setToolTipText("Reset the form");
    btnResetJobs.setEnabled(false);

    scrollPane_1 = new JScrollPane();
    scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
    scrollPane_1.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane_1.setBorder(null);
    scrollPane_1.setBounds(522, 44, 245, 405);
    pnlJob.add(scrollPane_1);

    panel_7 = new JPanel();
    panel_7.setToolTipText("Select a job to edit options, re-order, or delete");
    scrollPane_1.setViewportView(panel_7);
    panel_7.setBackground(Color.WHITE);
    panel_7.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, Color.LIGHT_GRAY, null, null, null));
    panel_7.setLayout(new BorderLayout(0, 0));

    listJobs = new JList(jobModel);
    listJobs.setSelectionModel(listJobsAvail.getSelectionModel());
    panel_7.add(listJobs, BorderLayout.NORTH);
    listJobs.setToolTipText("Select a job to edit options, re-order, or delete");
    listJobs.addListSelectionListener(new JobListSelectionListener());
    listJobs.setBorder(null);
    listJobs.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    listJobs.setCellRenderer(new JobListRenderer());
    pnlJob.setFocusTraversalPolicy(new FocusTraversalOnArray(
            new Component[] { cmbMaterials, txtThickness, txtDensity, cmbUnwindCore, txtUnwindAmount, txtSlits,
                    txtSlitWidth, cmbRewindCore, txtRewindAmount, cmbJobDomain, lblPresets, lblThickness_1,
                    lblDensity_1, pnlMaterials, lblWebWidthmm, lblmm0, lblUnwindCoremm, lblmm1, lblUnwindLength,
                    pnlUnwinds, lblmicro0, lblgm3, label_3, pnlJobs, lblTargetRewindLength, lblSlitWidth,
                    lblSlitCount, lblTrimtotal, lblTrim, lblRewindCoremm, lblPer_1, lblmm3, lblmm2 }));
    Image img = null;
    try {
        img = ImageIO.read(FrmMain.class.getResourceAsStream("/atlas/refresh.png"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    g.drawImage(img, 0, 0, 25, 25, null);

    LoadSettings();

    DoLicenceCheck();

    initialising = false;

}

From source file:net.sourceforge.msscodefactory.cfgcash.v2_0.CFGCashSwing.CFGCashSwingSecSessionAttrJPanel.java

public CFGCashSwingSecSessionAttrJPanel(ICFGCashSwingSchema argSchema, ICFGCashSecSessionObj argFocus) {
    super();/*from   w  w w .  j  ava 2 s  .c o m*/
    JLabel label;
    JComponent compo;
    CFJReferenceEditor reference;
    final String S_ProcName = "construct-schema-focus";
    if (argSchema == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "argSchema");
    }
    // argFocus is optional; focus may be set later during execution as
    // conditions of the runtime change.
    swingSchema = argSchema;
    setSwingFocusAsSecSession(argFocus);
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 785;
    final int panelwidth = fieldx + fieldwidth + spacing;
    // temporary -- I think you have to have a panel bigger than the coordinates initially
    setSize(panelwidth, 100000);

    label = getSwingLabelContainerSecUser();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceContainerSecUser();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelSecSessionId();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorSecSessionId();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelStart();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorStart();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelFinish();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorFinish();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    // Now we can set the proper size based on the fields and references populated
    setSize(panelwidth, y);
    Dimension pfsz = new Dimension(panelwidth, y);
    setPreferredSize(pfsz);
    Dimension min = new Dimension(400, y);
    setMinimumSize(min);
    populateFields();
    adjustComponentEnableStates();
    swingIsInitializing = false;
}

From source file:net.sourceforge.msscodefactory.cfinternet.v2_0.CFInternetSwing.CFInternetSwingTSecGroupMemberAttrJPanel.java

public CFInternetSwingTSecGroupMemberAttrJPanel(ICFInternetSwingSchema argSchema,
        ICFInternetTSecGroupMemberObj argFocus) {
    super();/* w w  w  .  j  a v a 2s .  c  o  m*/
    JLabel label;
    JComponent compo;
    CFJReferenceEditor reference;
    final String S_ProcName = "construct-schema-focus";
    if (argSchema == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "argSchema");
    }
    // argFocus is optional; focus may be set later during execution as
    // conditions of the runtime change.
    swingSchema = argSchema;
    setSwingFocusAsTSecGroupMember(argFocus);
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 785;
    final int panelwidth = fieldx + fieldwidth + spacing;
    // temporary -- I think you have to have a panel bigger than the coordinates initially
    setSize(panelwidth, 100000);

    label = getSwingLabelOwnerTenant();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceOwnerTenant();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelContainerGroup();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceContainerGroup();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelParentUser();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceParentUser();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelTSecGroupMemberId();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorTSecGroupMemberId();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    // Now we can set the proper size based on the fields and references populated
    setSize(panelwidth, y);
    Dimension pfsz = new Dimension(panelwidth, y);
    setPreferredSize(pfsz);
    Dimension min = new Dimension(400, y);
    setMinimumSize(min);
    populateFields();
    adjustComponentEnableStates();
    swingIsInitializing = false;
}

From source file:net.sourceforge.msscodefactory.cfinternet.v2_0.CFInternetSwing.CFInternetSwingURLProtocolAttrJPanel.java

public CFInternetSwingURLProtocolAttrJPanel(ICFInternetSwingSchema argSchema,
        ICFInternetURLProtocolObj argFocus) {
    super();/*from www .  j a v  a2 s .  c o  m*/
    JLabel label;
    JComponent compo;
    CFJReferenceEditor reference;
    final String S_ProcName = "construct-schema-focus";
    if (argSchema == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "argSchema");
    }
    // argFocus is optional; focus may be set later during execution as
    // conditions of the runtime change.
    swingSchema = argSchema;
    setSwingFocusAsURLProtocol(argFocus);
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 785;
    final int panelwidth = fieldx + fieldwidth + spacing;
    // temporary -- I think you have to have a panel bigger than the coordinates initially
    setSize(panelwidth, 100000);

    label = getSwingLabelURLProtocolId();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorURLProtocolId();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelName();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorName();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelDescription();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDescription();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelIsSecure();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorIsSecure();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    // Now we can set the proper size based on the fields and references populated
    setSize(panelwidth, y);
    Dimension pfsz = new Dimension(panelwidth, y);
    setPreferredSize(pfsz);
    Dimension min = new Dimension(400, y);
    setMinimumSize(min);
    populateFields();
    adjustComponentEnableStates();
    swingIsInitializing = false;
}

From source file:net.sourceforge.msscodefactory.cfinternet.v2_0.CFInternetSwing.CFInternetSwingVersionAttrJPanel.java

public CFInternetSwingVersionAttrJPanel(ICFInternetSwingSchema argSchema, ICFInternetVersionObj argFocus) {
    super();/*from ww  w .  j  ava2  s.co  m*/
    JLabel label;
    JComponent compo;
    CFJReferenceEditor reference;
    final String S_ProcName = "construct-schema-focus";
    if (argSchema == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "argSchema");
    }
    // argFocus is optional; focus may be set later during execution as
    // conditions of the runtime change.
    swingSchema = argSchema;
    setSwingFocusAsVersion(argFocus);
    final int spacing = 5;
    int y = spacing;
    final int height = 25;
    final int textheight = 80;
    final int vspacing = height + spacing;
    final int textvspacing = textheight + spacing;
    final int labelx = spacing;
    final int labelwidth = 200;
    final int fieldx = labelx + labelwidth + spacing;
    final int fieldwidth = 785;
    final int panelwidth = fieldx + fieldwidth + spacing;
    // temporary -- I think you have to have a panel bigger than the coordinates initially
    setSize(panelwidth, 100000);

    label = getSwingLabelOwnerTenant();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    reference = getSwingReferenceOwnerTenant();
    add(reference);
    reference.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelId();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorId();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    label = getSwingLabelDescription();
    add(label);
    label.setBounds(labelx, y, labelwidth, height);
    compo = getSwingEditorDescription();
    add(compo);
    compo.setBounds(fieldx, y, fieldwidth, height);
    y = y + vspacing;

    // Now we can set the proper size based on the fields and references populated
    setSize(panelwidth, y);
    Dimension pfsz = new Dimension(panelwidth, y);
    setPreferredSize(pfsz);
    Dimension min = new Dimension(400, y);
    setMinimumSize(min);
    populateFields();
    adjustComponentEnableStates();
    swingIsInitializing = false;
}