Example usage for javax.swing JList JList

List of usage examples for javax.swing JList JList

Introduction

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

Prototype

public JList() 

Source Link

Document

Constructs a JList with an empty, read-only, model.

Usage

From source file:imageuploader.ImgWindow.java

private void fillCombo(File f) throws FileNotFoundException, IOException {
    BufferedReader input = new BufferedReader(new FileReader(f));
    String line = null;//w w w  .  ja v  a  2s  .  com
    Vector model = new Vector();
    Items it;
    jCB_Colors.removeAllItems();
    JList list = new JList();
    while ((line = input.readLine()) != null) {
        String[] result = line.split(",");
        jCB_Colors.addItem(new Items(result[0], result[1]));
    }
    //jtx_colorname.setText("");
    input.close();

}

From source file:com.googlecode.vfsjfilechooser2.filepane.VFSFilePane.java

public JPanel createList() {
    JPanel p = new JPanel(new BorderLayout());
    final VFSJFileChooser fileChooser = getFileChooser();
    final JList aList = new JList() {
        @Override/* w ww.  j  a va2s  .  c om*/
        public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
            ListModel model = getModel();
            int max = model.getSize();

            if ((prefix == null) || (startIndex < 0) || (startIndex >= max)) {
                throw new IllegalArgumentException();
            }

            // start search from the next element before/after the selected element
            boolean backwards = (bias == Position.Bias.Backward);

            for (int i = startIndex; backwards ? (i >= 0) : (i < max); i += (backwards ? (-1) : 1)) {
                String filename = fileChooser.getName((FileObject) model.getElementAt(i));

                if (filename.regionMatches(true, 0, prefix, 0, prefix.length())) {
                    return i;
                }
            }

            return -1;
        }
    };

    aList.setCellRenderer(new FileRenderer());
    aList.setLayoutOrientation(JList.VERTICAL_WRAP);

    // 4835633 : tell BasicListUI that this is a file list
    aList.putClientProperty("List.isFileList", Boolean.TRUE);

    if (listViewWindowsStyle) {
        aList.addFocusListener(repaintListener);
    }

    updateListRowCount(aList);

    getModel().addListDataListener(new ListDataListener() {
        public void intervalAdded(ListDataEvent e) {
            updateListRowCount(aList);
        }

        public void intervalRemoved(ListDataEvent e) {
            updateListRowCount(aList);
        }

        public void contentsChanged(ListDataEvent e) {
            if (isShowing()) {
                clearSelection();
            }

            updateListRowCount(aList);
        }
    });

    getModel().addPropertyChangeListener(this);

    if (fileChooser.isMultiSelectionEnabled()) {
        aList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    } else {
        aList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    aList.setModel(getModel());

    aList.addListSelectionListener(createListSelectionListener());
    aList.addMouseListener(getMouseHandler());

    JScrollPane scrollpane = new JScrollPane(aList);

    if (listViewBackground != null) {
        aList.setBackground(listViewBackground);
    }

    if (listViewBorder != null) {
        scrollpane.setBorder(listViewBorder);
    }

    p.add(scrollpane, BorderLayout.CENTER);

    return p;
}

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

/**
 * Constructor of the Training Module GUI.
 * //from   ww  w  .jav  a 2 s  .  co  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:gtu._work.ui.PropertyEditUI.java

private void initGUI() {
    try {/*from  w  ww . j  a  va  2  s .c o  m*/
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        BorderLayout thisLayout = new BorderLayout();
        this.setTitle("PropertyEditUI");
        getContentPane().setLayout(thisLayout);
        {
            jMenuBar1 = new JMenuBar();
            setJMenuBar(jMenuBar1);
            {
                jMenu1 = new JMenu();
                jMenuBar1.add(jMenu1);
                jMenu1.setText("File");
                {
                    jMenuItem1 = new JMenuItem();
                    jMenu1.add(jMenuItem1);
                    jMenuItem1.setText("open directory");
                    jMenuItem1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            File file = JCommonUtil._jFileChooser_selectDirectoryOnly();
                            loadCurrentFile(file);
                        }
                    });
                }
                {
                    openDirectoryAndChildren = new JMenuItem();
                    jMenu1.add(openDirectoryAndChildren);
                    openDirectoryAndChildren.setText("open directory and children");
                    openDirectoryAndChildren.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            System.out.println("openDirectoryAndChildren.actionPerformed, event=" + evt);
                            File file = JCommonUtil._jFileChooser_selectDirectoryOnly();
                            if (file == null) {
                                // file =
                                // PropertiesUtil.getJarCurrentPath(getClass());//XXX
                                file = new File("D:\\my_tool\\english");
                                JCommonUtil._jOptionPane_showMessageDialog_info("load C:\\L-CONFIG !");
                            }
                            DefaultListModel model = new DefaultListModel();
                            List<File> list = new ArrayList<File>();
                            FileUtil.searchFileMatchs(file, ".*\\.properties", list);
                            for (File f : list) {
                                File_ ff = new File_();
                                ff.file = f;
                                model.addElement(ff);
                            }
                            backupFileList = list;
                            fileList.setModel(model);
                        }
                    });
                }
                {
                    jMenuItem2 = new JMenuItem();
                    jMenu1.add(jMenuItem2);
                    jMenuItem2.setText("save");
                    jMenuItem2.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            System.out.println("jMenu3.actionPerformed, event=" + evt);
                            if (currentFile == null) {
                                return;
                            }
                            if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                    "save to " + currentFile.getName(), "SAVE")) {
                                try {
                                    Properties prop = new Properties();
                                    // try {
                                    // prop.load(new
                                    // FileInputStream(currentFile));
                                    // } catch (Exception e) {
                                    // e.printStackTrace();
                                    // JCommonUtil.handleException(e);
                                    // return;
                                    // }
                                    loadModelToProperties(prop);
                                    prop.store(new FileOutputStream(currentFile), getTitle());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    JCommonUtil.handleException(e);
                                }
                            }
                        }
                    });
                }
                {
                    jMenuItem3 = new JMenuItem();
                    jMenu1.add(jMenuItem3);
                    jMenuItem3.setText("save to target");
                    jMenuItem3.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            File file = JFileChooserUtil.newInstance().selectFileOnly().showSaveDialog()
                                    .getApproveSelectedFile();
                            if (file == null) {
                                JCommonUtil._jOptionPane_showMessageDialog_error("file name is not correct!");
                                return;
                            }
                            if (!file.getName().contains(".properties")) {
                                file = new File(file.getParent(), file.getName() + ".properties");
                            }
                            try {
                                Properties prop = new Properties();
                                // try {
                                // prop.load(new
                                // FileInputStream(currentFile));
                                // } catch (Exception e) {
                                // e.printStackTrace();
                                // JCommonUtil.handleException(e);
                                // return;
                                // }
                                loadModelToProperties(prop);
                                prop.store(new FileOutputStream(file), getTitle());
                            } catch (Exception e) {
                                e.printStackTrace();
                                JCommonUtil.handleException(e);
                            }
                        }
                    });
                }
                {
                    jMenuItem4 = new JMenuItem();
                    jMenu1.add(jMenuItem4);
                    jMenuItem4.setText("save file(sorted)");
                    jMenuItem4.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            if (currentFile == null) {
                                return;
                            }
                            try {
                                BufferedReader reader = new BufferedReader(
                                        new InputStreamReader(new FileInputStream(currentFile)));
                                List<String> sortList = new ArrayList<String>();
                                for (String line = null; (line = reader.readLine()) != null;) {
                                    sortList.add(line);
                                }
                                reader.close();
                                Collections.sort(sortList);
                                StringBuilder sb = new StringBuilder();
                                for (String line : sortList) {
                                    sb.append(line + "\n");
                                }
                                FileUtil.saveToFile(currentFile, sb.toString(), "UTF8");
                            } catch (FileNotFoundException e) {
                                e.printStackTrace();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                {
                    jMenuItem5 = new JMenuItem();
                    jMenu1.add(jMenuItem5);
                    jMenuItem5.setText("");
                    jMenuItem5.addActionListener(new ActionListener() {
                        private void setMeaning(String meaning, int rowPos) {
                            propTable.getRowSorter().getModel().setValueAt(meaning, rowPos, 2);
                        }

                        private void setMeaningEn1(String english, int rowPos, List<String> errSb) {
                            EnglishTester_Diectory eng = new EnglishTester_Diectory();
                            try {
                                WordInfo wordInfo = eng.parseToWordInfo(english);
                                String meaning = getChs2Big5(wordInfo.getMeaning());
                                if (hasChinese(meaning)) {
                                    setMeaning(meaning, rowPos);
                                } else {
                                    setMeaningEn2(english, rowPos, errSb);
                                }
                            } catch (Exception e) {
                                errSb.add(english);
                                e.printStackTrace();
                            }
                        }

                        private void setMeaningEn2(String english, int rowPos, List<String> errSb) {
                            EnglishTester_Diectory2 eng2 = new EnglishTester_Diectory2();
                            try {
                                WordInfo2 wordInfo = eng2.parseToWordInfo(english);
                                String meaning = getChs2Big5(StringUtils.join(wordInfo.getMeaningList(), ";"));
                                setMeaning(meaning, rowPos);
                            } catch (Exception e) {
                                errSb.add(english);
                                e.printStackTrace();
                            }
                        }

                        private boolean hasChinese(String val) {
                            return new StringUtil_().getChineseWord(val, true).length() > 0;
                        }

                        private Properties loadFromMemoryBank() {
                            try {
                                Properties prop = new Properties();
                                File f1 = new File(
                                        "D:/gtu001_dropbox/Dropbox/Apps/gtu001_test/etc_config/EnglishSearchUI_MemoryBank.properties");
                                File f2 = new File(
                                        "e:/gtu001_dropbox/Dropbox/Apps/gtu001_test/etc_config/EnglishSearchUI_MemoryBank.properties");
                                for (File f : new File[] { f1, f2 }) {
                                    if (f.exists()) {
                                        HermannEbbinghaus_Memory memory = new HermannEbbinghaus_Memory();
                                        memory.init(f);
                                        List<MemData> memLst = memory.getAllMemData(true);
                                        for (MemData d : memLst) {
                                            prop.setProperty(d.getKey(), getChs2Big5(d.getRemark()));
                                        }
                                        break;
                                    }
                                }
                                return prop;
                            } catch (Exception ex) {
                                throw new RuntimeException(ex);
                            }
                        }

                        public void actionPerformed(ActionEvent evt) {
                            if (currentFile == null) {
                                return;
                            }

                            // Properties memoryProp = loadFromMemoryBank();
                            Properties memoryProp = new Properties();

                            List<String> errSb = new ArrayList<String>();
                            for (int row = 0; row < propTable.getModel().getRowCount(); row++) {
                                int rowPos = propTable.getRowSorter().convertRowIndexToModel(row);
                                String english = StringUtils.trimToEmpty(
                                        (String) propTable.getRowSorter().getModel().getValueAt(rowPos, 1))
                                        .toLowerCase();
                                String desc = (String) propTable.getRowSorter().getModel().getValueAt(rowPos,
                                        2);

                                if (memoryProp.containsKey(english)
                                        && StringUtils.isNotBlank(memoryProp.getProperty(english))) {
                                    setMeaning(memoryProp.getProperty(english), rowPos);
                                } else {
                                    if (StringUtils.isBlank(desc) || !hasChinese(desc)) {
                                        if (!english.contains(" ")) {
                                            setMeaningEn1(english, rowPos, errSb);
                                        } else {
                                            setMeaningEn2(english, rowPos, errSb);
                                        }
                                    }
                                }

                                if (StringUtils.trimToEmpty(desc).contains("?")) {
                                    setMeaning("", rowPos);
                                }
                            }
                            if (!errSb.isEmpty()) {
                                JCommonUtil._jOptionPane_showMessageDialog_error(":\n" + errSb);
                            }
                        }
                    });
                }

                {
                    JMenuItem jMenuItem6 = new JMenuItem();
                    jMenu1.add(jMenuItem6);
                    jMenuItem6.setText("");
                    jMenuItem6.addActionListener(new ActionListener() {
                        private void setMeaning(String meaning, int rowPos) {
                            propTable.getRowSorter().getModel().setValueAt(meaning, rowPos, 2);
                        }

                        public void actionPerformed(ActionEvent evt) {
                            for (int row = 0; row < propTable.getModel().getRowCount(); row++) {
                                int rowPos = propTable.getRowSorter().convertRowIndexToModel(row);
                                String english = StringUtils.trimToEmpty(
                                        (String) propTable.getRowSorter().getModel().getValueAt(rowPos, 1))
                                        .toLowerCase();
                                String desc = (String) propTable.getRowSorter().getModel().getValueAt(rowPos,
                                        2);

                                if (StringUtils.trimToEmpty(desc).contains("?")) {
                                    setMeaning("", rowPos);
                                }
                            }
                        }
                    });
                }
            }
        }
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel2 = new JPanel();
                BorderLayout jPanel2Layout = new BorderLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("editor", null, jPanel2, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel2.add(jScrollPane1, BorderLayout.CENTER);
                    jScrollPane1.setPreferredSize(new java.awt.Dimension(550, 314));
                    {
                        TableModel propTableModel = new DefaultTableModel(
                                new String[][] { { "", "", "" }, { "", "", "" } },
                                new String[] { "index", "Key", "value" });
                        propTable = new JTable();
                        JTableUtil.defaultSetting_AutoResize(propTable);
                        jScrollPane1.setViewportView(propTable);
                        propTable.setModel(propTableModel);
                        propTable.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                JTableUtil xxxxxx = JTableUtil.newInstance(propTable);
                                int[] rows = xxxxxx.getSelectedRows();
                                for (int ii : rows) {
                                    System.out.println(xxxxxx.getModel().getValueAt(ii, 1));
                                }
                                JPopupMenuUtil.newInstance(propTable).applyEvent(evt)
                                        .addJMenuItem(JTableUtil.newInstance(propTable).getDefaultJMenuItems())
                                        .show();
                            }
                        });
                    }
                }
                {
                    queryText = new JTextField();
                    jPanel2.add(queryText, BorderLayout.NORTH);
                    queryText.getDocument()
                            .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() {

                                @Override
                                public void process(DocumentEvent event) {
                                    if (currentFile == null) {
                                        return;
                                    }
                                    Properties prop = new Properties();
                                    try {
                                        prop.load(new FileInputStream(currentFile));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        JCommonUtil.handleException(e);
                                        return;
                                    }
                                    loadPropertiesToModel(prop);
                                    String text = JCommonUtil.getDocumentText(event);
                                    Pattern pattern = null;
                                    try {
                                        pattern = Pattern.compile(text);
                                    } catch (Exception ex) {
                                    }

                                    DefaultTableModel model = JTableUtil.newInstance(propTable).getModel();
                                    for (int ii = 0; ii < model.getRowCount(); ii++) {
                                        String key = (String) model.getValueAt(ii, 1);
                                        String value = (String) model.getValueAt(ii, 2);
                                        if (key.contains(text)) {
                                            continue;
                                        }
                                        if (value.contains(text)) {
                                            continue;
                                        }
                                        if (pattern != null) {
                                            if (pattern.matcher(key).find()) {
                                                continue;
                                            }
                                            if (pattern.matcher(value).find()) {
                                                continue;
                                            }
                                        }
                                        model.removeRow(propTable.convertRowIndexToModel(ii));
                                        ii--;
                                    }
                                }
                            }));
                }
            }
            {
                jPanel3 = new JPanel();
                BorderLayout jPanel3Layout = new BorderLayout();
                jPanel3.setLayout(jPanel3Layout);
                jTabbedPane1.addTab("folder", null, jPanel3, null);
                {
                    jScrollPane2 = new JScrollPane();
                    jPanel3.add(jScrollPane2, BorderLayout.CENTER);
                    jScrollPane2.setPreferredSize(new java.awt.Dimension(550, 314));
                    {
                        fileList = new JList();
                        jScrollPane2.setViewportView(fileList);
                        fileList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                JListUtil.newInstance(fileList).defaultJListKeyPressed(evt);
                            }
                        });
                        fileList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                final File_ file = JListUtil.getLeadSelectionObject(fileList);

                                if (evt.getButton() == MouseEvent.BUTTON1) {
                                    Properties prop = new Properties();
                                    currentFile = file.file;
                                    setTitle(currentFile.getName());
                                    try {
                                        prop.load(new FileInputStream(file.file));
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    loadPropertiesToModel(prop);
                                }

                                if (evt.getButton() == MouseEvent.BUTTON1 && evt.getClickCount() == 2) {
                                    try {
                                        Runtime.getRuntime().exec(String.format("cmd /c \"%s\"", file.file));
                                    } catch (IOException e1) {
                                        e1.printStackTrace();
                                    }
                                }

                                final File parent = file.file.getParentFile();
                                JMenuItem openTargetDir = new JMenuItem();
                                openTargetDir.setText("open : " + parent);
                                openTargetDir.addActionListener(new ActionListener() {
                                    @Override
                                    public void actionPerformed(ActionEvent e) {
                                        try {
                                            Desktop.getDesktop().open(parent);
                                        } catch (IOException e1) {
                                            JCommonUtil.handleException(e1);
                                        }
                                    }
                                });

                                JPopupMenuUtil.newInstance(fileList).addJMenuItem(openTargetDir).applyEvent(evt)
                                        .show();
                            }
                        });
                    }
                }
                {
                    fileQueryText = new JTextField();
                    jPanel3.add(fileQueryText, BorderLayout.NORTH);
                    fileQueryText.getDocument()
                            .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() {
                                @Override
                                public void process(DocumentEvent event) {
                                    String text = JCommonUtil.getDocumentText(event);
                                    DefaultListModel model = new DefaultListModel();
                                    for (File f : backupFileList) {
                                        if (f.getName().contains(text)) {
                                            File_ ff = new File_();
                                            ff.file = f;
                                            model.addElement(ff);
                                        }
                                    }
                                    fileList.setModel(model);
                                }
                            }));
                }
                {
                    contentQueryText = new JTextField();
                    jPanel3.add(contentQueryText, BorderLayout.SOUTH);
                    contentQueryText.addActionListener(new ActionListener() {

                        void addModel(File f, DefaultListModel model) {
                            File_ ff = new File_();
                            ff.file = f;
                            model.addElement(ff);
                        }

                        public void actionPerformed(ActionEvent evt) {
                            DefaultListModel model = new DefaultListModel();
                            String text = contentQueryText.getText();
                            if (StringUtils.isEmpty(contentQueryText.getText())) {
                                return;
                            }
                            Pattern pattern = Pattern.compile(text);
                            Properties pp = null;
                            for (File f : backupFileList) {
                                pp = new Properties();
                                try {
                                    pp.load(new FileInputStream(f));
                                    for (String key : pp.stringPropertyNames()) {
                                        if (key.isEmpty()) {
                                            continue;
                                        }
                                        if (pp.getProperty(key) == null || pp.getProperty(key).isEmpty()) {
                                            continue;
                                        }
                                        if (key.contains(text)) {
                                            addModel(f, model);
                                            break;
                                        }
                                        if (pp.getProperty(key).contains(text)) {
                                            addModel(f, model);
                                            break;
                                        }
                                        if (pattern.matcher(key).find()) {
                                            addModel(f, model);
                                            break;
                                        }
                                        if (pattern.matcher(pp.getProperty(key)).find()) {
                                            addModel(f, model);
                                            break;
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            fileList.setModel(model);
                        }
                    });
                }
            }
        }
        JCommonUtil.setJFrameIcon(this, "resource/images/ico/english.ico");
        JCommonUtil.setJFrameCenter(this);
        pack();
        this.setSize(571, 408);

        loadCurrentFile(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:eu.crisis_economics.abm.dashboard.Page_Parameters.java

@SuppressWarnings("serial")
private JPanel createParamsweepGUI() {

    // left/*from ww w.  jav  a2s  .  c o  m*/
    parameterList = new JList();
    parameterList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    new ListAction(parameterList, new AbstractAction() {
        public void actionPerformed(final ActionEvent event) {
            final AvailableParameter selectedParameter = (AvailableParameter) parameterList.getSelectedValue();
            addParameterToTree(new AvailableParameter[] { selectedParameter }, parameterTreeBranches.get(0));
            enableDisableParameterCombinationButtons();
        }
    });
    parameterList.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {
            if (!parameterList.isSelectionEmpty()) {
                boolean success = true;
                if (editedNode != null)
                    success = modify();

                if (success) {
                    cancelAllSelectionBut(parameterList);
                    resetSettings();
                    updateDescriptionField(parameterList.getSelectedValues());
                    enableDisableParameterCombinationButtons();
                } else
                    parameterList.clearSelection();
            }
        }
    });

    final JScrollPane parameterListPane = new JScrollPane(parameterList);
    parameterListPane.setBorder(BorderFactory.createTitledBorder("")); // for rounded border
    parameterListPane.setPreferredSize(new Dimension(300, 300));

    final JPanel parametersPanel = FormsUtils.build("p ' p:g", "[DialogBorder]00||" + "12||" + "34||" +
    //                                          "56||" + 
            "55||" + "66 f:p:g", new FormsUtils.Separator("<html><b>General parameters</b></html>"),
            NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsFieldPSW, NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT,
            numberTimestepsIgnoredPSW,
            //                                          UPDATE_CHARTS_LABEL_TEXT,onLineChartsCheckBoxPSW,
            new FormsUtils.Separator("<html><b>Model parameters</b></html>"), parameterListPane).getPanel();

    combinationsPanel = new JPanel(new GridLayout(0, 1, 5, 5));
    combinationsScrPane = new JScrollPane(combinationsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    combinationsScrPane.setBorder(null);
    combinationsScrPane.setPreferredSize(new Dimension(550, 500));

    parameterDescriptionLabel = new JXLabel();
    parameterDescriptionLabel.setLineWrap(true);
    parameterDescriptionLabel.setVerticalAlignment(SwingConstants.TOP);
    final JScrollPane descriptionScrollPane = new JScrollPane(parameterDescriptionLabel);
    descriptionScrollPane.setBorder(BorderFactory.createTitledBorder(null, "Description", TitledBorder.LEADING,
            TitledBorder.BELOW_TOP));
    descriptionScrollPane.setPreferredSize(
            new Dimension(PARAMETER_DESCRIPTION_LABEL_WIDTH, PARAMETER_DESCRIPTION_LABEL_HEIGHT));
    descriptionScrollPane.setViewportBorder(null);

    final JButton addNewBoxButton = new JButton("Add new combination");
    addNewBoxButton.setActionCommand(ACTIONCOMMAND_ADD_BOX);

    final JPanel left = FormsUtils.build("p ~ f:p:g ~ p", "011 f:p:g ||" + "0_2 p", parametersPanel,
            combinationsScrPane, addNewBoxButton).getPanel();
    left.setBorder(BorderFactory.createTitledBorder(null, "Specify parameter combinations",
            TitledBorder.LEADING, TitledBorder.BELOW_TOP));
    Style.registerCssClasses(left, Dashboard.CSS_CLASS_COMMON_PANEL);

    final JPanel leftAndDesc = new JPanel(new BorderLayout());
    leftAndDesc.add(left, BorderLayout.CENTER);
    leftAndDesc.add(descriptionScrollPane, BorderLayout.SOUTH);
    Style.registerCssClasses(leftAndDesc, Dashboard.CSS_CLASS_COMMON_PANEL);

    // right
    editedParameterText = new JLabel(ORIGINAL_TEXT);
    editedParameterText.setPreferredSize(new Dimension(280, 40));
    constDef = new JRadioButton("Constant");
    listDef = new JRadioButton("List");
    incrDef = new JRadioButton("Increment");

    final JPanel rightTop = FormsUtils.build("p:g", "[DialogBorder]0||" + "1||" + "2||" + "3",
            editedParameterText, constDef, listDef, incrDef).getPanel();

    Style.registerCssClasses(rightTop, Dashboard.CSS_CLASS_COMMON_PANEL);

    constDefField = new JTextField();
    final JPanel constDefPanel = FormsUtils
            .build("p ~ p:g", "[DialogBorder]01 p", "Constant value: ", CellConstraints.TOP, constDefField)
            .getPanel();

    listDefArea = new JTextArea();
    final JScrollPane listDefScr = new JScrollPane(listDefArea,
            ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    final JPanel listDefPanel = FormsUtils.build("p ~ p:g", "[DialogBorder]01|" + "_1 f:p:g||" + "_2 p",
            "Value list: ", listDefScr, "(Separate values with spaces!)").getPanel();

    incrStartValueField = new JTextField();
    incrEndValueField = new JTextField();
    incrStepField = new JTextField();

    final JPanel incrDefPanel = FormsUtils.build("p ~ p:g", "[DialogBorder]01||" + "23||" + "45",
            "Start value: ", incrStartValueField, "End value: ", incrEndValueField, "Step: ", incrStepField)
            .getPanel();

    enumDefBox = new JComboBox(new DefaultComboBoxModel());
    final JPanel enumDefPanel = FormsUtils
            .build("p ~ p:g", "[DialogBorder]01 p", "Constant value:", CellConstraints.TOP, enumDefBox)
            .getPanel();

    submodelTypeBox = new JComboBox();
    final JPanel submodelTypePanel = FormsUtils
            .build("p ~ p:g", "[DialogBorder]01", "Constant value:", CellConstraints.TOP, submodelTypeBox)
            .getPanel();

    fileTextField = new JTextField();
    fileTextField.addKeyListener(new KeyAdapter() {
        public void keyTyped(final KeyEvent e) {
            final char character = e.getKeyChar();
            final File file = new File(Character.isISOControl(character) ? fileTextField.getText()
                    : fileTextField.getText() + character);
            fileTextField.setToolTipText(file.getAbsolutePath());
        }
    });
    fileBrowseButton = new JButton(BROWSE_BUTTON_TEXT);
    fileBrowseButton.setActionCommand(ACTIONCOMMAND_BROWSE);
    final JPanel fileDefPanel = FormsUtils
            .build("p ~ p:g ~p", "[DialogBorder]012", "File:", fileTextField, fileBrowseButton).getPanel();

    constDefPanel.setName("CONST");
    listDefPanel.setName("LIST");
    incrDefPanel.setName("INCREMENT");
    enumDefPanel.setName("ENUM");
    submodelTypePanel.setName("SUBMODEL");
    fileDefPanel.setName("FILE");

    Style.registerCssClasses(constDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(listDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(incrDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(enumDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(submodelTypePanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    Style.registerCssClasses(fileDefPanel, Dashboard.CSS_CLASS_COMMON_PANEL);

    rightMiddle = new JPanel(new CardLayout());
    Style.registerCssClasses(rightMiddle, Dashboard.CSS_CLASS_COMMON_PANEL);
    rightMiddle.add(constDefPanel, constDefPanel.getName());
    rightMiddle.add(listDefPanel, listDefPanel.getName());
    rightMiddle.add(incrDefPanel, incrDefPanel.getName());
    rightMiddle.add(enumDefPanel, enumDefPanel.getName());
    rightMiddle.add(submodelTypePanel, submodelTypePanel.getName());
    rightMiddle.add(fileDefPanel, fileDefPanel.getName());

    modifyButton = new JButton("Modify");
    cancelButton = new JButton("Cancel");

    final JPanel rightBottom = FormsUtils
            .build("p:g p ~ p ~ p:g", "[DialogBorder]_01_ p", modifyButton, cancelButton).getPanel();

    Style.registerCssClasses(rightBottom, Dashboard.CSS_CLASS_COMMON_PANEL);

    final JPanel right = new JPanel(new BorderLayout());
    right.add(rightTop, BorderLayout.NORTH);
    right.add(rightMiddle, BorderLayout.CENTER);
    right.add(rightBottom, BorderLayout.SOUTH);
    right.setBorder(BorderFactory.createTitledBorder(null, "Parameter settings", TitledBorder.LEADING,
            TitledBorder.BELOW_TOP));

    Style.registerCssClasses(right, Dashboard.CSS_CLASS_COMMON_PANEL);

    // the whole paramsweep panel

    final JPanel content = FormsUtils.build("p:g p", "01 f:p:g", leftAndDesc, right).getPanel();
    Style.registerCssClasses(content, Dashboard.CSS_CLASS_COMMON_PANEL);

    sweepPanel = new JPanel();
    Style.registerCssClasses(sweepPanel, Dashboard.CSS_CLASS_COMMON_PANEL);
    sweepPanel.setLayout(new BorderLayout());
    final JScrollPane sp = new JScrollPane(content);
    sp.setBorder(null);
    sp.setViewportBorder(null);
    sweepPanel.add(sp, BorderLayout.CENTER);

    GUIUtils.createButtonGroup(constDef, listDef, incrDef);
    constDef.setSelected(true);
    constDef.setActionCommand("CONST");
    listDef.setActionCommand("LIST");
    incrDef.setActionCommand("INCREMENT");

    constDefField.setActionCommand("CONST_FIELD");
    incrStartValueField.setActionCommand("START_FIELD");
    incrEndValueField.setActionCommand("END_FIELD");
    incrStepField.setActionCommand("STEP_FIELD");

    modifyButton.setActionCommand("EDIT");
    cancelButton.setActionCommand("CANCEL");

    listDefArea.setLineWrap(true);
    listDefArea.setWrapStyleWord(true);
    listDefScr.setPreferredSize(new Dimension(100, 200));

    GUIUtils.addActionListener(this, modifyButton, cancelButton, constDef, listDef, incrDef, constDefField,
            incrStartValueField, incrEndValueField, incrStepField, addNewBoxButton, submodelTypeBox,
            fileBrowseButton);

    return sweepPanel;
}

From source file:gtu._work.ui.SvnLastestCommitInfoUI.java

private void initGUI() {
    try {/*from  w  ww .ja  va  2s .com*/
        BorderLayout thisLayout = new BorderLayout();
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(thisLayout);
        this.setFocusable(false);
        this.setTitle("SVN lastest commit wather");
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("svn dir", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        TableModel svnTableModel = new DefaultTableModel();
                        svnTable = new JTable();
                        jScrollPane1.setViewportView(svnTable);
                        svnTable.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                try {
                                    if (evt.getButton() == 3) {
                                        final List<File> list = new ArrayList<File>();
                                        SvnFile svnFile = null;
                                        final StringBuilder sb = new StringBuilder();
                                        for (int row : svnTable.getSelectedRows()) {
                                            svnFile = (SvnFile) svnTable.getModel().getValueAt(
                                                    svnTable.getRowSorter().convertRowIndexToModel(row),
                                                    SvnTableColumn.SVN_FILE.pos);
                                            list.add(svnFile.file);
                                            sb.append(svnFile.file.getName() + ",");
                                        }
                                        if (sb.length() > 200) {
                                            sb.delete(200, sb.length() - 1);
                                        }
                                        JMenuItem copySelectedMeun = new JMenuItem();
                                        copySelectedMeun.setText("copy selected file : " + list.size());
                                        copySelectedMeun.addActionListener(new ActionListener() {
                                            public void actionPerformed(ActionEvent e) {
                                                if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                        .newInstance().iconPlainMessage().confirmButtonYesNo()
                                                        .showConfirmDialog(
                                                                "are you sure copy files :\n" + sb + "\n???",
                                                                "COPY SELECTED FILE : " + list.size())) {
                                                    return;
                                                }
                                                final File copyToDir = JFileChooserUtil.newInstance()
                                                        .selectDirectoryOnly().showOpenDialog()
                                                        .getApproveSelectedFile();
                                                if (copyToDir == null) {
                                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                                            .showMessageDialog("dir folder is not correct!",
                                                                    "ERROR");
                                                    return;
                                                }
                                                new Thread(Thread.currentThread().getThreadGroup(),
                                                        new Runnable() {
                                                            public void run() {
                                                                StringBuilder errMsg = new StringBuilder();
                                                                int errCount = 0;
                                                                for (File f : list) {
                                                                    try {
                                                                        FileUtil.copyFile(f, new File(copyToDir,
                                                                                f.getName()));
                                                                    } catch (IOException e) {
                                                                        e.printStackTrace();
                                                                        errCount++;
                                                                        errMsg.append(f + "\n");
                                                                    }
                                                                }

                                                                JOptionPaneUtil.newInstance().iconPlainMessage()
                                                                        .showMessageDialog(
                                                                                "copy completed!\nerror : "
                                                                                        + errCount
                                                                                        + "\nerror list : \n"
                                                                                        + errMsg,
                                                                                "COMPLETED");
                                                            }
                                                        }, "copySelectedFiles_" + hashCode()).start();
                                            }
                                        });

                                        JMenuItem copySelectedOringTreeMeun = new JMenuItem();
                                        copySelectedOringTreeMeun
                                                .setText("copy selected file (orign tree): " + list.size());
                                        copySelectedOringTreeMeun.addActionListener(new ActionListener() {
                                            public void actionPerformed(ActionEvent e) {
                                                if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                        .newInstance().iconPlainMessage().confirmButtonYesNo()
                                                        .showConfirmDialog(
                                                                "are you sure copy files :\n" + sb + "\n???",
                                                                "COPY SELECTED FILE : " + list.size())) {
                                                    return;
                                                }
                                                final File copyToDir = JFileChooserUtil.newInstance()
                                                        .selectDirectoryOnly().showOpenDialog()
                                                        .getApproveSelectedFile();
                                                if (copyToDir == null) {
                                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                                            .showMessageDialog("dir folder is not correct!",
                                                                    "ERROR");
                                                    return;
                                                }
                                                new Thread(Thread.currentThread().getThreadGroup(),
                                                        new Runnable() {
                                                            public void run() {
                                                                File srcBaseDir = FileUtil
                                                                        .exportReceiveBaseDir(list);
                                                                int cutLength = 0;
                                                                if (srcBaseDir != null) {
                                                                    cutLength = srcBaseDir.getAbsolutePath()
                                                                            .length();
                                                                }

                                                                StringBuilder errMsg = new StringBuilder();
                                                                int errCount = 0;
                                                                File newFile = null;
                                                                for (File f : list) {
                                                                    try {
                                                                        newFile = new File(copyToDir + "/"
                                                                                + f.getAbsolutePath()
                                                                                        .substring(cutLength),
                                                                                f.getName());
                                                                        newFile.getParentFile().mkdirs();
                                                                        FileUtil.copyFile(f, newFile);
                                                                    } catch (IOException e) {
                                                                        e.printStackTrace();
                                                                        errCount++;
                                                                        errMsg.append(f + "\n");
                                                                    }
                                                                }

                                                                JOptionPaneUtil.newInstance().iconPlainMessage()
                                                                        .showMessageDialog(
                                                                                "copy completed!\nerror : "
                                                                                        + errCount
                                                                                        + "\nerror list : \n"
                                                                                        + errMsg,
                                                                                "COMPLETED");
                                                            }
                                                        }, "copySelectedFiles_orignTree_" + hashCode()).start();
                                            }
                                        });

                                        JPopupMenuUtil.newInstance(svnTable).applyEvent(evt)
                                                .addJMenuItem(copySelectedMeun, copySelectedOringTreeMeun)
                                                .show();
                                    }

                                    if (!JMouseEventUtil.buttonLeftClick(2, evt)) {
                                        return;
                                    }
                                    int row = JTableUtil.newInstance(svnTable).getSelectedRow();
                                    SvnFile svnFile = (SvnFile) svnTable.getModel().getValueAt(row,
                                            SvnTableColumn.SVN_FILE.pos);
                                    String command = String.format("cmd /c call \"%s\"", svnFile.file);
                                    System.out.println(command);
                                    try {
                                        Runtime.getRuntime().exec(command);
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                        svnTable.setModel(svnTableModel);
                        JTableUtil.defaultSetting(svnTable);
                    }
                }
                {
                    jPanel3 = new JPanel();
                    jPanel1.add(jPanel3, BorderLayout.NORTH);
                    jPanel3.setPreferredSize(new java.awt.Dimension(379, 35));
                    {
                        filterText = new JTextField();
                        jPanel3.add(filterText);
                        filterText.setPreferredSize(new java.awt.Dimension(258, 24));
                        filterText.getDocument()
                                .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() {
                                    public void process(DocumentEvent event) {
                                        try {
                                            String scanText = JCommonUtil.getDocumentText(event);
                                            reloadSvnTable(scanText, _defaultScanProcess);
                                        } catch (Exception ex) {
                                            JCommonUtil.handleException(ex);
                                        }
                                    }
                                }));
                    }
                    {
                        choiceSvnDir = new JButton();
                        jPanel3.add(choiceSvnDir);
                        choiceSvnDir.setText("choice svn dir");
                        choiceSvnDir.setPreferredSize(new java.awt.Dimension(154, 24));
                        choiceSvnDir.addActionListener(new ActionListener() {

                            Pattern svnOutputPattern = Pattern
                                    .compile("\\s*(\\d*)\\s+(\\d+)\\s+(\\w+)\\s+([\\S]+)");

                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    System.out.println("choiceSvnDir.actionPerformed, event=" + evt);
                                    final File svnDir = JFileChooserUtil.newInstance().selectDirectoryOnly()
                                            .showOpenDialog().getApproveSelectedFile();
                                    if (svnDir == null) {
                                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                                .showMessageDialog("dir is not correct!", "ERROR");
                                        return;
                                    }
                                    Thread thread = new Thread(Thread.currentThread().getThreadGroup(),
                                            new Runnable() {
                                                public void run() {
                                                    long startTime = System.currentTimeMillis();
                                                    String command = String
                                                            .format("cmd /c svn status -v \"%s\"", svnDir);
                                                    Matcher matcher = null;
                                                    try {
                                                        long projectLastestVersion = 0;
                                                        SvnFile svnFile = null;
                                                        Process process = Runtime.getRuntime().exec(command);
                                                        BufferedReader reader = new BufferedReader(
                                                                new InputStreamReader(process.getInputStream(),
                                                                        "BIG5"));
                                                        for (String line = null; (line = reader
                                                                .readLine()) != null;) {
                                                            matcher = svnOutputPattern.matcher(line);
                                                            if (matcher.find()) {
                                                                try {
                                                                    if (StringUtils
                                                                            .isNotBlank(matcher.group(1))) {
                                                                        projectLastestVersion = Math.max(
                                                                                projectLastestVersion,
                                                                                Long.parseLong(
                                                                                        matcher.group(1)));
                                                                    }
                                                                    svnFile = new SvnFile();
                                                                    svnFile.lastestVersion = Long
                                                                            .parseLong(matcher.group(2));
                                                                    svnFile.author = matcher.group(3);
                                                                    svnFile.filePath = matcher.group(4);
                                                                    svnFile.file = new File(svnFile.filePath);
                                                                    svnFile.fileName = svnFile.file.getName();
                                                                    svnFileSet.add(svnFile);
                                                                    authorSet.add(svnFile.author);
                                                                    String extension = null;
                                                                    if (svnFile.file.isFile()
                                                                            && (extension = getExtension(
                                                                                    svnFile.fileName)) != null) {
                                                                        fileExtenstionSet.add(extension);
                                                                    }
                                                                } catch (Exception ex) {
                                                                    ex.printStackTrace();
                                                                }
                                                            } else {
                                                                System.out.println("ignore : " + line);
                                                            }
                                                        }
                                                        reader.close();
                                                        lastestVersion = projectLastestVersion;
                                                        projectName = svnDir.getName();
                                                        resetUiAndShowMessage(startTime, projectName,
                                                                projectLastestVersion);
                                                    } catch (IOException e) {
                                                        JCommonUtil.handleException(e);
                                                    }
                                                }
                                            }, "loadSvnLastest_" + this.hashCode());
                                    thread.setDaemon(true);
                                    thread.start();
                                    setTitle("sweeping...");
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }

                            String getExtension(String name) {
                                int pos = -1;
                                if ((pos = name.lastIndexOf(".")) != -1) {
                                    return name.substring(pos).toLowerCase();
                                }
                                return null;
                            }
                        });
                    }
                    {
                        jLabel1 = new JLabel();
                        jPanel3.add(jLabel1);
                        jLabel1.setText("match :");
                        jLabel1.setPreferredSize(new java.awt.Dimension(56, 22));
                    }
                    {
                        matchCount = new JLabel();
                        jPanel3.add(matchCount);
                        matchCount.setPreferredSize(new java.awt.Dimension(82, 22));
                    }
                }
            }
            {
                jPanel2 = new JPanel();
                FlowLayout jPanel2Layout = new FlowLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("config", null, jPanel2, null);
                {
                    DefaultComboBoxModel authorComboBoxModel = new DefaultComboBoxModel();
                    authorComboBox = new JComboBox();
                    jPanel2.add(authorComboBox);
                    authorComboBox.setModel(authorComboBoxModel);
                    authorComboBox.setPreferredSize(new java.awt.Dimension(260, 24));
                    authorComboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                Object author = authorComboBox.getSelectedItem();
                                if (author instanceof Map.Entry) {
                                    Map.Entry<?, ?> entry = (Map.Entry<?, ?>) author;
                                    reloadSvnTable((String) entry.getKey(), _authorScanProcess);
                                } else {
                                    reloadSvnTable((String) author, _authorScanProcess);
                                }
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    ComboBoxModel jComboBox1Model = new DefaultComboBoxModel();
                    fileExtensionComboBox = new JComboBox();
                    jPanel2.add(fileExtensionComboBox);
                    fileExtensionComboBox.setModel(jComboBox1Model);
                    fileExtensionComboBox.setPreferredSize(new java.awt.Dimension(186, 24));
                    fileExtensionComboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                String extension = (String) fileExtensionComboBox.getSelectedItem();
                                reloadSvnTable(extension, _fileExtensionScanProcess);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    jScrollPane2 = new JScrollPane();
                    jScrollPane2.setPreferredSize(new java.awt.Dimension(130, 200));
                    jPanel2.add(jScrollPane2);
                    {
                        DefaultListModel model = new DefaultListModel();
                        fileExtensionFilter = new JList();
                        jScrollPane2.setViewportView(fileExtensionFilter);
                        fileExtensionFilter.setModel(model);
                        fileExtensionFilter.addListSelectionListener(new ListSelectionListener() {
                            public void valueChanged(ListSelectionEvent evt) {
                                try {
                                    System.out
                                            .println(Arrays.toString(fileExtensionFilter.getSelectedValues()));
                                    String extensionStr = "";
                                    StringBuilder sb = new StringBuilder();
                                    for (Object val : fileExtensionFilter.getSelectedValues()) {
                                        sb.append(val + ",");
                                    }
                                    extensionStr = (sb.length() > 0 ? sb.deleteCharAt(sb.length() - 1) : sb)
                                            .toString();
                                    System.out.format("extensionStr = [%s]\n", extensionStr);
                                    multiExtendsionFilter.setName(extensionStr);
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                }
                {
                    multiExtendsionFilter = new JButton();
                    jPanel2.add(multiExtendsionFilter);
                    multiExtendsionFilter.setText("multi extension filter");
                    multiExtendsionFilter.setPreferredSize(new java.awt.Dimension(166, 34));
                    multiExtendsionFilter.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                reloadSvnTable(multiExtendsionFilter.getName(), _fileExtensionMultiScanProcess);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    loadAuthorReference = new JButton();
                    jPanel2.add(loadAuthorReference);
                    loadAuthorReference.setText("load author reference");
                    loadAuthorReference.setPreferredSize(new java.awt.Dimension(188, 35));
                    loadAuthorReference.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File file = JFileChooserUtil.newInstance().selectFileOnly().showOpenDialog()
                                        .getApproveSelectedFile();
                                if (file == null) {
                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                            .showMessageDialog("file is not correct!", "ERROR");
                                    return;
                                }
                                authorProps.load(new FileInputStream(file));
                                reloadAuthorComboBox();
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    saveCurrentData = new JButton();
                    jPanel2.add(saveCurrentData);
                    saveCurrentData.setText("save current data");
                    saveCurrentData.setPreferredSize(new java.awt.Dimension(166, 34));
                    saveCurrentData.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File saveDataConfig = new File(jarExistLocation, getSaveCurrentDataFileName());
                                ObjectOutputStream writer = new ObjectOutputStream(
                                        new FileOutputStream(saveDataConfig));
                                writer.writeObject(projectName);
                                writer.writeObject(authorSet);
                                writer.writeObject(fileExtenstionSet);
                                writer.writeObject(svnFileSet);
                                writer.writeObject(authorProps);
                                writer.writeObject(lastestVersion);
                                writer.flush();
                                writer.close();

                                JOptionPaneUtil.newInstance().iconInformationMessage()
                                        .showMessageDialog("current project : " + projectName
                                                + " save completed! \n" + saveDataConfig, "SUCCESS");
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
                {
                    loadDataFromFile = new JButton();
                    jPanel2.add(loadDataFromFile);
                    loadDataFromFile.setText("load data cfg");
                    loadDataFromFile.setPreferredSize(new java.awt.Dimension(165, 35));
                    loadDataFromFile.addActionListener(new ActionListener() {
                        @SuppressWarnings("unchecked")
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                File file = JFileChooserUtil.newInstance().selectFileOnly()
                                        .addAcceptFile(".cfg", ".cfg").showOpenDialog()
                                        .getApproveSelectedFile();
                                if (file == null) {
                                    JOptionPaneUtil.newInstance().iconErrorMessage()
                                            .showMessageDialog("file is not correct!", "ERROR");
                                    return;
                                }
                                long startTime = System.currentTimeMillis();
                                ObjectInputStream input = new ObjectInputStream(new FileInputStream(file));
                                projectName = (String) input.readObject();
                                authorSet = (Set<String>) input.readObject();
                                fileExtenstionSet = (Set<String>) input.readObject();
                                svnFileSet = (Set<SvnFile>) input.readObject();
                                authorProps = (Properties) input.readObject();
                                lastestVersion = (Long) input.readObject();
                                input.close();

                                resetUiAndShowMessage(startTime, projectName, lastestVersion);
                            } catch (Exception ex) {
                                JCommonUtil.handleException(ex);
                            }
                        }
                    });
                }
            }
        }
        pack();
        this.setSize(726, 459);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:au.org.ala.delta.intkey.Intkey.java

/**
 * Creates and shows the GUI. Called by the swing application framework
 *///from w  ww.  jav a2s .c om
@Override
protected void startup() {
    final JFrame mainFrame = getMainFrame();
    _defaultGlassPane = mainFrame.getGlassPane();
    mainFrame.setTitle("Intkey");
    mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
    mainFrame.setIconImages(IconHelper.getRedIconList());

    _helpController = new HelpController(HELPSET_PATH);

    _taxonformatter = new ItemFormatter(false, CommentStrippingMode.STRIP_ALL, AngleBracketHandlingMode.REMOVE,
            true, false, true);
    _context = new IntkeyContext(new IntkeyUIInterceptor(this), new DirectivePopulatorInterceptor(this));

    _advancedModeOnlyDynamicButtons = new ArrayList<JButton>();
    _normalModeOnlyDynamicButtons = new ArrayList<JButton>();
    _activeOnlyWhenCharactersUsedButtons = new ArrayList<JButton>();
    _dynamicButtonsFullHelp = new HashMap<JButton, String>();

    ActionMap actionMap = getContext().getActionMap();

    _rootPanel = new JPanel();
    _rootPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
    _rootPanel.setBackground(SystemColor.control);
    _rootPanel.setLayout(new BorderLayout(0, 0));

    _globalOptionBar = new JPanel();
    _globalOptionBar.setBorder(new EmptyBorder(0, 5, 0, 5));
    _rootPanel.add(_globalOptionBar, BorderLayout.NORTH);
    _globalOptionBar.setLayout(new BorderLayout(0, 0));

    _pnlDynamicButtons = new JPanel();
    FlowLayout flowLayout_1 = (FlowLayout) _pnlDynamicButtons.getLayout();
    flowLayout_1.setVgap(0);
    flowLayout_1.setHgap(0);
    _globalOptionBar.add(_pnlDynamicButtons, BorderLayout.WEST);

    _btnContextHelp = new JButton();
    _btnContextHelp.setMinimumSize(new Dimension(30, 30));
    _btnContextHelp.setMaximumSize(new Dimension(30, 30));
    _btnContextHelp.setAction(actionMap.get("btnContextHelp"));
    _btnContextHelp.setPreferredSize(new Dimension(30, 30));
    _btnContextHelp.setMargin(new Insets(2, 5, 2, 5));
    _btnContextHelp.addActionListener(actionMap.get("btnContextHelp"));
    _globalOptionBar.add(_btnContextHelp, BorderLayout.EAST);

    _rootSplitPane = new JSplitPane();
    _rootSplitPane.setDividerSize(3);
    _rootSplitPane.setResizeWeight(0.5);
    _rootSplitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
    _rootSplitPane.setContinuousLayout(true);
    _rootPanel.add(_rootSplitPane);

    _innerSplitPaneLeft = new JSplitPane();
    _innerSplitPaneLeft.setMinimumSize(new Dimension(25, 25));
    _innerSplitPaneLeft.setAlignmentX(Component.CENTER_ALIGNMENT);
    _innerSplitPaneLeft.setDividerSize(3);
    _innerSplitPaneLeft.setResizeWeight(0.5);

    _innerSplitPaneLeft.setContinuousLayout(true);
    _innerSplitPaneLeft.setOrientation(JSplitPane.VERTICAL_SPLIT);
    _rootSplitPane.setLeftComponent(_innerSplitPaneLeft);

    _pnlAvailableCharacters = new JPanel();
    _innerSplitPaneLeft.setLeftComponent(_pnlAvailableCharacters);
    _pnlAvailableCharacters.setLayout(new BorderLayout(0, 0));

    _sclPaneAvailableCharacters = new JScrollPane();
    _pnlAvailableCharacters.add(_sclPaneAvailableCharacters, BorderLayout.CENTER);

    _listAvailableCharacters = new JList();
    // _listAvailableCharacters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    _listAvailableCharacters.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    _listAvailableCharacters.setCellRenderer(_availableCharactersListCellRenderer);
    _listAvailableCharacters.addMouseListener(new MouseInputAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                int selectedIndex = _listAvailableCharacters.getSelectedIndex();
                if (selectedIndex >= 0) {
                    try {
                        Character ch = (Character) _availableCharacterListModel.getElementAt(selectedIndex);
                        executeDirective(new UseDirective(), Integer.toString(ch.getCharacterId()));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    });

    _sclPaneAvailableCharacters.setViewportView(_listAvailableCharacters);

    _pnlAvailableCharactersHeader = new JPanel();
    _pnlAvailableCharacters.add(_pnlAvailableCharactersHeader, BorderLayout.NORTH);
    _pnlAvailableCharactersHeader.setLayout(new BorderLayout(0, 0));

    _lblNumAvailableCharacters = new JLabel();
    _lblNumAvailableCharacters.setBorder(new EmptyBorder(0, 5, 0, 0));
    _lblNumAvailableCharacters.setFont(new Font("Tahoma", Font.PLAIN, 15));
    _lblNumAvailableCharacters.setText(MessageFormat.format(availableCharactersCaption, 0));
    _pnlAvailableCharactersHeader.add(_lblNumAvailableCharacters, BorderLayout.WEST);

    _pnlAvailableCharactersButtons = new JPanel();
    FlowLayout flowLayout = (FlowLayout) _pnlAvailableCharactersButtons.getLayout();
    flowLayout.setVgap(2);
    flowLayout.setHgap(2);
    _pnlAvailableCharactersHeader.add(_pnlAvailableCharactersButtons, BorderLayout.EAST);

    // All toolbar buttons should be disabled until a dataset is loaded.
    _btnRestart = new JButton();
    _btnRestart.setAction(actionMap.get("btnRestart"));
    _btnRestart.setPreferredSize(new Dimension(30, 30));
    _btnRestart.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnRestart);

    _btnBestOrder = new JButton();
    _btnBestOrder.setAction(actionMap.get("btnBestOrder"));
    _btnBestOrder.setPreferredSize(new Dimension(30, 30));
    _btnBestOrder.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnBestOrder);

    _btnSeparate = new JButton();
    _btnSeparate.setAction(actionMap.get("btnSeparate"));
    _btnSeparate.setVisible(_advancedMode);
    _btnSeparate.setPreferredSize(new Dimension(30, 30));
    _btnSeparate.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnSeparate);

    _btnNaturalOrder = new JButton();
    _btnNaturalOrder.setAction(actionMap.get("btnNaturalOrder"));
    _btnNaturalOrder.setPreferredSize(new Dimension(30, 30));
    _btnNaturalOrder.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnNaturalOrder);

    _btnDiffSpecimenTaxa = new JButton();
    _btnDiffSpecimenTaxa.setAction(actionMap.get("btnDiffSpecimenTaxa"));
    _btnDiffSpecimenTaxa.setEnabled(false);
    _btnDiffSpecimenTaxa.setPreferredSize(new Dimension(30, 30));
    _pnlAvailableCharactersButtons.add(_btnDiffSpecimenTaxa);

    _btnSetTolerance = new JButton();
    _btnSetTolerance.setAction(actionMap.get("btnSetTolerance"));
    _btnSetTolerance.setPreferredSize(new Dimension(30, 30));
    _btnSetTolerance.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnSetTolerance);

    _btnSetMatch = new JButton();
    _btnSetMatch.setAction(actionMap.get("btnSetMatch"));
    _btnSetMatch.setVisible(_advancedMode);
    _btnSetMatch.setPreferredSize(new Dimension(30, 30));
    _btnSetMatch.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnSetMatch);

    _btnSubsetCharacters = new JButton();
    _btnSubsetCharacters.setAction(actionMap.get("btnSubsetCharacters"));
    _btnSubsetCharacters.setPreferredSize(new Dimension(30, 30));
    _btnSubsetCharacters.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnSubsetCharacters);

    _btnFindCharacter = new JButton();
    _btnFindCharacter.setAction(actionMap.get("btnFindCharacter"));
    _btnFindCharacter.setPreferredSize(new Dimension(30, 30));
    _btnFindCharacter.setEnabled(false);
    _pnlAvailableCharactersButtons.add(_btnFindCharacter);

    _pnlAvailableCharactersButtons.setEnabled(false);

    _pnlUsedCharacters = new JPanel();
    _innerSplitPaneLeft.setRightComponent(_pnlUsedCharacters);
    _pnlUsedCharacters.setLayout(new BorderLayout(0, 0));

    _sclPnUsedCharacters = new JScrollPane();
    _pnlUsedCharacters.add(_sclPnUsedCharacters, BorderLayout.CENTER);

    _listUsedCharacters = new JList();
    _listUsedCharacters.setCellRenderer(_usedCharactersListCellRenderer);
    _listUsedCharacters.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    _listUsedCharacters.addMouseListener(new MouseInputAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                int selectedIndex = _listUsedCharacters.getSelectedIndex();
                if (selectedIndex >= 0) {
                    try {
                        Attribute attr = (Attribute) _usedCharacterListModel.getElementAt(selectedIndex);

                        if (_context.charactersFixed() && _context.getFixedCharactersList()
                                .contains(attr.getCharacter().getCharacterId())) {
                            return;
                        }

                        executeDirective(new ChangeDirective(),
                                Integer.toString(attr.getCharacter().getCharacterId()));
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    });

    _sclPnUsedCharacters.setViewportView(_listUsedCharacters);

    _pnlUsedCharactersHeader = new JPanel();
    _pnlUsedCharacters.add(_pnlUsedCharactersHeader, BorderLayout.NORTH);
    _pnlUsedCharactersHeader.setLayout(new BorderLayout(0, 0));

    _lblNumUsedCharacters = new JLabel();
    _lblNumUsedCharacters.setBorder(new EmptyBorder(7, 5, 7, 0));
    _lblNumUsedCharacters.setFont(new Font("Tahoma", Font.PLAIN, 15));
    _lblNumUsedCharacters.setText(MessageFormat.format(usedCharactersCaption, 0));
    _pnlUsedCharactersHeader.add(_lblNumUsedCharacters, BorderLayout.WEST);

    _innerSplitPaneRight = new JSplitPane();
    _innerSplitPaneRight.setMinimumSize(new Dimension(25, 25));
    _innerSplitPaneRight.setDividerSize(3);
    _innerSplitPaneRight.setResizeWeight(0.5);
    _innerSplitPaneRight.setContinuousLayout(true);
    _innerSplitPaneRight.setOrientation(JSplitPane.VERTICAL_SPLIT);
    _rootSplitPane.setRightComponent(_innerSplitPaneRight);

    _pnlRemainingTaxa = new JPanel();
    _innerSplitPaneRight.setLeftComponent(_pnlRemainingTaxa);
    _pnlRemainingTaxa.setLayout(new BorderLayout(0, 0));

    _sclPnRemainingTaxa = new JScrollPane();
    _pnlRemainingTaxa.add(_sclPnRemainingTaxa, BorderLayout.CENTER);

    _listRemainingTaxa = new JList();

    _listRemainingTaxa.addMouseListener(new MouseInputAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                displayInfoForSelectedTaxa();
            }
        }
    });

    _sclPnRemainingTaxa.setViewportView(_listRemainingTaxa);

    _pnlRemainingTaxaHeader = new JPanel();
    _pnlRemainingTaxa.add(_pnlRemainingTaxaHeader, BorderLayout.NORTH);
    _pnlRemainingTaxaHeader.setLayout(new BorderLayout(0, 0));

    _lblNumRemainingTaxa = new JLabel();
    _lblNumRemainingTaxa.setBorder(new EmptyBorder(0, 5, 0, 0));
    _lblNumRemainingTaxa.setFont(new Font("Tahoma", Font.PLAIN, 15));
    _lblNumRemainingTaxa.setText(MessageFormat.format(remainingTaxaCaption, 0));
    _pnlRemainingTaxaHeader.add(_lblNumRemainingTaxa, BorderLayout.WEST);

    _pnlRemainingTaxaButtons = new JPanel();
    FlowLayout fl_pnlRemainingTaxaButtons = (FlowLayout) _pnlRemainingTaxaButtons.getLayout();
    fl_pnlRemainingTaxaButtons.setVgap(2);
    fl_pnlRemainingTaxaButtons.setHgap(2);
    _pnlRemainingTaxaHeader.add(_pnlRemainingTaxaButtons, BorderLayout.EAST);

    // All toolbar buttons should be disabled until a dataset is loaded.
    _btnTaxonInfo = new JButton();
    _btnTaxonInfo.setAction(actionMap.get("btnTaxonInfo"));
    _btnTaxonInfo.setPreferredSize(new Dimension(30, 30));
    _btnTaxonInfo.setEnabled(false);
    _pnlRemainingTaxaButtons.add(_btnTaxonInfo);

    _btnDiffTaxa = new JButton();
    _btnDiffTaxa.setAction(actionMap.get("btnDiffTaxa"));
    _btnDiffTaxa.setPreferredSize(new Dimension(30, 30));
    _btnDiffTaxa.setEnabled(false);
    _pnlRemainingTaxaButtons.add(_btnDiffTaxa);

    _btnSubsetTaxa = new JButton();
    _btnSubsetTaxa.setAction(actionMap.get("btnSubsetTaxa"));
    _btnSubsetTaxa.setPreferredSize(new Dimension(30, 30));
    _btnSubsetTaxa.setEnabled(false);
    _pnlRemainingTaxaButtons.add(_btnSubsetTaxa);

    _btnFindTaxon = new JButton();
    _btnFindTaxon.setAction(actionMap.get("btnFindTaxon"));
    _btnFindTaxon.setPreferredSize(new Dimension(30, 30));
    _btnFindTaxon.setEnabled(false);
    _pnlRemainingTaxaButtons.add(_btnFindTaxon);

    _pnlEliminatedTaxa = new JPanel();
    _innerSplitPaneRight.setRightComponent(_pnlEliminatedTaxa);
    _pnlEliminatedTaxa.setLayout(new BorderLayout(0, 0));

    _sclPnEliminatedTaxa = new JScrollPane();
    _pnlEliminatedTaxa.add(_sclPnEliminatedTaxa, BorderLayout.CENTER);

    _listEliminatedTaxa = new JList();

    _listEliminatedTaxa.addMouseListener(new MouseInputAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() >= 2) {
                displayInfoForSelectedTaxa();
            }
        }
    });

    _sclPnEliminatedTaxa.setViewportView(_listEliminatedTaxa);

    _pnlEliminatedTaxaHeader = new JPanel();
    _pnlEliminatedTaxa.add(_pnlEliminatedTaxaHeader, BorderLayout.NORTH);
    _pnlEliminatedTaxaHeader.setLayout(new BorderLayout(0, 0));

    _lblEliminatedTaxa = new JLabel();
    _lblEliminatedTaxa.setBorder(new EmptyBorder(7, 5, 7, 0));
    _lblEliminatedTaxa.setFont(new Font("Tahoma", Font.PLAIN, 15));
    _lblEliminatedTaxa.setText(MessageFormat.format(eliminatedTaxaCaption, 0));
    _pnlEliminatedTaxaHeader.add(_lblEliminatedTaxa, BorderLayout.WEST);

    JMenuBar menuBar = buildMenus(_advancedMode);
    getMainView().setMenuBar(menuBar);

    _txtFldCmdBar = new JTextField();
    _txtFldCmdBar.setCaretColor(Color.WHITE);
    _txtFldCmdBar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String cmdStr = _txtFldCmdBar.getText();

            cmdStr = cmdStr.trim();
            if (_cmdMenus.containsKey(cmdStr)) {
                JMenu cmdMenu = _cmdMenus.get(cmdStr);
                cmdMenu.doClick();
            } else {
                _context.parseAndExecuteDirective(cmdStr);
            }
            _txtFldCmdBar.setText(null);
        }
    });

    _txtFldCmdBar.setFont(new Font("Courier New", Font.BOLD, 13));
    _txtFldCmdBar.setForeground(SystemColor.text);
    _txtFldCmdBar.setBackground(Color.BLACK);
    _txtFldCmdBar.setOpaque(true);
    _txtFldCmdBar.setVisible(_advancedMode);
    _rootPanel.add(_txtFldCmdBar, BorderLayout.SOUTH);
    _txtFldCmdBar.setColumns(10);

    _logDialog = new RtfReportDisplayDialog(getMainFrame(), new SimpleRtfEditorKit(null), null, logDialogTitle);

    // Set context-sensitive help keys for toolbar buttons
    _helpController.setHelpKeyForComponent(_btnRestart, HELP_ID_CHARACTERS_TOOLBAR_RESTART);
    _helpController.setHelpKeyForComponent(_btnBestOrder, HELP_ID_CHARACTERS_TOOLBAR_BEST);
    _helpController.setHelpKeyForComponent(_btnSeparate, HELP_ID_CHARACTERS_TOOLBAR_SEPARATE);
    _helpController.setHelpKeyForComponent(_btnNaturalOrder, HELP_ID_CHARACTERS_TOOLBAR_NATURAL);
    _helpController.setHelpKeyForComponent(_btnDiffSpecimenTaxa,
            HELP_ID_CHARACTERS_TOOLBAR_DIFF_SPECIMEN_REMAINING);
    _helpController.setHelpKeyForComponent(_btnSetTolerance, HELP_ID_CHARACTERS_TOOLBAR_TOLERANCE);
    _helpController.setHelpKeyForComponent(_btnSetMatch, HELP_ID_CHARACTERS_TOOLBAR_SET_MATCH);
    _helpController.setHelpKeyForComponent(_btnSubsetCharacters, HELP_ID_CHARACTERS_TOOLBAR_SUBSET_CHARACTERS);
    _helpController.setHelpKeyForComponent(_btnFindCharacter, HELP_ID_CHARACTERS_TOOLBAR_FIND_CHARACTERS);

    _helpController.setHelpKeyForComponent(_btnTaxonInfo, HELP_ID_TAXA_TOOLBAR_INFO);
    _helpController.setHelpKeyForComponent(_btnDiffTaxa, HELP_ID_TAXA_TOOLBAR_DIFF_TAXA);
    _helpController.setHelpKeyForComponent(_btnSubsetTaxa, HELP_ID_TAXA_TOOLBAR_SUBSET_TAXA);
    _helpController.setHelpKeyForComponent(_btnFindTaxon, HELP_ID_TAXA_TOOLBAR_FIND_TAXA);

    // This mouse listener on the default glasspane is to assist with
    // context senstive help. It intercepts the mouse events,
    // determines what component was being clicked on, then takes the
    // appropriate action to provide help for the component
    _defaultGlassPane.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            // Determine what point has been clicked on
            Point glassPanePoint = e.getPoint();
            Point containerPoint = SwingUtilities.convertPoint(getMainFrame().getGlassPane(), glassPanePoint,
                    getMainFrame().getContentPane());
            Component component = SwingUtilities.getDeepestComponentAt(getMainFrame().getContentPane(),
                    containerPoint.x, containerPoint.y);

            // Get the java help ID for this component. If none has been
            // defined, this will be null
            String helpID = _helpController.getHelpKeyForComponent(component);

            // change the cursor back to the normal one and take down the
            // classpane
            mainFrame.setCursor(Cursor.getDefaultCursor());
            mainFrame.getGlassPane().setVisible(false);

            // If a help ID was found, display the related help page in the
            // help viewer
            if (_helpController.getHelpKeyForComponent(component) != null) {
                _helpController.helpAction().actionPerformed(new ActionEvent(component, 0, null));
                _helpController.displayHelpTopic(mainFrame, helpID);
            } else {
                // If a dynamically-defined toolbar button was clicked, show
                // the help for this button in the ToolbarHelpDialog.
                if (component instanceof JButton) {
                    JButton button = (JButton) component;
                    if (_dynamicButtonsFullHelp.containsKey(button)) {
                        String fullHelpText = _dynamicButtonsFullHelp.get(button);
                        if (fullHelpText == null) {
                            fullHelpText = noHelpAvailableCaption;
                        }
                        RTFBuilder builder = new RTFBuilder();
                        builder.startDocument();
                        builder.appendText(fullHelpText);
                        builder.endDocument();
                        ToolbarHelpDialog dlg = new ToolbarHelpDialog(mainFrame, builder.toString(),
                                button.getIcon());
                        show(dlg);
                    }
                }
            }
        }
    });

    show(_rootPanel);
}

From source file:gtu._work.etc.EnglishTester.java

private void initGUI() {
    try {//from ww  w.java  2  s.  c o m
        JCommonUtil.defaultToolTipDelay();
        BorderLayout thisLayout = new BorderLayout();
        getContentPane().setLayout(thisLayout);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            jTabbedPane1.setPreferredSize(new java.awt.Dimension(462, 259));

            jTabbedPane1.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent evt) {
                    // XXX
                    // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
                    jTabbedPane1.requestFocus();// FOCUS TODO
                    // XXX
                    // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
                }
            });
            jTabbedPane1.addKeyListener(new KeyAdapter() {
                public void keyPressed(KeyEvent evt) {
                    System.out.println("2===" + evt.getKeyCode());
                    if (evt.getKeyCode() == 49) {// 0
                        jTabbedPane1.setSelectedIndex(0);
                    }
                    if (evt.getKeyCode() == 50) {// 1
                        jTabbedPane1.setSelectedIndex(1);
                    }
                    if (evt.getKeyCode() == 10) {// enter
                        skipBtnAction();
                    }
                    if (evt.getKeyCode() == 32) {// 
                        removeBtnAction();
                    }
                }
            });
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("english", null, jPanel1, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel1.add(jScrollPane1, BorderLayout.CENTER);
                    jScrollPane1.setPreferredSize(new java.awt.Dimension(420, 141));
                    {
                        englishArea = new JTextArea();
                        jScrollPane1.setViewportView(englishArea);
                        englishArea.setFont(new java.awt.Font("Microsoft JhengHei", 0, 22));
                    }
                }
                {
                    jPanel5 = new JPanel();
                    jPanel1.add(jPanel5, BorderLayout.SOUTH);
                    jPanel5.setPreferredSize(new java.awt.Dimension(402, 65));
                    {
                        skipBtn = new JButton();
                        jPanel5.add(skipBtn);
                        skipBtn.setText("skip");
                        skipBtn.setPreferredSize(new java.awt.Dimension(187, 24));
                        skipBtn.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                skipBtnAction();
                            }
                        });
                    }
                    {
                        removeBtn = new JButton();
                        jPanel5.add(removeBtn);
                        removeBtn.setText("remove");
                        removeBtn.setPreferredSize(new java.awt.Dimension(180, 24));
                        removeBtn.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                removeBtnAction();
                            }
                        });
                    }
                    {
                        questionCountLabel = new JLabel();
                        jPanel5.add(questionCountLabel);
                        questionCountLabel.setPreferredSize(new java.awt.Dimension(47, 21));
                        questionCountLabel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
                        questionCountLabel.setToolTipText("");
                    }
                    {
                        propCountLabel = new JLabel();
                        jPanel5.add(propCountLabel);
                        propCountLabel.setPreferredSize(new java.awt.Dimension(45, 21));
                        propCountLabel.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
                        propCountLabel.setToolTipText("");
                    }
                    {
                        googleSearchBtn = new JButton();
                        jPanel5.add(googleSearchBtn);
                        googleSearchBtn.setText("<html>GPic</html>");
                        googleSearchBtn.setPreferredSize(new java.awt.Dimension(58, 24));
                        googleSearchBtn.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    String word = currentWordIndex.trim();
                                    ClipboardUtil.getInstance().setContents(word);
                                    word = word.replace(" ", "%20");
                                    URI uri = new URI(
                                            "https://www.google.com.tw/search?num=10&hl=zh-TW&site=imghp&tbm=isch&source=hp&biw=1280&bih=696&q="
                                                    + word);
                                    //URI uri = new URI("http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=" + word);
                                    Desktop.getDesktop().browse(uri);
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                    {
                        yahooDicBtn = new JButton();
                        jPanel5.add(yahooDicBtn);
                        yahooDicBtn.setText("<html>Dict</html>");
                        yahooDicBtn.setPreferredSize(new java.awt.Dimension(57, 24));
                        yahooDicBtn.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    // URI uri = new
                                    // URI("http://tw.dictionary.yahoo.com/dictionary?p="
                                    // + currentWord.trim());
                                    URI uri = new URI("http://www.dreye.com/axis/ddict.jsp?ver=big5&dod=0102&w="
                                            + currentWordIndex.trim() + "&x=0&y=0");
                                    Desktop.getDesktop().browse(uri);
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                    {
                        pickBtn = new JButton();
                        jPanel5.add(pickBtn);
                        pickBtn.setText("<html>+Pick</html>");
                        pickBtn.setPreferredSize(new java.awt.Dimension(60, 24));
                        pickBtn.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                try {
                                    String key = currentWordIndex;
                                    String value = englishProp.getProperty(currentWordIndex);
                                    if (StringUtils.isEmpty(value)) {
                                        JCommonUtil._jOptionPane_showMessageDialog_error(
                                                "add pick failed : no such word => " + key);
                                    } else {
                                        pickProp.setProperty(key, value);
                                        JCommonUtil._jOptionPane_showMessageDialog_info(
                                                "key=" + key + "\nvalue=" + value + "\nsize=" + pickProp.size(),
                                                "??");
                                    }
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                    {
                        scanPicBtn = new JButton();
                        scanPicBtn.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent e) {
                            }
                        });
                        jPanel5.add(scanPicBtn);
                        scanPicBtn.setPreferredSize(new java.awt.Dimension(46, 24));
                        scanPicBtn.addMouseListener(new MouseAdapter() {

                            public void mouseClicked(MouseEvent evt) {
                                if (picDir == null) {
                                    JCommonUtil._jOptionPane_showMessageDialog_error("picDir is null");
                                    return;
                                }

                                if (picSet != null && picSet.size() > 0) {
                                    try {
                                        Desktop.getDesktop().open(picSet.iterator().next());
                                    } catch (IOException e) {
                                        JCommonUtil.handleException(e);
                                    }
                                    return;
                                }

                                try {
                                    String text = currentWordIndex.trim().toLowerCase();
                                    ClipboardUtil.getInstance().setContents(text);
                                    text = text.replace(" ", "%20");
                                    URI uri = new URI(
                                            "https://www.google.com.tw/search?num=10&hl=zh-TW&site=imghp&tbm=isch&source=hp&biw=1280&bih=696&q="
                                                    + text);
                                    //URI uri = new URI("http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=" + text);
                                    Desktop.getDesktop().browse(uri);
                                } catch (Exception ex) {
                                    JCommonUtil.handleException(ex);
                                }
                            }
                        });
                    }
                    {
                        showChineseOption = new JCheckBox();
                        showChineseOption.setSelected(true);
                        jPanel5.add(showChineseOption);
                    }
                }
            }
            {
                jPanel2 = new JPanel();
                BorderLayout jPanel2Layout = new BorderLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("chinese", null, jPanel2, null);
                jPanel2.setPreferredSize(new java.awt.Dimension(420, 211));
                {
                    showEnglishText = new JTextField();
                    jPanel2.add(showEnglishText, BorderLayout.NORTH);
                    showEnglishText.setEditable(false);
                }
                {
                    jPanel10 = new JPanel();
                    jPanel2.add(jPanel10, BorderLayout.CENTER);
                }
                {
                    answerBtn[0] = new JButton();
                    jPanel10.add(answerBtn[0]);
                    answerBtn[0].setPreferredSize(new java.awt.Dimension(190, 110));
                    answerBtn[0].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            answerBtnClick(answerBtn[0]);
                        }
                    });
                }
                {
                    answerBtn[1] = new JButton();
                    jPanel10.add(answerBtn[1]);
                    answerBtn[1].setPreferredSize(new java.awt.Dimension(190, 110));
                    answerBtn[1].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            answerBtnClick(answerBtn[1]);
                        }
                    });
                }
                {
                    answerBtn[2] = new JButton();
                    jPanel10.add(answerBtn[2]);
                    answerBtn[2].setPreferredSize(new java.awt.Dimension(190, 110));
                    answerBtn[2].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            answerBtnClick(answerBtn[2]);
                        }
                    });
                }
                {
                    answerBtn[3] = new JButton();
                    jPanel10.add(answerBtn[3]);
                    answerBtn[3].setPreferredSize(new java.awt.Dimension(190, 110));
                    answerBtn[3].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            answerBtnClick(answerBtn[3]);
                        }
                    });
                }
                {
                    for (int ii = 0; ii < 4; ii++) {
                        answerBtn[ii].setFont(new java.awt.Font("", 0, 14));
                    }
                }
            }
            {
                jPanel3 = new JPanel();
                BorderLayout jPanel3Layout = new BorderLayout();
                jPanel3.setLayout(jPanel3Layout);
                jTabbedPane1.addTab("word", null, jPanel3, null);
                {
                    jScrollPane3 = new JScrollPane();
                    jPanel3.add(jScrollPane3, BorderLayout.CENTER);
                    jScrollPane3.setPreferredSize(new java.awt.Dimension(420, 187));
                    {
                        propTable = new JTable();
                        jScrollPane3.setViewportView(propTable);
                        JTableUtil.defaultSetting(propTable);
                        propTable.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                JPopupMenuUtil.newInstance(propTable)
                                        .addJMenuItem(JTableUtil.newInstance(propTable).getDefaultJMenuItems())
                                        .applyEvent(evt).show();
                            }
                        });
                    }
                }
                {
                    saveBtn = new JButton();
                    jPanel3.add(saveBtn, BorderLayout.SOUTH);
                    saveBtn.setText("save table");
                    saveBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            DefaultTableModel model = JTableUtil.newInstance(propTable).getModel();
                            for (int ii = 0; ii < model.getRowCount(); ii++) {
                                String key = (String) model.getValueAt(ii, 0);
                                String value = (String) model.getValueAt(ii, 1);
                                if (!englishProp.containsKey(key)) {
                                    englishProp.setProperty(key, value);
                                }
                            }
                            try {
                                englishProp.store(new FileOutputStream(englishFile), "comment");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            JCommonUtil._jOptionPane_showMessageDialog_info("save file ok!  \n" + englishFile);
                        }
                    });
                }
                {
                    queryText = new JTextField();
                    jPanel3.add(queryText, BorderLayout.NORTH);
                    queryText.getDocument()
                            .addDocumentListener(JCommonUtil.getDocumentListener(new HandleDocumentEvent() {
                                @Override
                                public void process(DocumentEvent event) {
                                    String text = JCommonUtil.getDocumentText(event);
                                    Pattern pattern = Pattern.compile(text);
                                    Matcher matcher = null;
                                    DefaultTableModel propTableModel = JTableUtil.createModel(false, "english",
                                            "chinese");
                                    for (Enumeration<?> enu = englishProp.propertyNames(); enu
                                            .hasMoreElements();) {
                                        String key = (String) enu.nextElement();
                                        String value = englishProp.getProperty(key);
                                        if (key.contains(text)) {
                                            propTableModel.addRow(new Object[] { key, value });
                                            continue;
                                        }
                                        matcher = pattern.matcher(key);
                                        if (matcher.find()) {
                                            propTableModel.addRow(new Object[] { key, value });
                                            continue;
                                        }
                                    }
                                    propTable.setModel(propTableModel);
                                }
                            }));
                }
            }
            {
                jPanel4 = new JPanel();
                jTabbedPane1.addTab("config", null, jPanel4, null);
                {
                    savePickBtn = new JButton();
                    jPanel4.add(savePickBtn);
                    savePickBtn.setText("save pick");
                    savePickBtn.setPreferredSize(new java.awt.Dimension(116, 40));
                    savePickBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            if (englishFile == null) {
                                File file = new File(//
                                        PropertiesUtil.getJarCurrentPath(EnglishTester.class),
                                        "temp.properties");
                                englishFile = file;
                            }
                            if (pickProp.isEmpty()) {
                                JCommonUtil._jOptionPane_showMessageDialog_error("?!");
                                return;
                            }
                            String fileName = englishFile.getName().replaceAll("\\.properties",
                                    "_bak.properties");
                            File jarWhereFile = PropertiesUtil.getJarCurrentPath(EnglishTester.class);
                            fileName = JCommonUtil._jOptionPane_showInputDialog("save target properties",
                                    fileName);
                            if (StringUtils.isEmpty(fileName)) {
                                JCommonUtil._jOptionPane_showMessageDialog_error("can't save!");
                                return;
                            }
                            if (fileName.equalsIgnoreCase(englishFile.getName())) {
                                JCommonUtil._jOptionPane_showMessageDialog_error(
                                        "??englishFile???");
                                return;
                            }
                            if (!fileName.endsWith(".properties")) {
                                fileName += ".properties";
                            }
                            File newFile = new File(jarWhereFile, fileName);
                            Properties oldProp = new Properties();
                            if (newFile.exists()) {
                                try {
                                    oldProp.load(new FileInputStream(newFile));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                            oldProp.putAll(pickProp);
                            try {
                                oldProp.store(new FileOutputStream(newFile), "comment");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            JCommonUtil._jOptionPane_showMessageDialog_info("save file ok!  \n" + newFile);
                        }
                    });
                }
                {
                    saveConfigBtn2 = new JButton();
                    jPanel4.add(saveConfigBtn2);
                    saveConfigBtn2.setText("save config");
                    saveConfigBtn2.setPreferredSize(new java.awt.Dimension(108, 40));
                    saveConfigBtn2.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            saveConfigBtnAction();
                        }
                    });
                }
                {
                    startAllBtn = new JButton();
                    jPanel4.add(startAllBtn);
                    startAllBtn.setText("start all");
                    startAllBtn.setPreferredSize(new java.awt.Dimension(101, 40));
                    startAllBtn.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            Object[] files = fileList.getSelectedValues();
                            if (files == null || files.length == 0) {
                                JCommonUtil
                                        ._jOptionPane_showMessageDialog_error("?properties");
                                return;
                            }
                            Properties allProp = new Properties();
                            Properties prop = new Properties();
                            for (Object ff : files) {
                                try {
                                    prop.load(new FileInputStream((File) ff));
                                } catch (Exception e) {
                                    JCommonUtil.handleException(e);
                                }
                                allProp.putAll(prop);
                            }
                            englishProp = allProp;
                            System.out.println("englishProp = " + englishProp.size());
                            startNow();
                        }
                    });
                }
                {
                    startNow = new JButton();
                    jPanel4.add(startNow);
                    startNow.setText("start now");
                    startNow.setPreferredSize(new java.awt.Dimension(101, 40));

                    startNow.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            startNow();
                        }
                    });
                }
                {
                    picOnly = new JCheckBox();
                    jPanel4.add(picOnly);
                    picOnly.setText("picOnly");
                }
                {
                    sortChkBox = new JCheckBox();
                    jPanel4.add(sortChkBox);
                    sortChkBox.setText("sort");
                }
                {
                    showPicChkBox = new JCheckBox();
                    showPicChkBox.setSelected(true);
                    jPanel4.add(showPicChkBox);
                    showPicChkBox.setText("showPic");
                }
                {
                    JCommonUtil.defaultToolTipDelay();
                    fontSizeSliber = new JSlider(JSlider.HORIZONTAL);
                    jPanel4.add(fontSizeSliber);
                    fontSizeSliber.setPreferredSize(new java.awt.Dimension(419, 35));
                    fontSizeSliber.setValue(22);
                    fontSizeSliber.setMinimum(22);
                    fontSizeSliber.setMaximum(300);
                    fontSizeSliber.setMajorTickSpacing(30);
                    fontSizeSliber.setMinorTickSpacing(5);
                    fontSizeSliber.setCursor(new Cursor(Cursor.HAND_CURSOR));
                    fontSizeSliber.setPaintTicks(false);
                    fontSizeSliber.setPaintLabels(true);
                    {
                        picFolderDirText = new JTextField();
                        JCommonUtil.jTextFieldSetFilePathMouseEvent(picFolderDirText, true);
                        jPanel4.add(picFolderDirText);
                        picFolderDirText.setColumns(20);
                    }
                    fontSizeSliber.addChangeListener(new ChangeListener() {
                        @Override
                        public void stateChanged(ChangeEvent e) {
                            int size = fontSizeSliber.getValue();
                            fontSizeSliber.setToolTipText("" + size);
                            englishArea.setFont(new java.awt.Font("Microsoft JhengHei", 0, size));
                        }
                    });

                }
            }
            {
                jPanel6 = new JPanel();
                jTabbedPane1.addTab("files", null, jPanel6, null);
                BorderLayout jPanel6Layout = new BorderLayout();
                jPanel6.setLayout(jPanel6Layout);
                {
                    jScrollPane4 = new JScrollPane();
                    jPanel6.add(jScrollPane4, BorderLayout.CENTER);
                    jScrollPane4.setPreferredSize(new java.awt.Dimension(420, 211));
                    {
                        fileList = new JList();
                        reloadFileList();
                        jScrollPane4.setViewportView(fileList);
                        fileList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                final File file = JListUtil.getLeadSelectionObject(fileList);
                                if (JMouseEventUtil.buttonRightClick(1, evt)) {
                                    JPopupMenuUtil.newInstance(EnglishTester.this.fileList).applyEvent(evt)//
                                            .addJMenuItem("reload", new ActionListener() {
                                                @Override
                                                public void actionPerformed(ActionEvent e) {
                                                    reloadFileList();
                                                }
                                            })//
                                            .addJMenuItem("delete : " + file.getName(), new ActionListener() {
                                                @Override
                                                public void actionPerformed(ActionEvent e) {
                                                    boolean result = JCommonUtil
                                                            ._JOptionPane_showConfirmDialog_yesNoOption(
                                                                    "delete : " + file.getName() + " ?",
                                                                    "confirm");
                                                    if (result) {
                                                        file.delete();
                                                        reloadFileList();
                                                    }
                                                }//
                                            }).show();
                                    return;
                                }
                                if (evt.getClickCount() == 1) {
                                    return;
                                }
                                if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                        "?,?\n" + file.getName(),
                                        "")) {
                                    loadEnglishFile(file);
                                }
                            }
                        });
                        fileList.addKeyListener(new KeyAdapter() {
                            public void keyPressed(KeyEvent evt) {
                                JListUtil.newInstance(fileList).defaultJListKeyPressed(evt);
                            }
                        });
                    }
                }
            }
            {
                jPanel9 = new JPanel();
                jTabbedPane1.addTab("pic", null, jPanel9, null);
                {
                    picCheckText = new JTextField();
                    jPanel9.add(picCheckText);
                    picCheckText.setPreferredSize(new java.awt.Dimension(177, 39));
                }
                {
                    picCheckBtn = new JButton();
                    jPanel9.add(picCheckBtn);
                    picCheckBtn.setText("check");
                    picCheckBtn.setPreferredSize(new java.awt.Dimension(98, 43));
                    {
                        jPanel11 = new JPanel();
                        jTabbedPane1.addTab("", null, jPanel11, null);
                        jPanel11.setLayout(new BorderLayout(0, 0));
                        {
                            inputTestArea2 = new JTextArea();
                            inputTestArea2.setFont(new Font("", Font.PLAIN, 12));
                            inputTestArea2.addKeyListener(new KeyAdapter() {
                                @Override
                                public void keyReleased(KeyEvent e) {
                                    inputTestTrainer.keyin(e);
                                }
                            });
                            jPanel11.add(inputTestArea2, BorderLayout.SOUTH);
                        }
                        {
                            inputTestArea1 = new JTextArea();
                            JTextAreaUtil.setWrapTextArea(inputTestArea1);
                            inputTestArea1.setFont(new Font("", Font.PLAIN, 22));
                            jPanel11.add(inputTestArea1, BorderLayout.CENTER);
                        }
                        {
                            panel = new JPanel();
                            jPanel11.add(panel, BorderLayout.NORTH);
                            {
                                inputTestLabel = new JLabel("");
                                panel.add(inputTestLabel);
                            }
                            {
                                inputTestChk = new JCheckBox("");
                                inputTestChk.addActionListener(new ActionListener() {
                                    public void actionPerformed(ActionEvent e) {
                                        inputTestTrainer.initQuestion();
                                    }
                                });
                                panel.add(inputTestChk);
                            }
                        }
                    }
                    picCheckBtn.addActionListener(new ActionListener() {
                        void scanPic(String searchWord, File file, Set<File> findFile) {
                            if (file.isDirectory()) {
                                File[] list = null;
                                if ((list = file.listFiles()) != null) {
                                    for (File f : list) {
                                        scanPic(searchWord, f, findFile);
                                    }
                                }
                            } else {
                                String text = searchWord;
                                String name = file.getName().toLowerCase();
                                if (isMatch(name, text)) {
                                    findFile.add(file);
                                }
                            }
                        }

                        public void actionPerformed(ActionEvent evt) {
                            picDir = new File(picFolderDirText.getText());
                            if (picDir == null) {
                                JCommonUtil._jOptionPane_showMessageDialog_error("picDir is null");
                                return;
                            }
                            if (!picDir.exists() || !picDir.isDirectory()) {
                                JCommonUtil._jOptionPane_showMessageDialog_error("picDir ");
                                return;
                            }

                            picCheckBtn.setText("search..");

                            String searchWord = picCheckText.getText().toLowerCase().trim();

                            Set<File> picSet2 = new HashSet<File>();
                            scanPic(searchWord, picDir, picSet2);

                            if (picSet2 != null && picSet2.size() > 0) {
                                picCheckBtn.setText("" + picSet2.size());

                                try {
                                    Desktop.getDesktop().open(picSet2.iterator().next());
                                } catch (IOException e) {
                                    JCommonUtil.handleException(e);
                                }
                            } else {
                                picCheckBtn.setText("0");
                            }
                        }
                    });
                }
            }
        }

        JCommonUtil.setJFrameIcon(this, "resource/images/ico/english_tester.ico");

        pack();
        this.setSize(423, 314);

        configHelper.init();
    } catch (Exception e) {
        // add your error handling code here
        e.printStackTrace();
    }
}

From source file:com.atlassian.theplugin.idea.jira.IssueCreateDialog.java

/**
 * Method generated by IntelliJ IDEA GUI Designer
 * >>> IMPORTANT!! <<<
 * DO NOT edit this method OR call it in your code!
 *
 * @noinspection ALL/*from w  ww . j a  va 2 s .  c om*/
 */
private void $$$setupUI$$$() {
    mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayoutManager(10, 3, new Insets(5, 5, 5, 5), -1, -1));
    mainPanel.setMinimumSize(new Dimension(480, 500));
    final JScrollPane scrollPane1 = new JScrollPane();
    mainPanel.add(scrollPane1,
            new GridConstraints(7, 1, 2, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW, null, null,
                    null, 0, false));
    description = new JTextArea();
    description.setLineWrap(true);
    description.setWrapStyleWord(true);
    scrollPane1.setViewportView(description);
    final JLabel label1 = new JLabel();
    label1.setText("Summary:");
    mainPanel.add(label1,
            new GridConstraints(6, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    final JLabel label2 = new JLabel();
    label2.setText("Project:");
    mainPanel.add(label2,
            new GridConstraints(0, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    projectComboBox = new JComboBox();
    mainPanel.add(projectComboBox,
            new GridConstraints(0, 1, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_FIXED, new Dimension(100, -1), null, null, 0, false));
    summary = new JTextField();
    mainPanel.add(summary,
            new GridConstraints(6, 1, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_FIXED, null, new Dimension(100, -1), null, 0, false));
    final JLabel label3 = new JLabel();
    label3.setText("Description:");
    mainPanel.add(label3,
            new GridConstraints(7, 0, 1, 1, GridConstraints.ANCHOR_NORTHEAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    final JLabel label4 = new JLabel();
    label4.setText("Assignee:");
    mainPanel.add(label4,
            new GridConstraints(9, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    final JLabel label5 = new JLabel();
    label5.setFont(new Font(label5.getFont().getName(), label5.getFont().getStyle(), 10));
    label5.setHorizontalTextPosition(10);
    label5.setText("Warning! This field is not validated prior to sending to JIRA");
    mainPanel.add(label5,
            new GridConstraints(9, 2, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    final JLabel label6 = new JLabel();
    label6.setText("Type:");
    mainPanel.add(label6,
            new GridConstraints(1, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    typeComboBox = new JComboBox();
    mainPanel.add(typeComboBox,
            new GridConstraints(1, 1, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    final JLabel label7 = new JLabel();
    label7.setText("Priority:");
    mainPanel.add(label7,
            new GridConstraints(5, 0, 1, 1, GridConstraints.ANCHOR_EAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    priorityComboBox = new JComboBox();
    mainPanel.add(priorityComboBox,
            new GridConstraints(5, 1, 1, 2, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_HORIZONTAL,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_FIXED, new Dimension(100, -1), null, null, 0, false));
    final JLabel label8 = new JLabel();
    label8.setText("Component/s:");
    mainPanel.add(label8,
            new GridConstraints(2, 0, 1, 1, GridConstraints.ANCHOR_NORTHEAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    final JScrollPane scrollPane2 = new JScrollPane();
    mainPanel.add(scrollPane2,
            new GridConstraints(2, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false));
    componentsList = new JList();
    componentsList.setToolTipText("Select Affected Components ");
    componentsList.setVisibleRowCount(5);
    scrollPane2.setViewportView(componentsList);
    final JLabel label9 = new JLabel();
    label9.setText("Affects Version/s:");
    mainPanel.add(label9,
            new GridConstraints(3, 0, 1, 1, GridConstraints.ANCHOR_NORTHWEST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    final JScrollPane scrollPane3 = new JScrollPane();
    mainPanel.add(scrollPane3,
            new GridConstraints(3, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
                    null, 0, false));
    versionsList = new JList();
    versionsList.setVisibleRowCount(5);
    scrollPane3.setViewportView(versionsList);
    final JScrollPane scrollPane4 = new JScrollPane();
    mainPanel.add(scrollPane4,
            new GridConstraints(4, 1, 1, 2, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_WANT_GROW,
                    GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW, null, null,
                    null, 0, false));
    fixVersionsList = new JList();
    fixVersionsList.setVisible(true);
    fixVersionsList.setVisibleRowCount(5);
    scrollPane4.setViewportView(fixVersionsList);
    final JLabel label10 = new JLabel();
    label10.setText("Fix Version/s:");
    mainPanel.add(label10,
            new GridConstraints(4, 0, 1, 1, GridConstraints.ANCHOR_NORTHEAST, GridConstraints.FILL_NONE,
                    GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0,
                    false));
    label1.setLabelFor(summary);
    label2.setLabelFor(projectComboBox);
    label3.setLabelFor(description);
    label6.setLabelFor(typeComboBox);
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.DataImportDialog.java

/**
 * Goes through and checks the import data for potential errors (where the data being import
 * violates size constraints when being imported into the data base - ie. column header length (64)
 * or field value length (255)//ww  w  .  ja v a  2  s  . c o m
 * @param headers - the column headers
 * @param data - the table data
 * @return
 * JList - all list of errors
 */
private JList genListOfErrorWhereTableDataDefiesSizeConstraints(String[] headers, String[][] data) {
    DefaultListModel listModel = new DefaultListModel();
    JList listOfImportDataErrors = new JList();
    for (int i = 0; i < headers.length; i++) {
        if (!isStringShorterThan(WorkbenchTemplateMappingItem.getImportedColNameMaxLength(), headers[i])) {
            String msg = "Column at index=" + i
                    + " is too long to be inserted into the database.  It will be truncated.\n"
                    + "Current Value:\n" + headers[i] + "\nTruncated Value:\n"
                    + headers[i].substring(0, WorkbenchTemplateMappingItem.getImportedColNameMaxLength() - 1);
            log.warn(msg);
            listModel.addElement(msg);
        }
    }
    for (int i = 0; i < data.length; i++) {
        for (int j = 0; j < data[i].length; j++) {
            //WorkbenchDataItem.class.getDeclaredMethod("getCellData", null).getDeclaredAnnotations();
            String str = data[i][j];
            if (!isStringShorterThan(WorkbenchDataItem.getMaxWBCellLength(), str)) {
                String msg = "The value in cell Row=" + i + ", Column=" + headers[j]
                        + " is too long to be inserted into the database.  It will be truncated.\n"
                        + "Current Value:\n" + str + "\nTruncated Value:\n"
                        + str.substring(0, WorkbenchDataItem.getMaxWBCellLength() - 1);
                log.warn(msg);
                listModel.addElement(msg);
            }
        }
    }
    listOfImportDataErrors.setModel(listModel);
    return listOfImportDataErrors;
}