Example usage for java.awt.event WindowEvent getSource

List of usage examples for java.awt.event WindowEvent getSource

Introduction

In this page you can find the example usage for java.awt.event WindowEvent getSource.

Prototype

public Object getSource() 

Source Link

Document

The object on which the Event initially occurred.

Usage

From source file:de.bwravencl.controllerbuddy.gui.Main.java

private Main() {
    Singleton.start(this, SINGLETON_ID);

    frame = new JFrame();
    frame.addWindowListener(new WindowAdapter() {

        @Override/*from  www.j  a  va 2s . co m*/
        public void windowClosing(final WindowEvent e) {
            super.windowClosing(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(true);
        }

        @Override
        public void windowDeiconified(final WindowEvent e) {
            super.windowDeiconified(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(false);
        }

        @Override
        public void windowIconified(final WindowEvent e) {
            super.windowIconified(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(true);
        }

        @Override
        public void windowOpened(final WindowEvent e) {
            super.windowOpened(e);

            if (showMenuItem != null)
                showMenuItem.setEnabled(false);
        }

    });

    frame.setBounds(DIALOG_BOUNDS_X, DIALOG_BOUNDS_Y, DIALOG_BOUNDS_WIDTH, DIALOG_BOUNDS_HEIGHT);
    frame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

    final var icons = new ArrayList<Image>();
    for (final var path : ICON_RESOURCE_PATHS) {
        final var icon = new ImageIcon(Main.class.getResource(path));
        icons.add(icon.getImage());
    }
    frame.setIconImages(icons);

    frame.setJMenuBar(menuBar);

    menuBar.add(fileMenu);
    final QuitAction quitAction = new QuitAction();
    fileMenu.add(quitAction);
    menuBar.add(deviceMenu);

    if (windows) {
        menuBar.add(localMenu, 2);

        final var buttonGroupLocalState = new ButtonGroup();
        startLocalRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("START_MENU_ITEM"));
        startLocalRadioButtonMenuItem.setAction(new StartLocalAction());
        buttonGroupLocalState.add(startLocalRadioButtonMenuItem);
        localMenu.add(startLocalRadioButtonMenuItem);

        stopLocalRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("STOP_MENU_ITEM"));
        stopLocalRadioButtonMenuItem.setAction(new StopLocalAction());
        buttonGroupLocalState.add(stopLocalRadioButtonMenuItem);
        localMenu.add(stopLocalRadioButtonMenuItem);

        menuBar.add(clientMenu);

        final var buttonGroupClientState = new ButtonGroup();

        startClientRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("START_MENU_ITEM"));
        startClientRadioButtonMenuItem.setAction(new StartClientAction());
        buttonGroupClientState.add(startClientRadioButtonMenuItem);
        clientMenu.add(startClientRadioButtonMenuItem);

        stopClientRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("STOP_MENU_ITEM"));
        stopClientRadioButtonMenuItem.setAction(new StopClientAction());
        buttonGroupClientState.add(stopClientRadioButtonMenuItem);
        clientMenu.add(stopClientRadioButtonMenuItem);
    }

    final var buttonGroupServerState = new ButtonGroup();
    startServerRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("START_MENU_ITEM"));
    startServerRadioButtonMenuItem.setAction(new StartServerAction());
    buttonGroupServerState.add(startServerRadioButtonMenuItem);
    serverMenu.add(startServerRadioButtonMenuItem);

    stopServerRadioButtonMenuItem = new JRadioButtonMenuItem(rb.getString("STOP_MENU_ITEM"));
    stopServerRadioButtonMenuItem.setAction(new StopServerAction());
    buttonGroupServerState.add(stopServerRadioButtonMenuItem);
    serverMenu.add(stopServerRadioButtonMenuItem);

    final var helpMenu = new JMenu(rb.getString("HELP_MENU"));
    menuBar.add(helpMenu);
    helpMenu.add(new ShowAboutDialogAction());

    frame.getContentPane().add(tabbedPane);

    settingsPanel = new JPanel();
    settingsPanel.setLayout(new GridBagLayout());

    settingsScrollPane.setViewportView(settingsPanel);
    tabbedPane.addTab(rb.getString("SETTINGS_TAB"), null, settingsScrollPane);

    final var panelGridBagConstraints = new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0.0, 0.0,
            GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 5);

    final var panelFlowLayout = new FlowLayout(FlowLayout.LEADING, 10, 10);

    final var pollIntervalPanel = new JPanel(panelFlowLayout);
    settingsPanel.add(pollIntervalPanel, panelGridBagConstraints);

    final var pollIntervalLabel = new JLabel(rb.getString("POLL_INTERVAL_LABEL"));
    pollIntervalLabel.setPreferredSize(new Dimension(120, 15));
    pollIntervalPanel.add(pollIntervalLabel);

    final var pollIntervalSpinner = new JSpinner(new SpinnerNumberModel(
            preferences.getInt(PREFERENCES_POLL_INTERVAL, OutputThread.DEFAULT_POLL_INTERVAL), 10, 500, 1));
    final JSpinner.DefaultEditor pollIntervalSpinnerEditor = new JSpinner.NumberEditor(pollIntervalSpinner,
            "#");
    ((DefaultFormatter) pollIntervalSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
    pollIntervalSpinner.setEditor(pollIntervalSpinnerEditor);
    pollIntervalSpinner.addChangeListener(
            e -> preferences.putInt(PREFERENCES_POLL_INTERVAL, (int) ((JSpinner) e.getSource()).getValue()));
    pollIntervalPanel.add(pollIntervalSpinner);

    if (windows) {
        final var vJoyDirectoryPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(vJoyDirectoryPanel, panelGridBagConstraints);

        final var vJoyDirectoryLabel = new JLabel(rb.getString("VJOY_DIRECTORY_LABEL"));
        vJoyDirectoryLabel.setPreferredSize(new Dimension(120, 15));
        vJoyDirectoryPanel.add(vJoyDirectoryLabel);

        vJoyDirectoryLabel1 = new JLabel(
                preferences.get(PREFERENCES_VJOY_DIRECTORY, VJoyOutputThread.getDefaultInstallationPath()));
        vJoyDirectoryPanel.add(vJoyDirectoryLabel1);

        final var vJoyDirectoryButton = new JButton(new ChangeVJoyDirectoryAction());
        vJoyDirectoryPanel.add(vJoyDirectoryButton);

        final var vJoyDevicePanel = new JPanel(panelFlowLayout);
        settingsPanel.add(vJoyDevicePanel, panelGridBagConstraints);

        final var vJoyDeviceLabel = new JLabel(rb.getString("VJOY_DEVICE_LABEL"));
        vJoyDeviceLabel.setPreferredSize(new Dimension(120, 15));
        vJoyDevicePanel.add(vJoyDeviceLabel);

        final var vJoyDeviceSpinner = new JSpinner(new SpinnerNumberModel(
                preferences.getInt(PREFERENCES_VJOY_DEVICE, VJoyOutputThread.DEFAULT_VJOY_DEVICE), 1, 16, 1));
        final JSpinner.DefaultEditor vJoyDeviceSpinnerEditor = new JSpinner.NumberEditor(vJoyDeviceSpinner,
                "#");
        ((DefaultFormatter) vJoyDeviceSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
        vJoyDeviceSpinner.setEditor(vJoyDeviceSpinnerEditor);
        vJoyDeviceSpinner.addChangeListener(
                e -> preferences.putInt(PREFERENCES_VJOY_DEVICE, (int) ((JSpinner) e.getSource()).getValue()));
        vJoyDevicePanel.add(vJoyDeviceSpinner);

        final var hostPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(hostPanel, panelGridBagConstraints);

        final var hostLabel = new JLabel(rb.getString("HOST_LABEL"));
        hostLabel.setPreferredSize(new Dimension(120, 15));
        hostPanel.add(hostLabel);

        hostTextField = new JTextField(preferences.get(PREFERENCES_HOST, ClientVJoyOutputThread.DEFAULT_HOST),
                10);
        final var setHostAction = new SetHostAction(hostTextField);
        hostTextField.addActionListener(setHostAction);
        hostTextField.addFocusListener(setHostAction);
        hostPanel.add(hostTextField);
    }

    final var portPanel = new JPanel(panelFlowLayout);
    settingsPanel.add(portPanel, panelGridBagConstraints);

    final var portLabel = new JLabel(rb.getString("PORT_LABEL"));
    portLabel.setPreferredSize(new Dimension(120, 15));
    portPanel.add(portLabel);

    final var portSpinner = new JSpinner(new SpinnerNumberModel(
            preferences.getInt(PREFERENCES_PORT, ServerOutputThread.DEFAULT_PORT), 1024, 65535, 1));
    final JSpinner.DefaultEditor portSpinnerEditor = new JSpinner.NumberEditor(portSpinner, "#");
    ((DefaultFormatter) portSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
    portSpinner.setEditor(portSpinnerEditor);
    portSpinner.addChangeListener(
            e -> preferences.putInt(PREFERENCES_PORT, (int) ((JSpinner) e.getSource()).getValue()));
    portPanel.add(portSpinner);

    final var timeoutPanel = new JPanel(panelFlowLayout);
    settingsPanel.add(timeoutPanel, panelGridBagConstraints);

    final var timeoutLabel = new JLabel(rb.getString("TIMEOUT_LABEL"));
    timeoutLabel.setPreferredSize(new Dimension(120, 15));
    timeoutPanel.add(timeoutLabel);

    final var timeoutSpinner = new JSpinner(new SpinnerNumberModel(
            preferences.getInt(PREFERENCES_TIMEOUT, ServerOutputThread.DEFAULT_TIMEOUT), 10, 60000, 1));
    final JSpinner.DefaultEditor timeoutSpinnerEditor = new JSpinner.NumberEditor(timeoutSpinner, "#");
    ((DefaultFormatter) timeoutSpinnerEditor.getTextField().getFormatter()).setCommitsOnValidEdit(true);
    timeoutSpinner.setEditor(timeoutSpinnerEditor);
    timeoutSpinner.addChangeListener(
            e -> preferences.putInt(PREFERENCES_TIMEOUT, (int) ((JSpinner) e.getSource()).getValue()));
    timeoutPanel.add(timeoutSpinner);

    final var alwaysOnTopSupported = Toolkit.getDefaultToolkit().isAlwaysOnTopSupported();
    if (alwaysOnTopSupported || preferences.getBoolean(PREFERENCES_SHOW_OVERLAY, alwaysOnTopSupported)) {
        final var overlaySettingsPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(overlaySettingsPanel, panelGridBagConstraints);

        final var overlayLabel = new JLabel(rb.getString("OVERLAY_LABEL"));
        overlayLabel.setPreferredSize(new Dimension(120, 15));
        overlaySettingsPanel.add(overlayLabel);

        final var showOverlayCheckBox = new JCheckBox(rb.getString("SHOW_OVERLAY_CHECK_BOX"));
        showOverlayCheckBox.setSelected(preferences.getBoolean(PREFERENCES_SHOW_OVERLAY, true));
        showOverlayCheckBox.addActionListener(e -> {
            final boolean showOverlay = ((JCheckBox) e.getSource()).isSelected();

            preferences.putBoolean(PREFERENCES_SHOW_OVERLAY, showOverlay);
        });
        overlaySettingsPanel.add(showOverlayCheckBox);
    }

    if (windows) {
        if (preferences.getBoolean(PREFERENCES_SHOW_VR_OVERLAY, true)) {
            final var vrOverlaySettingsPanel = new JPanel(panelFlowLayout);
            settingsPanel.add(vrOverlaySettingsPanel, panelGridBagConstraints);

            final var vrOverlayLabel = new JLabel(rb.getString("VR_OVERLAY_LABEL"));
            vrOverlayLabel.setPreferredSize(new Dimension(120, 15));
            vrOverlaySettingsPanel.add(vrOverlayLabel);

            final var showVrOverlayCheckBox = new JCheckBox(rb.getString("SHOW_VR_OVERLAY_CHECK_BOX"));
            showVrOverlayCheckBox.setSelected(preferences.getBoolean(PREFERENCES_SHOW_VR_OVERLAY, true));
            showVrOverlayCheckBox.addActionListener(e -> {
                final var showVrOverlay = ((JCheckBox) e.getSource()).isSelected();

                preferences.putBoolean(PREFERENCES_SHOW_VR_OVERLAY, showVrOverlay);
            });
            vrOverlaySettingsPanel.add(showVrOverlayCheckBox);
        }

        final var preventPowerSaveModeSettingsPanel = new JPanel(panelFlowLayout);
        settingsPanel.add(preventPowerSaveModeSettingsPanel, panelGridBagConstraints);

        final var preventPowerSaveModeLabel = new JLabel(rb.getString("POWER_SAVE_MODE_LABEL"));
        preventPowerSaveModeLabel.setPreferredSize(new Dimension(120, 15));
        preventPowerSaveModeSettingsPanel.add(preventPowerSaveModeLabel);

        final var preventPowerSaveModeCheckBox = new JCheckBox(
                rb.getString("PREVENT_POWER_SAVE_MODE_CHECK_BOX"));
        preventPowerSaveModeCheckBox
                .setSelected(preferences.getBoolean(PREFERENCES_PREVENT_POWER_SAVE_MODE, true));
        preventPowerSaveModeCheckBox.addActionListener(e -> {
            final var preventPowerSaveMode = ((JCheckBox) e.getSource()).isSelected();

            preferences.putBoolean(PREFERENCES_PREVENT_POWER_SAVE_MODE, preventPowerSaveMode);
        });
        preventPowerSaveModeSettingsPanel.add(preventPowerSaveModeCheckBox);
    }

    if (SystemTray.isSupported()) {
        final var popupMenu = new PopupMenu();

        final var showAction = new ShowAction();
        showMenuItem = new MenuItem((String) showAction.getValue(Action.NAME));
        showMenuItem.addActionListener(showAction);
        popupMenu.add(showMenuItem);

        popupMenu.addSeparator();

        final var openMenuItem = new MenuItem((String) openAction.getValue(Action.NAME));
        openMenuItem.addActionListener(openAction);
        popupMenu.add(openMenuItem);

        popupMenu.addSeparator();

        final var quitMenuItem = new MenuItem((String) quitAction.getValue(Action.NAME));
        quitMenuItem.addActionListener(quitAction);
        popupMenu.add(quitMenuItem);

        trayIcon = new TrayIcon(frame.getIconImage());
        trayIcon.addActionListener(showAction);
        trayIcon.setPopupMenu(popupMenu);
        try {
            SystemTray.getSystemTray().add(trayIcon);
        } catch (final AWTException e) {
            log.log(Logger.Level.ERROR, e.getMessage(), e);
        }
    }

    updateTitleAndTooltip();

    settingsPanel.add(Box.createGlue(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 1.0, 1.0,
            GridBagConstraints.FIRST_LINE_START, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));

    final var outsideBorder = BorderFactory.createEtchedBorder(EtchedBorder.RAISED);
    final var insideBorder = BorderFactory.createEmptyBorder(0, 5, 0, 5);
    statusLabel.setBorder(BorderFactory.createCompoundBorder(outsideBorder, insideBorder));
    frame.add(statusLabel, BorderLayout.SOUTH);

    final var glfwInitialized = glfwInit();
    if (!glfwInitialized)
        if (windows)
            JOptionPane.showMessageDialog(frame, rb.getString("COULD_NOT_INITIALIZE_GLFW_DIALOG_TEXT_WINDOWS"),
                    rb.getString("ERROR_DIALOG_TITLE"), JOptionPane.ERROR_MESSAGE);
        else {
            JOptionPane.showMessageDialog(frame, rb.getString("COULD_NOT_INITIALIZE_GLFW_DIALOG_TEXT"),
                    rb.getString("ERROR_DIALOG_TITLE"), JOptionPane.ERROR_MESSAGE);
            quit();
        }

    final var presentJids = new HashSet<Integer>();
    for (var jid = GLFW_JOYSTICK_1; jid <= GLFW_JOYSTICK_LAST; jid++)
        if (glfwJoystickPresent(jid) && glfwJoystickIsGamepad(jid))
            presentJids.add(jid);

    final var lastControllerGuid = preferences.get(PREFERENCES_LAST_CONTROLLER, null);
    for (final var jid : presentJids) {
        final var lastControllerFound = lastControllerGuid != null
                ? lastControllerGuid.equals(glfwGetJoystickGUID(jid))
                : false;

        if (!isSelectedJidValid() || lastControllerFound)
            selectedJid = jid;

        if (lastControllerFound)
            break;
    }

    newProfile();

    onControllersChanged(true);

    glfwSetJoystickCallback(new GLFWJoystickCallback() {

        @Override
        public void invoke(final int jid, final int event) {
            final var disconnected = event == GLFW_DISCONNECTED;
            if (disconnected || glfwJoystickIsGamepad(jid)) {
                if (disconnected && selectedJid == jid)
                    selectedJid = INVALID_JID;

                invokeOnEventDispatchThreadIfRequired(() -> onControllersChanged(false));
            }

        }
    });

    if (glfwInitialized && presentJids.isEmpty()) {
        if (windows)
            JOptionPane.showMessageDialog(frame, rb.getString("NO_CONTROLLER_CONNECTED_DIALOG_TEXT_WINDOWS"),
                    rb.getString("INFORMATION_DIALOG_TITLE"), JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog(frame, rb.getString("NO_CONTROLLER_CONNECTED_DIALOG_TEXT"),
                    rb.getString("INFORMATION_DIALOG_TITLE"), JOptionPane.INFORMATION_MESSAGE);
    } else {
        final String path = preferences.get(PREFERENCES_LAST_PROFILE, null);
        if (path != null)
            loadProfile(new File(path));
    }
}

From source file:com.vgi.mafscaling.MafCompare.java

/**
 * Initialize the contents of the frame.
 *///from w ww .j  a  va  2  s.  co  m
private void initialize() {
    try {
        ImageIcon tableImage = new ImageIcon(getClass().getResource("/table.jpg"));
        setTitle(Title);
        setIconImage(tableImage.getImage());
        setBounds(100, 100, 621, 372);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setSize(Config.getCompWindowSize());
        setLocation(Config.getCompWindowLocation());
        setLocationRelativeTo(null);
        setVisible(false);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                Utils.clearTable(origMafTable);
                Utils.clearTable(newMafTable);
                Utils.clearTable(compMafTable);
                Config.setCompWindowSize(getSize());
                Config.setCompWindowLocation(getLocation());
                origMafData.clear();
                newMafData.clear();
            }
        });

        JPanel dataPanel = new JPanel();
        GridBagLayout gbl_dataPanel = new GridBagLayout();
        gbl_dataPanel.columnWidths = new int[] { 0, 0, 0 };
        gbl_dataPanel.rowHeights = new int[] { RowHeight, RowHeight, RowHeight, RowHeight, RowHeight, 0 };
        gbl_dataPanel.columnWeights = new double[] { 0.0, 0.0, 0.0 };
        gbl_dataPanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 };
        dataPanel.setLayout(gbl_dataPanel);
        getContentPane().add(dataPanel);

        JLabel origLabel = new JLabel(origMaf);
        GridBagConstraints gbc_origLabel = new GridBagConstraints();
        gbc_origLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_origLabel.insets = new Insets(1, 1, 1, 5);
        gbc_origLabel.weightx = 0;
        gbc_origLabel.weighty = 0;
        gbc_origLabel.gridx = 0;
        gbc_origLabel.gridy = 0;
        gbc_origLabel.gridheight = 2;
        dataPanel.add(origLabel, gbc_origLabel);

        JLabel newLabel = new JLabel(newMaf);
        GridBagConstraints gbc_newLabel = new GridBagConstraints();
        gbc_newLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_newLabel.insets = new Insets(1, 1, 1, 5);
        gbc_newLabel.weightx = 0;
        gbc_newLabel.weighty = 0;
        gbc_newLabel.gridx = 0;
        gbc_newLabel.gridy = 2;
        gbc_newLabel.gridheight = 2;
        dataPanel.add(newLabel, gbc_newLabel);

        JLabel compLabel = new JLabel("Change");
        GridBagConstraints gbc_compLabel = new GridBagConstraints();
        gbc_compLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_compLabel.insets = new Insets(1, 1, 1, 5);
        gbc_compLabel.weightx = 0;
        gbc_compLabel.weighty = 0;
        gbc_compLabel.gridx = 0;
        gbc_compLabel.gridy = 4;
        dataPanel.add(compLabel, gbc_compLabel);

        JLabel origVoltLabel = new JLabel("volt");
        GridBagConstraints gbc_origVoltLabel = new GridBagConstraints();
        gbc_origVoltLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_origVoltLabel.insets = new Insets(1, 1, 1, 5);
        gbc_origVoltLabel.weightx = 0;
        gbc_origVoltLabel.weighty = 0;
        gbc_origVoltLabel.gridx = 1;
        gbc_origVoltLabel.gridy = 0;
        dataPanel.add(origVoltLabel, gbc_origVoltLabel);

        JLabel origGsLabel = new JLabel(" g/s");
        GridBagConstraints gbc_origGsLabel = new GridBagConstraints();
        gbc_origGsLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_origGsLabel.insets = new Insets(1, 1, 1, 5);
        gbc_origGsLabel.weightx = 0;
        gbc_origGsLabel.weighty = 0;
        gbc_origGsLabel.gridx = 1;
        gbc_origGsLabel.gridy = 1;
        dataPanel.add(origGsLabel, gbc_origGsLabel);

        JLabel newVoltLabel = new JLabel("volt");
        GridBagConstraints gbc_newVoltLabel = new GridBagConstraints();
        gbc_newVoltLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_newVoltLabel.insets = new Insets(1, 1, 1, 5);
        gbc_newVoltLabel.weightx = 0;
        gbc_newVoltLabel.weighty = 0;
        gbc_newVoltLabel.gridx = 1;
        gbc_newVoltLabel.gridy = 2;
        dataPanel.add(newVoltLabel, gbc_newVoltLabel);

        JLabel newGsLabel = new JLabel(" g/s");
        GridBagConstraints gbc_newGsLabel = new GridBagConstraints();
        gbc_newGsLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_newGsLabel.insets = new Insets(1, 1, 1, 5);
        gbc_newGsLabel.weightx = 0;
        gbc_newGsLabel.weighty = 0;
        gbc_newGsLabel.gridx = 1;
        gbc_newGsLabel.gridy = 3;
        dataPanel.add(newGsLabel, gbc_newGsLabel);

        JLabel compPctLabel = new JLabel(" %  ");
        GridBagConstraints gbc_compPctLabel = new GridBagConstraints();
        gbc_compPctLabel.anchor = GridBagConstraints.PAGE_START;
        gbc_compPctLabel.insets = new Insets(1, 1, 1, 5);
        gbc_compPctLabel.weightx = 0;
        gbc_compPctLabel.weighty = 0;
        gbc_compPctLabel.gridx = 1;
        gbc_compPctLabel.gridy = 4;
        dataPanel.add(compPctLabel, gbc_compPctLabel);

        JPanel tablesPanel = new JPanel();
        GridBagLayout gbl_tablesPanel = new GridBagLayout();
        gbl_tablesPanel.columnWidths = new int[] { 0 };
        gbl_tablesPanel.rowHeights = new int[] { 0, 0, 0 };
        gbl_tablesPanel.columnWeights = new double[] { 0.0 };
        gbl_tablesPanel.rowWeights = new double[] { 0.0, 0.0, 1.0 };
        tablesPanel.setLayout(gbl_tablesPanel);

        JScrollPane mafScrollPane = new JScrollPane(tablesPanel);
        mafScrollPane.setMinimumSize(new Dimension(1600, 107));
        mafScrollPane.getHorizontalScrollBar().setMaximumSize(new Dimension(20, 20));
        mafScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
        mafScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        GridBagConstraints gbc_mafScrollPane = new GridBagConstraints();
        gbc_mafScrollPane.weightx = 1.0;
        gbc_mafScrollPane.anchor = GridBagConstraints.PAGE_START;
        gbc_mafScrollPane.fill = GridBagConstraints.HORIZONTAL;
        gbc_mafScrollPane.gridx = 2;
        gbc_mafScrollPane.gridy = 0;
        gbc_mafScrollPane.gridheight = 5;
        dataPanel.add(mafScrollPane, gbc_mafScrollPane);

        origMafTable = new JTable();
        origMafTable.setColumnSelectionAllowed(true);
        origMafTable.setCellSelectionEnabled(true);
        origMafTable.setBorder(new LineBorder(new Color(0, 0, 0)));
        origMafTable.setRowHeight(RowHeight);
        origMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        origMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        origMafTable.setModel(new DefaultTableModel(2, MafTableColumnCount));
        origMafTable.setTableHeader(null);
        Utils.initializeTable(origMafTable, ColumnWidth);
        GridBagConstraints gbc_origMafTable = new GridBagConstraints();
        gbc_origMafTable.anchor = GridBagConstraints.PAGE_START;
        gbc_origMafTable.insets = new Insets(0, 0, 0, 0);
        gbc_origMafTable.fill = GridBagConstraints.HORIZONTAL;
        gbc_origMafTable.weightx = 1.0;
        gbc_origMafTable.weighty = 0;
        gbc_origMafTable.gridx = 0;
        gbc_origMafTable.gridy = 0;
        tablesPanel.add(origMafTable, gbc_origMafTable);
        excelAdapter.addTable(origMafTable, false, false, false, false, true, false, true, false, true);

        newMafTable = new JTable();
        newMafTable.setColumnSelectionAllowed(true);
        newMafTable.setCellSelectionEnabled(true);
        newMafTable.setBorder(new LineBorder(new Color(0, 0, 0)));
        newMafTable.setRowHeight(RowHeight);
        newMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        newMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        newMafTable.setModel(new DefaultTableModel(2, MafTableColumnCount));
        newMafTable.setTableHeader(null);
        Utils.initializeTable(newMafTable, ColumnWidth);
        GridBagConstraints gbc_newMafTable = new GridBagConstraints();
        gbc_newMafTable.anchor = GridBagConstraints.PAGE_START;
        gbc_newMafTable.insets = new Insets(0, 0, 0, 0);
        gbc_newMafTable.fill = GridBagConstraints.HORIZONTAL;
        gbc_newMafTable.weightx = 1.0;
        gbc_newMafTable.weighty = 0;
        gbc_newMafTable.gridx = 0;
        gbc_newMafTable.gridy = 1;
        tablesPanel.add(newMafTable, gbc_newMafTable);
        excelAdapter.addTable(newMafTable, false, false, false, false, false, false, false, false, true);

        compMafTable = new JTable();
        compMafTable.setColumnSelectionAllowed(true);
        compMafTable.setCellSelectionEnabled(true);
        compMafTable.setBorder(new LineBorder(new Color(0, 0, 0)));
        compMafTable.setRowHeight(RowHeight);
        compMafTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        compMafTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        compMafTable.setModel(new DefaultTableModel(1, MafTableColumnCount));
        compMafTable.setTableHeader(null);
        Utils.initializeTable(compMafTable, ColumnWidth);
        NumberFormatRenderer numericRenderer = new NumberFormatRenderer();
        numericRenderer.setFormatter(new DecimalFormat("0.000"));
        compMafTable.setDefaultRenderer(Object.class, numericRenderer);
        GridBagConstraints gbc_compMafTable = new GridBagConstraints();
        gbc_compMafTable.anchor = GridBagConstraints.PAGE_START;
        gbc_compMafTable.insets = new Insets(0, 0, 0, 0);
        gbc_compMafTable.fill = GridBagConstraints.HORIZONTAL;
        gbc_compMafTable.weightx = 1.0;
        gbc_compMafTable.weighty = 0;
        gbc_compMafTable.gridx = 0;
        gbc_compMafTable.gridy = 2;
        tablesPanel.add(compMafTable, gbc_compMafTable);
        compExcelAdapter.addTable(compMafTable, false, true, false, false, false, true, true, false, true);

        TableModelListener origTableListener = new TableModelListener() {
            public void tableChanged(TableModelEvent tme) {
                if (tme.getType() == TableModelEvent.UPDATE) {
                    int colCount = origMafTable.getColumnCount();
                    Utils.ensureColumnCount(colCount, newMafTable);
                    Utils.ensureColumnCount(colCount, compMafTable);
                    origMafData.clear();
                    String origY, origX, newY;
                    for (int i = 0; i < colCount; ++i) {
                        origY = origMafTable.getValueAt(1, i).toString();
                        if (Pattern.matches(Utils.fpRegex, origY)) {
                            origX = origMafTable.getValueAt(0, i).toString();
                            if (Pattern.matches(Utils.fpRegex, origX))
                                origMafData.add(Double.valueOf(origX), Double.valueOf(origY), false);
                            newY = newMafTable.getValueAt(1, i).toString();
                            if (Pattern.matches(Utils.fpRegex, newY))
                                compMafTable.setValueAt(
                                        ((Double.valueOf(newY) / Double.valueOf(origY)) - 1.0) * 100.0, 0, i);
                        } else
                            break;
                    }
                    origMafData.fireSeriesChanged();
                }
            }
        };

        TableModelListener newTableListener = new TableModelListener() {
            public void tableChanged(TableModelEvent tme) {
                if (tme.getType() == TableModelEvent.UPDATE) {
                    int colCount = newMafTable.getColumnCount();
                    Utils.ensureColumnCount(colCount, origMafTable);
                    Utils.ensureColumnCount(colCount, compMafTable);
                    newMafData.clear();
                    String newY, newX, origY;
                    for (int i = 0; i < colCount; ++i) {
                        newY = newMafTable.getValueAt(1, i).toString();
                        if (Pattern.matches(Utils.fpRegex, newY)) {
                            newX = newMafTable.getValueAt(0, i).toString();
                            if (Pattern.matches(Utils.fpRegex, newX))
                                newMafData.add(Double.valueOf(newX), Double.valueOf(newY), false);
                            origY = origMafTable.getValueAt(1, i).toString();
                            if (Pattern.matches(Utils.fpRegex, origY))
                                compMafTable.setValueAt(
                                        ((Double.valueOf(newY) / Double.valueOf(origY)) - 1.0) * 100.0, 0, i);
                        } else
                            break;
                    }
                    newMafData.fireSeriesChanged();
                }
            }
        };

        origMafTable.getModel().addTableModelListener(origTableListener);
        newMafTable.getModel().addTableModelListener(newTableListener);

        Action action = new AbstractAction() {
            private static final long serialVersionUID = 8148393537657380215L;

            public void actionPerformed(ActionEvent e) {
                TableCellListener tcl = (TableCellListener) e.getSource();
                if (Pattern.matches(Utils.fpRegex, compMafTable.getValueAt(0, tcl.getColumn()).toString())) {
                    if (Pattern.matches(Utils.fpRegex,
                            origMafTable.getValueAt(1, tcl.getColumn()).toString())) {
                        double corr = Double.valueOf(compMafTable.getValueAt(0, tcl.getColumn()).toString())
                                / 100.0 + 1.0;
                        newMafTable.setValueAt(
                                Double.valueOf(origMafTable.getValueAt(1, tcl.getColumn()).toString()) * corr,
                                1, tcl.getColumn());
                    }
                } else
                    compMafTable.setValueAt(tcl.getOldValue(), 0, tcl.getColumn());
            }
        };

        setCompMafCellListener(new TableCellListener(compMafTable, action));

        // CHART

        JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, null, PlotOrientation.VERTICAL,
                false, true, false);
        chart.setBorderVisible(true);
        chartPanel = new ChartPanel(chart, true, true, true, true, true);
        chartPanel.setAutoscrolls(true);

        GridBagConstraints gbl_chartPanel = new GridBagConstraints();
        gbl_chartPanel.anchor = GridBagConstraints.PAGE_START;
        gbl_chartPanel.fill = GridBagConstraints.BOTH;
        gbl_chartPanel.insets = new Insets(1, 1, 1, 1);
        gbl_chartPanel.weightx = 1.0;
        gbl_chartPanel.weighty = 1.0;
        gbl_chartPanel.gridx = 0;
        gbl_chartPanel.gridy = 5;
        gbl_chartPanel.gridheight = 1;
        gbl_chartPanel.gridwidth = 3;
        dataPanel.add(chartPanel, gbl_chartPanel);

        XYSplineRenderer lineRenderer = new XYSplineRenderer(3);
        lineRenderer.setUseFillPaint(true);
        lineRenderer.setBaseToolTipGenerator(
                new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                        new DecimalFormat("0.00"), new DecimalFormat("0.00")));

        Stroke stroke = new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, null, 0.0f);
        lineRenderer.setSeriesStroke(0, stroke);
        lineRenderer.setSeriesStroke(1, stroke);
        lineRenderer.setSeriesPaint(0, new Color(201, 0, 0));
        lineRenderer.setSeriesPaint(1, new Color(0, 0, 255));
        lineRenderer.setSeriesShape(0, ShapeUtilities.createDiamond((float) 2.5));
        lineRenderer.setSeriesShape(1, ShapeUtilities.createDownTriangle((float) 2.5));
        lineRenderer.setLegendItemLabelGenerator(new StandardXYSeriesLabelGenerator() {
            private static final long serialVersionUID = -4045338273187150888L;

            public String generateLabel(XYDataset dataset, int series) {
                XYSeries xys = ((XYSeriesCollection) dataset).getSeries(series);
                return xys.getDescription();
            }
        });

        NumberAxis mafvDomain = new NumberAxis(XAxisName);
        mafvDomain.setAutoRangeIncludesZero(false);
        mafvDomain.setAutoRange(true);
        mafvDomain.setAutoRangeStickyZero(false);
        NumberAxis mafgsRange = new NumberAxis(YAxisName);
        mafgsRange.setAutoRangeIncludesZero(false);
        mafgsRange.setAutoRange(true);
        mafgsRange.setAutoRangeStickyZero(false);

        XYSeriesCollection lineDataset = new XYSeriesCollection();
        origMafData.setDescription(origMaf);
        newMafData.setDescription(newMaf);
        lineDataset.addSeries(origMafData);
        lineDataset.addSeries(newMafData);

        XYPlot plot = chart.getXYPlot();
        plot.setRangePannable(true);
        plot.setDomainPannable(true);
        plot.setDomainGridlinePaint(Color.DARK_GRAY);
        plot.setRangeGridlinePaint(Color.DARK_GRAY);
        plot.setBackgroundPaint(new Color(224, 224, 224));

        plot.setDataset(0, lineDataset);
        plot.setRenderer(0, lineRenderer);
        plot.setDomainAxis(0, mafvDomain);
        plot.setRangeAxis(0, mafgsRange);
        plot.mapDatasetToDomainAxis(0, 0);
        plot.mapDatasetToRangeAxis(0, 0);

        LegendTitle legend = new LegendTitle(plot.getRenderer());
        legend.setItemFont(new Font("Arial", 0, 10));
        legend.setPosition(RectangleEdge.TOP);
        chart.addLegend(legend);

    } catch (Exception e) {
        logger.error(e);
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

    // TABS //

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

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

    final JPanel createResponseTab = new JPanel();

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

    // RESPONSE MODEL TAB //

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

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

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

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

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

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

    // RESPONSE PARAMETERS //

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

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

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

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

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

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

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

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

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

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

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

    // SELECT ACTIVITY MODEL //

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

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

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

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

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

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

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

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

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

    final JTextPane newPricingSchemePane = new JTextPane();

    newPricingScrollPane.setViewportView(newPricingSchemePane);

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

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

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

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

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

    // PANELS //

    // DATA IMPORT TAB //

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

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

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

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

    // TRAINING ACTIVITY TAB //

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

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

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

    // EXPORT TAB //

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

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

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

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

    // COMPONENTS //

    // IMPORT TAB //

    // DATA IMPORT //

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // TRAINING PARAMETERS //

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // APPLIANCE SELECTION //

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

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

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

    // DISTRIBUTION SELECTION //

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

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

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

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

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

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

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

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

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

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

    // EXPORT TAB //

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // IMPORT TAB //

    // DATA IMPORT ////

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

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

            int returnVal = fc.showOpenDialog(contentPane);

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

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

        }
    });

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

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

            int returnVal = fc.showOpenDialog(contentPane);

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

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

        }
    });

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

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

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

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

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

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

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

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

        }
    });

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

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

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

            try {

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

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

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

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

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

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

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

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

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

                    }

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

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

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

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

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

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

            try {

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

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

                File file = new File(filename);

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

                String fileNameWithExtension = file.getName();

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

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

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

                        Disaggregate dis = new Disaggregate(folder, fileNameWithExtension);

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

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

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

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

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

                        String type = "";

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

                        }

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

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

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

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

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

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

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

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

                    input.close();

                    // Read activity file and start activity parsing

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

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

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

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

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

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

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

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

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

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

                    input.close();

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

                        Appliance tempAppliance = temp.toAppliance();

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

                    }

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

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

                    }

                }
                // In case of an error.
                else {

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

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

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

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

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

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

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

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

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

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

            try {

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

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

                Appliance appliance = null;
                try {

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

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

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

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

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

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

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

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

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

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

                String selection = detectedApplianceList.getSelectedValue();

                Appliance current = installation.findAppliance(selection);

                ChartPanel chartPanel = current.consumptionGraph();

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

            }
        }
    });

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

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

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

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

            try {

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

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

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

                Appliance current = installation.findAppliance(selection);

                String startTime, duration, dailyTimes;

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

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

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

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

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

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

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

                }

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

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

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

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

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

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

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

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

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

                activitySelectList.setModel(activityModels);

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

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

                exportModelList.setModel(exportModels);

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

                tabbedPane.setEnabledAt(2, true);
            }

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

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

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

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

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

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

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

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

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

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

        }
    });

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

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

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

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

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

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

        }
    });

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

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

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

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

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

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

        }
    });

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

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

            String selection = selectedApplianceList.getSelectedValue();

            Appliance current = installation.findAppliance(selection);

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

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

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

        }
    });

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

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

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

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

                Appliance currentAppliance = installation.findAppliance(selection);

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

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

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

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

                if (activityModel != null) {

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

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

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

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

        }
    });

    // RESPONSE TAB //

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

        }

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

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

            try {

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

                responsePanel.removeAll();

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

                int response = -1;

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

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

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

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

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

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

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

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

            try {

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

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

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

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

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

                String response = "";

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

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

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

                    exc.printStackTrace();
                }

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

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

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

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

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

                if (manyFlag == false) {

                    JFrame success = new JFrame();

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

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

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

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

            JFrame success = new JFrame();

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

            manyFlag = false;
        }
    });

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

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

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

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

            try {

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

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

                pricingPreviewPanel.removeAll();

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

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

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

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

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

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

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

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

                        previewResponseButton.setEnabled(true);

                    } else {
                        JFrame error = new JFrame();

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

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

            }

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

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

            try {

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

                responsePanel.removeAll();

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

                int response = -1;

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

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

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

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

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

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

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

        }
    });

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

            try {

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

                responsePanel.removeAll();

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

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

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

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

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

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

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

        }
    });

    // EXPORT TAB //

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

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

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

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

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

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

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

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

                        try {
                            chartPanel = installation.measurementsChart();

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

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

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

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

                    } else if (appliance != null) {

                        chartPanel = appliance.consumptionGraph();

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

                    } else if (activity != null) {

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

                        chartPanel = response.createDailyTimesDistributionChart();

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

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

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

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

            String selection = exportModelList.getSelectedValue();

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

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

            ChartPanel chartPanel = null;

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

            else
                chartPanel = response.createDailyTimesDistributionChart();

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

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

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

            String selection = exportModelList.getSelectedValue();

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

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

            ChartPanel chartPanel = null;

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

            else
                chartPanel = response.createStartTimeBinnedDistributionChart();

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

        }
    });

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

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

            String selection = exportModelList.getSelectedValue();

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

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

            ChartPanel chartPanel = null;

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

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

        }
    });

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

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

            String selection = exportModelList.getSelectedValue();

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

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

            ChartPanel chartPanel = null;

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

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

        }
    });

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

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

            String selection = exportModelList.getSelectedValue();

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

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

            ChartPanel chartPanel = null;

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

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

        }
    });

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

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

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

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

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

        }
    });

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

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

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

            try {

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

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

                Appliance appliance = installation.findAppliance(selection);

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

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

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

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

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

                    installation.setName(oldName);

                    JFrame success = new JFrame();

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

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

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

                    JFrame success = new JFrame();

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

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

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

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

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

                    JFrame success = new JFrame();

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

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

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

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

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

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

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

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

                    }

                    try {

                        String[] appliancesID = applianceTemp;

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

                        activityTemp = activity.getActivityModelID();

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

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

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

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

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

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

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

                    } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) {

                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

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

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

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

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

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

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

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

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

                    try {

                        String[] appliancesID = applianceTemp;

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

                        responseTemp = response.getActivityModelID();

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

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

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

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

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

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

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

                    } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) {

                        e1.printStackTrace();
                    }

                    JFrame success = new JFrame();

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

                }
            }

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

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

            try {

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

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

                    String selection = exportModelList.getSelectedValue();

                    Appliance appliance = installation.findAppliance(selection);

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

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

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

                        String oldName = installation.getName();

                        try {

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

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

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

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

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

                    } else if (appliance != null) {

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

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

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

                    } else if (activity != null) {

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

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

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

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

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

                        try {

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

                            String[] appliancesID = applianceTemp;

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

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

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

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

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

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

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

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

                    } else if (response != null) {

                    }
                }

            }

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

            JFrame success = new JFrame();

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

        }
    });

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

            try {

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

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

                    String selection = exportModelList.getSelectedValue();

                    Appliance appliance = installation.findAppliance(selection);

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

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

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

                        String oldName = installation.getName();

                        try {

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

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

                            installation.setName(oldName);

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

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

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

                    } else if (appliance != null) {

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

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

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

                    } else if (activity != null) {

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

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

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

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

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

                        try {

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

                            String[] appliancesID = applianceTemp;

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

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

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

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

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

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

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

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

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

            JFrame success = new JFrame();

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

From source file:org.freeplane.view.swing.features.time.mindmapmode.nodelist.NodeList.java

public void startup() {
    if (dialog != null) {
        dialog.toFront();/*w w w  . j a  v a2s . com*/
        return;
    }
    NodeList.COLUMN_MODIFIED = TextUtils.getText(PLUGINS_TIME_LIST_XML_MODIFIED);
    NodeList.COLUMN_CREATED = TextUtils.getText(PLUGINS_TIME_LIST_XML_CREATED);
    NodeList.COLUMN_ICONS = TextUtils.getText(PLUGINS_TIME_LIST_XML_ICONS);
    NodeList.COLUMN_TEXT = TextUtils.getText(PLUGINS_TIME_LIST_XML_TEXT);
    NodeList.COLUMN_DETAILS = TextUtils.getText(PLUGINS_TIME_LIST_XML_DETAILS);
    NodeList.COLUMN_DATE = TextUtils.getText(PLUGINS_TIME_LIST_XML_DATE);
    NodeList.COLUMN_NOTES = TextUtils.getText(PLUGINS_TIME_LIST_XML_NOTES);
    dialog = new JDialog(Controller.getCurrentController().getViewController().getFrame(), modal /* modal */);
    String windowTitle;
    if (showAllNodes) {
        windowTitle = PLUGINS_TIME_MANAGEMENT_XML_WINDOW_TITLE_ALL_NODES;
    } else {
        windowTitle = PLUGINS_TIME_MANAGEMENT_XML_WINDOW_TITLE;
    }
    dialog.setTitle(TextUtils.getText(windowTitle));
    dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    final WindowAdapter windowListener = new WindowAdapter() {

        @Override
        public void windowGainedFocus(WindowEvent e) {
            mFilterTextSearchField.getEditor().selectAll();
        }

        @Override
        public void windowClosing(final WindowEvent event) {
            disposeDialog();
        }
    };
    dialog.addWindowListener(windowListener);
    dialog.addWindowFocusListener(windowListener);
    UITools.addEscapeActionToDialog(dialog, new AbstractAction() {
        /**
         *
         */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            disposeDialog();
        }
    });
    final Container contentPane = dialog.getContentPane();
    final GridBagLayout gbl = new GridBagLayout();
    contentPane.setLayout(gbl);
    final GridBagConstraints layoutConstraints = new GridBagConstraints();
    layoutConstraints.gridx = 0;
    layoutConstraints.gridy = 0;
    layoutConstraints.gridwidth = 1;
    layoutConstraints.gridheight = 1;
    layoutConstraints.weightx = 0.0;
    layoutConstraints.weighty = 0.0;
    layoutConstraints.anchor = GridBagConstraints.WEST;
    layoutConstraints.fill = GridBagConstraints.HORIZONTAL;
    contentPane.add(new JLabel(TextUtils.getText(PLUGINS_TIME_MANAGEMENT_XML_FIND)), layoutConstraints);
    layoutConstraints.gridwidth = 1;
    layoutConstraints.gridx++;
    contentPane.add(Box.createHorizontalStrut(40), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(new JLabel(TextUtils.getText("filter_match_case")), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(matchCase, layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(Box.createHorizontalStrut(40), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(new JLabel(TextUtils.getText("regular_expressions")), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(useRegexInFind, layoutConstraints);
    layoutConstraints.gridx = 0;
    layoutConstraints.weightx = 1.0;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    layoutConstraints.gridy++;
    contentPane.add(/* new JScrollPane */(mFilterTextSearchField), layoutConstraints);
    layoutConstraints.gridy++;
    layoutConstraints.weightx = 0.0;
    layoutConstraints.gridwidth = 1;
    contentPane.add(new JLabel(TextUtils.getText(PLUGINS_TIME_MANAGEMENT_XML_REPLACE)), layoutConstraints);
    layoutConstraints.gridx = 5;
    contentPane.add(new JLabel(TextUtils.getText("regular_expressions")), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(useRegexInReplace, layoutConstraints);
    layoutConstraints.gridx = 0;
    layoutConstraints.weightx = 1.0;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    layoutConstraints.gridy++;
    contentPane.add(/* new JScrollPane */(mFilterTextReplaceField), layoutConstraints);
    dateRenderer = new DateRenderer();
    textRenderer = new TextRenderer();
    iconsRenderer = new IconsRenderer();
    tableView = new FlatNodeTable();
    tableView.addKeyListener(new FlatNodeTableKeyListener());
    tableView.addMouseListener(new FlatNodeTableMouseAdapter());
    tableView.getTableHeader().setReorderingAllowed(false);
    tableModel = updateModel();
    mFlatNodeTableFilterModel = new FlatNodeTableFilterModel(tableModel,
            new int[] { NodeList.NODE_TEXT_COLUMN, NodeList.NODE_DETAILS_COLUMN, NodeList.NODE_NOTES_COLUMN });
    sorter = new TableSorter(mFlatNodeTableFilterModel);
    tableView.setModel(sorter);
    sorter.setTableHeader(tableView.getTableHeader());
    sorter.setColumnComparator(Date.class, TableSorter.COMPARABLE_COMPARATOR);
    sorter.setColumnComparator(NodeModel.class, TableSorter.LEXICAL_COMPARATOR);
    sorter.setColumnComparator(IconsHolder.class, TableSorter.COMPARABLE_COMPARATOR);
    sorter.setSortingStatus(NodeList.DATE_COLUMN, TableSorter.ASCENDING);
    final JScrollPane pane = new JScrollPane(tableView);
    UITools.setScrollbarIncrement(pane);
    layoutConstraints.gridy++;
    GridBagConstraints tableConstraints = (GridBagConstraints) layoutConstraints.clone();
    tableConstraints.weightx = 1;
    tableConstraints.weighty = 10;
    tableConstraints.fill = GridBagConstraints.BOTH;
    contentPane.add(pane, tableConstraints);
    mTreeLabel = new JLabel();
    layoutConstraints.gridy++;
    GridBagConstraints treeConstraints = (GridBagConstraints) layoutConstraints.clone();
    treeConstraints.fill = GridBagConstraints.BOTH;
    @SuppressWarnings("serial")
    JScrollPane scrollPane = new JScrollPane(mTreeLabel) {
        @Override
        public boolean isValidateRoot() {
            return false;
        }
    };
    contentPane.add(scrollPane, treeConstraints);
    final AbstractAction exportAction = new AbstractAction(
            TextUtils.getText("plugins/TimeManagement.xml_Export")) {
        /**
             *
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            exportSelectedRowsAndClose();
        }
    };
    final JButton exportButton = new JButton(exportAction);
    final AbstractAction replaceAllAction = new AbstractAction(
            TextUtils.getText("plugins/TimeManagement.xml_Replace_All")) {
        /**
             *
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            replace(new HolderAccessor(false));
        }
    };
    final JButton replaceAllButton = new JButton(replaceAllAction);
    final AbstractAction replaceSelectedAction = new AbstractAction(
            TextUtils.getText("plugins/TimeManagement.xml_Replace_Selected")) {
        /**
             *
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            replace(new HolderAccessor(true));
        }
    };
    final JButton replaceSelectedButton = new JButton(replaceSelectedAction);
    final AbstractAction gotoAction = new AbstractAction(TextUtils.getText("plugins/TimeManagement.xml_Goto")) {
        /**
             *
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            selectSelectedRows();
        }
    };
    final JButton gotoButton = new JButton(gotoAction);
    final AbstractAction disposeAction = new AbstractAction(
            TextUtils.getText(PLUGINS_TIME_MANAGEMENT_XML_CLOSE)) {
        /**
             *
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            disposeDialog();
        }
    };
    final JButton cancelButton = new JButton(disposeAction);
    /* Initial State */
    gotoAction.setEnabled(false);
    exportAction.setEnabled(false);
    replaceSelectedAction.setEnabled(false);
    final Box bar = Box.createHorizontalBox();
    bar.add(Box.createHorizontalGlue());
    bar.add(cancelButton);
    bar.add(exportButton);
    bar.add(replaceAllButton);
    bar.add(replaceSelectedButton);
    bar.add(gotoButton);
    bar.add(Box.createHorizontalGlue());
    layoutConstraints.gridy++;
    contentPane.add(/* new JScrollPane */(bar), layoutConstraints);
    final JMenuBar menuBar = new JMenuBar();
    final JMenu menu = new JMenu(TextUtils.getText("plugins/TimeManagement.xml_menu_actions"));
    final AbstractAction[] actionList = new AbstractAction[] { gotoAction, replaceSelectedAction,
            replaceAllAction, exportAction, disposeAction };
    for (int i = 0; i < actionList.length; i++) {
        final AbstractAction action = actionList[i];
        final JMenuItem item = menu.add(action);
        item.setIcon(new BlindIcon(UIBuilder.ICON_SIZE));
    }
    menuBar.add(menu);
    dialog.setJMenuBar(menuBar);
    final ListSelectionModel rowSM = tableView.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            final ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            final boolean enable = !(lsm.isSelectionEmpty());
            replaceSelectedAction.setEnabled(enable);
            gotoAction.setEnabled(enable);
            exportAction.setEnabled(enable);
        }
    });
    rowSM.addListSelectionListener(new ListSelectionListener() {
        String getNodeText(final NodeModel node) {
            return TextController.getController().getShortText(node)
                    + ((node.isRoot()) ? "" : (" <- " + getNodeText(node.getParentNode())));
        }

        public void valueChanged(final ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            final ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (lsm.isSelectionEmpty()) {
                mTreeLabel.setText("");
                return;
            }
            final int selectedRow = lsm.getLeadSelectionIndex();
            final NodeModel mindMapNode = getMindMapNode(selectedRow);
            mTreeLabel.setText(getNodeText(mindMapNode));
        }
    });
    final String marshalled = ResourceController.getResourceController()
            .getProperty(NodeList.WINDOW_PREFERENCE_STORAGE_PROPERTY);
    final WindowConfigurationStorage result = TimeWindowConfigurationStorage.decorateDialog(marshalled, dialog);
    final WindowConfigurationStorage storage = result;
    if (storage != null) {
        tableView.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        int column = 0;
        for (final TimeWindowColumnSetting setting : ((TimeWindowConfigurationStorage) storage)
                .getListTimeWindowColumnSettingList()) {
            tableView.getColumnModel().getColumn(column).setPreferredWidth(setting.getColumnWidth());
            sorter.setSortingStatus(column, setting.getColumnSorting());
            column++;
        }
    }
    mFlatNodeTableFilterModel.setFilter((String) mFilterTextSearchField.getSelectedItem(),
            matchCase.isSelected(), useRegexInFind.isSelected());
    dialog.setVisible(true);
}

From source file:org.freeplane.view.swing.features.time.mindmapmode.NodeList.java

public void startup() {
    if (dialog != null) {
        dialog.toFront();//from   w w w.j a  va 2  s.c  o m
        return;
    }
    NodeList.COLUMN_MODIFIED = TextUtils.getText(PLUGINS_TIME_LIST_XML_MODIFIED);
    NodeList.COLUMN_CREATED = TextUtils.getText(PLUGINS_TIME_LIST_XML_CREATED);
    NodeList.COLUMN_ICONS = TextUtils.getText(PLUGINS_TIME_LIST_XML_ICONS);
    NodeList.COLUMN_TEXT = TextUtils.getText(PLUGINS_TIME_LIST_XML_TEXT);
    NodeList.COLUMN_DATE = TextUtils.getText(PLUGINS_TIME_LIST_XML_DATE);
    NodeList.COLUMN_NOTES = TextUtils.getText(PLUGINS_TIME_LIST_XML_NOTES);
    dialog = new JDialog(Controller.getCurrentController().getViewController().getFrame(), modal /* modal */);
    String windowTitle;
    if (showAllNodes) {
        windowTitle = PLUGINS_TIME_MANAGEMENT_XML_WINDOW_TITLE_ALL_NODES;
    } else {
        windowTitle = PLUGINS_TIME_MANAGEMENT_XML_WINDOW_TITLE;
    }
    dialog.setTitle(TextUtils.getText(windowTitle));
    dialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    final WindowAdapter windowListener = new WindowAdapter() {

        @Override
        public void windowGainedFocus(WindowEvent e) {
            mFilterTextSearchField.getEditor().selectAll();
        }

        @Override
        public void windowClosing(final WindowEvent event) {
            disposeDialog();
        }
    };
    dialog.addWindowListener(windowListener);
    dialog.addWindowFocusListener(windowListener);
    UITools.addEscapeActionToDialog(dialog, new AbstractAction() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            disposeDialog();
        }
    });
    final Container contentPane = dialog.getContentPane();
    final GridBagLayout gbl = new GridBagLayout();
    contentPane.setLayout(gbl);
    final GridBagConstraints layoutConstraints = new GridBagConstraints();
    layoutConstraints.gridx = 0;
    layoutConstraints.gridy = 0;
    layoutConstraints.gridwidth = 1;
    layoutConstraints.gridheight = 1;
    layoutConstraints.weightx = 0.0;
    layoutConstraints.weighty = 0.0;
    layoutConstraints.anchor = GridBagConstraints.WEST;
    layoutConstraints.fill = GridBagConstraints.HORIZONTAL;
    contentPane.add(new JLabel(TextUtils.getText(PLUGINS_TIME_MANAGEMENT_XML_FIND)), layoutConstraints);
    layoutConstraints.gridwidth = 1;
    layoutConstraints.gridx++;
    contentPane.add(Box.createHorizontalStrut(40), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(new JLabel(TextUtils.getText("filter_match_case")), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(matchCase, layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(Box.createHorizontalStrut(40), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(new JLabel(TextUtils.getText("regular_expressions")), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(useRegexInFind, layoutConstraints);
    layoutConstraints.gridx = 0;
    layoutConstraints.weightx = 1.0;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    layoutConstraints.gridy++;
    contentPane.add(/* new JScrollPane */(mFilterTextSearchField), layoutConstraints);
    layoutConstraints.gridy++;
    layoutConstraints.weightx = 0.0;
    layoutConstraints.gridwidth = 1;
    contentPane.add(new JLabel(TextUtils.getText(PLUGINS_TIME_MANAGEMENT_XML_REPLACE)), layoutConstraints);
    layoutConstraints.gridx = 5;
    contentPane.add(new JLabel(TextUtils.getText("regular_expressions")), layoutConstraints);
    layoutConstraints.gridx++;
    contentPane.add(useRegexInReplace, layoutConstraints);
    layoutConstraints.gridx = 0;
    layoutConstraints.weightx = 1.0;
    layoutConstraints.gridwidth = GridBagConstraints.REMAINDER;
    layoutConstraints.gridy++;
    contentPane.add(/* new JScrollPane */(mFilterTextReplaceField), layoutConstraints);
    dateRenderer = new DateRenderer();
    nodeRenderer = new NodeRenderer();
    notesRenderer = new NotesRenderer();
    iconsRenderer = new IconsRenderer();
    timeTable = new FlatNodeTable();
    timeTable.addKeyListener(new FlatNodeTableKeyListener());
    timeTable.addMouseListener(new FlatNodeTableMouseAdapter());
    timeTable.getTableHeader().setReorderingAllowed(false);
    timeTableModel = updateModel();
    mFlatNodeTableFilterModel = new FlatNodeTableFilterModel(timeTableModel, NodeList.NODE_TEXT_COLUMN);
    sorter = new TableSorter(mFlatNodeTableFilterModel);
    timeTable.setModel(sorter);
    sorter.setTableHeader(timeTable.getTableHeader());
    sorter.setColumnComparator(Date.class, TableSorter.COMPARABLE_COMPARATOR);
    sorter.setColumnComparator(NodeModel.class, TableSorter.LEXICAL_COMPARATOR);
    sorter.setColumnComparator(IconsHolder.class, TableSorter.COMPARABLE_COMPARATOR);
    sorter.setSortingStatus(NodeList.DATE_COLUMN, TableSorter.ASCENDING);
    final JScrollPane pane = new JScrollPane(timeTable);
    UITools.setScrollbarIncrement(pane);
    layoutConstraints.gridy++;
    GridBagConstraints tableConstraints = (GridBagConstraints) layoutConstraints.clone();
    tableConstraints.weightx = 1;
    tableConstraints.weighty = 10;
    tableConstraints.fill = GridBagConstraints.BOTH;
    contentPane.add(pane, tableConstraints);
    mTreeLabel = new JLabel();
    layoutConstraints.gridy++;
    GridBagConstraints treeConstraints = (GridBagConstraints) layoutConstraints.clone();
    treeConstraints.fill = GridBagConstraints.BOTH;
    @SuppressWarnings("serial")
    JScrollPane scrollPane = new JScrollPane(mTreeLabel) {
        @Override
        public boolean isValidateRoot() {
            return false;
        }
    };
    contentPane.add(scrollPane, treeConstraints);
    final AbstractAction exportAction = new AbstractAction(
            TextUtils.getText("plugins/TimeManagement.xml_Export")) {
        /**
             * 
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            exportSelectedRowsAndClose();
        }
    };
    final JButton exportButton = new JButton(exportAction);
    final AbstractAction replaceAllAction = new AbstractAction(
            TextUtils.getText("plugins/TimeManagement.xml_Replace_All")) {
        /**
             * 
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            replace(new ReplaceAllInfo());
        }
    };
    final JButton replaceAllButton = new JButton(replaceAllAction);
    final AbstractAction replaceSelectedAction = new AbstractAction(
            TextUtils.getText("plugins/TimeManagement.xml_Replace_Selected")) {
        /**
             * 
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            replace(new ReplaceSelectedInfo());
        }
    };
    final JButton replaceSelectedButton = new JButton(replaceSelectedAction);
    final AbstractAction gotoAction = new AbstractAction(TextUtils.getText("plugins/TimeManagement.xml_Goto")) {
        /**
             * 
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            selectSelectedRows();
        }
    };
    final JButton gotoButton = new JButton(gotoAction);
    final AbstractAction disposeAction = new AbstractAction(
            TextUtils.getText(PLUGINS_TIME_MANAGEMENT_XML_CLOSE)) {
        /**
             * 
             */
        private static final long serialVersionUID = 1L;

        public void actionPerformed(final ActionEvent arg0) {
            disposeDialog();
        }
    };
    final JButton cancelButton = new JButton(disposeAction);
    /* Initial State */
    gotoAction.setEnabled(false);
    exportAction.setEnabled(false);
    replaceSelectedAction.setEnabled(false);
    final Box bar = Box.createHorizontalBox();
    bar.add(Box.createHorizontalGlue());
    bar.add(cancelButton);
    bar.add(exportButton);
    bar.add(replaceAllButton);
    bar.add(replaceSelectedButton);
    bar.add(gotoButton);
    bar.add(Box.createHorizontalGlue());
    layoutConstraints.gridy++;
    contentPane.add(/* new JScrollPane */(bar), layoutConstraints);
    final JMenuBar menuBar = new JMenuBar();
    final JMenu menu = new JMenu(TextUtils.getText("plugins/TimeManagement.xml_menu_actions"));
    final AbstractAction[] actionList = new AbstractAction[] { gotoAction, replaceSelectedAction,
            replaceAllAction, exportAction, disposeAction };
    for (int i = 0; i < actionList.length; i++) {
        final AbstractAction action = actionList[i];
        final JMenuItem item = menu.add(action);
        item.setIcon(new BlindIcon(UIBuilder.ICON_SIZE));
    }
    menuBar.add(menu);
    dialog.setJMenuBar(menuBar);
    final ListSelectionModel rowSM = timeTable.getSelectionModel();
    rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(final ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            final ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            final boolean enable = !(lsm.isSelectionEmpty());
            replaceSelectedAction.setEnabled(enable);
            gotoAction.setEnabled(enable);
            exportAction.setEnabled(enable);
        }
    });
    rowSM.addListSelectionListener(new ListSelectionListener() {
        String getNodeText(final NodeModel node) {
            return TextController.getController().getShortText(node)
                    + ((node.isRoot()) ? "" : (" <- " + getNodeText(node.getParentNode())));
        }

        public void valueChanged(final ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            final ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (lsm.isSelectionEmpty()) {
                mTreeLabel.setText("");
                return;
            }
            final int selectedRow = lsm.getLeadSelectionIndex();
            final NodeModel mindMapNode = getMindMapNode(selectedRow);
            mTreeLabel.setText(getNodeText(mindMapNode));
        }
    });
    final String marshalled = ResourceController.getResourceController()
            .getProperty(NodeList.WINDOW_PREFERENCE_STORAGE_PROPERTY);
    final WindowConfigurationStorage result = TimeWindowConfigurationStorage.decorateDialog(marshalled, dialog);
    final WindowConfigurationStorage storage = result;
    if (storage != null) {
        timeTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        int column = 0;
        for (final TimeWindowColumnSetting setting : ((TimeWindowConfigurationStorage) storage)
                .getListTimeWindowColumnSettingList()) {
            timeTable.getColumnModel().getColumn(column).setPreferredWidth(setting.getColumnWidth());
            sorter.setSortingStatus(column, setting.getColumnSorting());
            column++;
        }
    }
    mFlatNodeTableFilterModel.setFilter((String) mFilterTextSearchField.getSelectedItem(),
            matchCase.isSelected(), useRegexInFind.isSelected());
    dialog.setVisible(true);
}

From source file:org.geworkbench.engine.ccm.ComponentConfigurationManagerWindow.java

/**
 * Set up the GUI/*from w  ww  .ja v  a 2s .  co  m*/
 * 
 * @param void
 * @return void
 */
private void initComponents() {
    frame = new JFrame("geWorkbench - Component Configuration Manager");

    topPanel = new JPanel();
    displayLabel = new JLabel();
    String[] displayChoices = { DISPLAY_FILTER_ALL, DISPLAY_ONLY_LOADED, DISPLAY_ONLY_UNLOADED };
    displayComboBox = new JComboBox(displayChoices);
    showByTypeLabel = new JLabel();
    String[] showByTypeChoices = new String[PluginComponent.categoryList.size() + 2];
    showByTypeChoices[0] = SHOW_BY_TYPE_ALL;
    int index = 1;
    for (String s : PluginComponent.categoryList) {
        showByTypeChoices[index] = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
        index++;
    }
    ;
    showByTypeChoices[index] = SHOW_BY_TYPE_OTHERS;
    Arrays.sort(showByTypeChoices);
    showByTypeComboBox = new JComboBox(showByTypeChoices);
    showByTypeComboBox.setMaximumRowCount(showByTypeChoices.length);
    keywordSearchLabel = new JLabel("Keyword search:");
    keywordSearchField = new JTextField("Enter Text");
    splitPane = new JSplitPane();
    scrollPaneForTextPane = new JScrollPane();
    textPane = new JTextPane();
    bottompanel = new JPanel();
    CellConstraints cc = new CellConstraints();

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            ccmWindow = null;
        }
    });

    viewLicenseButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            viewLicense_actionPerformed(e);
        }
    });

    applyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            applyCcmSelections_actionPerformed(e);
        }
    });
    resetButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            resetCcmSelections_actionPerformed(e);
        }

    });
    closeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            closeCcmSelections_actionPerformed(e);
        }

    });

    //======== frame ========
    {
        Container frameContentPane = frame.getContentPane();
        frameContentPane.setLayout(new BorderLayout());

        //======== outerPanel ========
        {

            frameContentPane.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
                public void propertyChange(java.beans.PropertyChangeEvent e) {
                    if ("border".equals(e.getPropertyName()))
                        throw new RuntimeException();
                }
            });

            //======== topPanel ========
            {
                FormLayout topPanelLayout = new FormLayout(
                        " 32dlu, default,  4dlu, default,  32dlu, default,  4dlu, default, 32dlu, default,  4dlu, 64dlu, 32dlu",
                        "center:25dlu");
                topPanel.setLayout(topPanelLayout);

                //---- displayLabel ----
                displayLabel.setText("Display:");
                topPanel.add(displayLabel, cc.xy(2, 1));
                //======== scrollPaneForTopList1 ========
                {
                    //---- displayComboBox ----
                    ActionListener actionListener = new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            ItemSelectable is = (ItemSelectable) actionEvent.getSource();
                            Object[] selections = is.getSelectedObjects();
                            String selection = (String) selections[0];
                            ccmTableModel.setLoadedFilterValue(selection);
                            sorter.setRowFilter(combinedFilter);
                            ccmTableModel.fireTableDataChanged();
                        }
                    };

                    displayComboBox.addActionListener(actionListener);
                }
                topPanel.add(displayComboBox, cc.xy(4, 1));

                //---- showByTypeLabel ----
                showByTypeLabel.setText("Show by type:");
                topPanel.add(showByTypeLabel, cc.xy(6, 1));
                //======== scrollPaneForTopList2 ========
                {
                    //---- showByTypeComboBox ----
                    ActionListener actionListener2 = new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            ItemSelectable is = (ItemSelectable) actionEvent.getSource();
                            Object[] selections = is.getSelectedObjects();
                            String selection = (String) selections[0];
                            ccmTableModel.setTypeFilterValue(selection);
                            sorter.setRowFilter(combinedFilter);
                            ccmTableModel.fireTableDataChanged();
                        }
                    };

                    showByTypeComboBox.addActionListener(actionListener2);
                }
                topPanel.add(showByTypeComboBox, cc.xy(8, 1));

                //---- topLabel3 ----               
                topPanel.add(keywordSearchLabel, cc.xy(10, 1));

                //======== scrollPaneForTopList3 ========
                {
                    // ---- keywordSearchField ----
                    KeyListener actionListener3 = new KeyListener() {

                        public void keyPressed(KeyEvent e) {
                        }

                        public void keyReleased(KeyEvent e) {
                            String text = keywordSearchField.getText();
                            ccmTableModel.setKeywordFilterValue(text);
                            sorter.setRowFilter(combinedFilter);
                            ccmTableModel.fireTableDataChanged();
                        }

                        public void keyTyped(KeyEvent e) {
                        }
                    };

                    keywordSearchField.setText("Enter Text");
                    keywordSearchField.addKeyListener(actionListener3);
                }
                topPanel.add(keywordSearchField, cc.xy(12, 1));
            } // Top Panel
            frameContentPane.add(topPanel, BorderLayout.NORTH);

            //======== splitPane ========
            {
                splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
                splitPane.setResizeWeight(0.5);

                //======== scrollPaneForTable ========
                {
                    //---- table ----
                    ccmTableModel = new CCMTableModel(manager);
                    setOriginalChoices();
                    table = new JTable(ccmTableModel);
                    sorter = new TableRowSorter<CCMTableModel>(ccmTableModel);
                    table.setRowSorter(sorter);

                    table.setDefaultRenderer(Object.class, new CellRenderer());
                    table.setDefaultRenderer(CCMTableModel.ImageLink.class, new ImageLinkRenderer());
                    table.setDefaultRenderer(CCMTableModel.HyperLink.class, new HyperLinkRenderer());
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

                    ListSelectionModel cellSM = table.getSelectionModel();
                    cellSM.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                    cellSM.addListSelectionListener(new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e) {
                            boolean adjusting = e.getValueIsAdjusting();
                            if (adjusting) {
                                return;
                            }
                            int selectedRow = table.getSelectedRow();
                            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                            if (lsm.isSelectionEmpty()) {
                                textPane.setText(" ");
                            } else {
                                String description = (String) ccmTableModel.getValueAt(
                                        table.convertRowIndexToModel(selectedRow),
                                        CCMTableModel.DESCRIPTION_INDEX);
                                textPane.setText(description);

                                if (textPane.getCaretPosition() > 1) {
                                    textPane.setCaretPosition(1);
                                }
                            }
                        }
                    });

                    table.addMouseListener(new MouseAdapter() {

                        @Override
                        public void mouseClicked(java.awt.event.MouseEvent event) {
                            launchBrowser();
                        }
                    });

                    TableColumn column = table.getColumnModel().getColumn(CCMTableModel.SELECTION_INDEX);
                    column.setMaxWidth(50);
                    column = table.getColumnModel().getColumn(CCMTableModel.VERSION_INDEX);
                    column.setMaxWidth(60);
                    column = table.getColumnModel().getColumn(CCMTableModel.TUTORIAL_URL_INDEX);
                    column.setMaxWidth(70);
                    column = table.getColumnModel().getColumn(CCMTableModel.TOOL_URL_INDEX);
                    column.setMaxWidth(70);

                    scrollPaneForTable = new JScrollPane(table);
                }
                splitPane.setTopComponent(scrollPaneForTable);

                //======== scrollPaneForTextPane ========
                {
                    //---- textPane ----
                    textPane.setEditable(false);
                    scrollPaneForTextPane.setViewportView(textPane);
                }
                splitPane.setBottomComponent(scrollPaneForTextPane);
            } //======== splitPane ========.
            frameContentPane.add(splitPane, BorderLayout.CENTER);

            //======== bottompanel ========
            {
                bottompanel.setLayout(new FormLayout("20dlu," + "default,  4dlu, " + // view License
                        "default,200dlu, " + // Apply
                        "default,  4dlu, " + // Reset
                        "default,  4dlu, " + // Cancel
                        "default " // Close
                        , "center:25dlu"));

                viewLicenseButton.setText("View License");
                bottompanel.add(viewLicenseButton, cc.xy(2, 1));

                //---- applyButton ----
                applyButton.setText("Apply");
                bottompanel.add(applyButton, cc.xy(6, 1));

                //---- resetButton ----
                resetButton.setText("Reset");
                bottompanel.add(resetButton, cc.xy(8, 1));

                //---- closeButton ----
                closeButton.setText("Close");
                bottompanel.add(closeButton, cc.xy(10, 1));

            } //======== bottompanel ========.
            frameContentPane.add(bottompanel, BorderLayout.SOUTH);
        } //======== outerPanel ========
        frame.pack();
        frame.setLocationRelativeTo(frame.getOwner());
    } // ============ frame ============

    topPanel.setVisible(true);
    splitPane.setVisible(true);
    scrollPaneForTable.setVisible(true);
    table.setVisible(true);
    scrollPaneForTextPane.setVisible(true);
    textPane.setVisible(true);
    bottompanel.setVisible(true);
    sorter.setRowFilter(combinedFilter);
    frame.setVisible(true);
    splitPane.setDividerLocation(.7d);
}

From source file:org.geworkbench.engine.ccm.ComponentConfigurationManagerWindow2.java

/**
 * Set up the GUI/*  w  w w. ja v a  2s.c  o m*/
 * 
 * @param void
 * @return void
 */
private void initComponents() {
    frame = new JFrame("geWorkbench - Component Configuration Manager");

    topPanel = new JPanel();
    displayLabel = new JLabel();
    String[] displayChoices = { DISPLAY_FILTER_ALL, DISPLAY_ONLY_LOADED, DISPLAY_ONLY_UNLOADED };
    displayComboBox = new JComboBox(displayChoices);
    showByTypeLabel = new JLabel();
    String[] showByTypeChoices = new String[PluginComponent.categoryList.size() + 2];
    showByTypeChoices[0] = SHOW_BY_TYPE_ALL;
    int index = 1;
    for (String s : PluginComponent.categoryList) {
        showByTypeChoices[index] = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
        index++;
    }
    ;
    showByTypeChoices[index] = SHOW_BY_TYPE_OTHERS;
    Arrays.sort(showByTypeChoices);
    showByTypeComboBox = new JComboBox(showByTypeChoices);
    showByTypeComboBox.setMaximumRowCount(showByTypeChoices.length);
    keywordSearchLabel = new JLabel("Keyword search:");
    keywordSearchField = new JTextField("Enter Text");
    splitPane = new JSplitPane();
    scrollPaneForTextPane = new JScrollPane();
    textPane = new JTextPane();
    bottompanel = new JPanel();
    CellConstraints cc = new CellConstraints();

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            ccmWindow = null;
        }
    });

    viewLicenseButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            viewLicense_actionPerformed(e);
        }
    });

    applyButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            applyCcmSelections_actionPerformed(e);
        }
    });
    resetButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            resetCcmSelections_actionPerformed(e);
        }

    });
    closeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            closeCcmSelections_actionPerformed(e);
        }

    });
    componentUpdateButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            componentRemoteUpdate_actionPerformed(e);
        }

    });

    //======== frame ========
    {
        Container frameContentPane = frame.getContentPane();
        frameContentPane.setLayout(new BorderLayout());

        //======== outerPanel ========
        {

            frameContentPane.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
                public void propertyChange(java.beans.PropertyChangeEvent e) {
                    if ("border".equals(e.getPropertyName()))
                        throw new RuntimeException();
                }
            });

            //======== topPanel ========
            {
                FormLayout topPanelLayout = new FormLayout(
                        " 32dlu, default,  4dlu, default,  32dlu, default,  4dlu, default, 32dlu, default,  4dlu, 64dlu, 32dlu",
                        "center:25dlu");
                topPanel.setLayout(topPanelLayout);

                //---- displayLabel ----
                displayLabel.setText("Display:");
                topPanel.add(displayLabel, cc.xy(2, 1));
                //======== scrollPaneForTopList1 ========
                {
                    //---- displayComboBox ----
                    ActionListener actionListener = new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            ItemSelectable is = (ItemSelectable) actionEvent.getSource();
                            Object[] selections = is.getSelectedObjects();
                            String selection = (String) selections[0];
                            ccmTableModel.setLoadedFilterValue(selection);
                            sorter.setRowFilter(combinedFilter);
                            ccmTableModel.fireTableDataChanged();
                        }
                    };

                    displayComboBox.addActionListener(actionListener);
                }
                topPanel.add(displayComboBox, cc.xy(4, 1));

                //---- showByTypeLabel ----
                showByTypeLabel.setText("Show by type:");
                topPanel.add(showByTypeLabel, cc.xy(6, 1));
                //======== scrollPaneForTopList2 ========
                {
                    //---- showByTypeComboBox ----
                    ActionListener actionListener2 = new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            ItemSelectable is = (ItemSelectable) actionEvent.getSource();
                            Object[] selections = is.getSelectedObjects();
                            String selection = (String) selections[0];
                            ccmTableModel.setTypeFilterValue(selection);
                            sorter.setRowFilter(combinedFilter);
                            ccmTableModel.fireTableDataChanged();
                        }
                    };

                    showByTypeComboBox.addActionListener(actionListener2);
                }
                topPanel.add(showByTypeComboBox, cc.xy(8, 1));

                //---- topLabel3 ----               
                topPanel.add(keywordSearchLabel, cc.xy(10, 1));

                //======== scrollPaneForTopList3 ========
                {
                    // ---- keywordSearchField ----
                    KeyListener actionListener3 = new KeyListener() {

                        public void keyPressed(KeyEvent e) {
                        }

                        public void keyReleased(KeyEvent e) {
                            String text = keywordSearchField.getText();
                            ccmTableModel.setKeywordFilterValue(text);
                            sorter.setRowFilter(combinedFilter);
                            ccmTableModel.fireTableDataChanged();
                        }

                        public void keyTyped(KeyEvent e) {
                        }
                    };

                    keywordSearchField.setText("Enter Text");
                    keywordSearchField.addKeyListener(actionListener3);
                }
                topPanel.add(keywordSearchField, cc.xy(12, 1));
            } // Top Panel
            frameContentPane.add(topPanel, BorderLayout.NORTH);

            //======== splitPane ========
            {
                splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
                splitPane.setResizeWeight(0.5);

                //======== scrollPaneForTable ========
                {
                    //---- table ----
                    ccmTableModel = new CCMTableModel2(manager.componentConfigurationManager);
                    setOriginalChoices();
                    table = new JTable(ccmTableModel);
                    sorter = new TableRowSorter<CCMTableModel2>(ccmTableModel);
                    table.setRowSorter(sorter);

                    table.setDefaultRenderer(Object.class, new CellRenderer());
                    table.setDefaultRenderer(CCMTableModel2.ImageLink.class, new ImageLinkRenderer());
                    table.setDefaultRenderer(CCMTableModel2.HyperLink.class, new HyperLinkRenderer());
                    table.setDefaultRenderer(CCMTableModel2.DownloadLink.class, new DownloadLinkRenderer());
                    table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

                    ListSelectionModel cellSM = table.getSelectionModel();
                    cellSM.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                    cellSM.addListSelectionListener(new ListSelectionListener() {
                        public void valueChanged(ListSelectionEvent e) {
                            boolean adjusting = e.getValueIsAdjusting();
                            if (adjusting) {
                                return;
                            }
                            int[] selectedRow = table.getSelectedRows();
                            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
                            if (lsm.isSelectionEmpty()) {
                                textPane.setText(" ");
                            } else {
                                String description = (String) ccmTableModel.getValueAt(
                                        table.convertRowIndexToModel(selectedRow[0]),
                                        CCMTableModel2.DESCRIPTION_INDEX);
                                textPane.setText(description);

                                if (textPane.getCaretPosition() > 1) {
                                    textPane.setCaretPosition(1);
                                }
                            }

                            if (table.getSelectedRow() >= 0) {
                                int modelColumn = table.convertColumnIndexToModel(table.getSelectedColumn());
                                if (modelColumn == CCMTableModel2.AVAILABLE_UPDATE_INDEX)
                                    installRemoteComponent();
                                else
                                    launchBrowser();
                            }
                        }
                    });

                    TableColumn column = table.getColumnModel().getColumn(CCMTableModel2.SELECTION_INDEX);
                    column.setMaxWidth(50);
                    column = table.getColumnModel().getColumn(CCMTableModel2.VERSION_INDEX);
                    column.setMaxWidth(60);
                    column = table.getColumnModel().getColumn(CCMTableModel2.AVAILABLE_UPDATE_INDEX);
                    column.setMaxWidth(60);
                    column = table.getColumnModel().getColumn(CCMTableModel2.TUTORIAL_URL_INDEX_2);
                    column.setMaxWidth(70);
                    column = table.getColumnModel().getColumn(CCMTableModel2.TOOL_URL_INDEX_2);
                    column.setMaxWidth(70);

                    scrollPaneForTable = new JScrollPane(table);
                }
                splitPane.setTopComponent(scrollPaneForTable);

                //======== scrollPaneForTextPane ========
                {
                    //---- textPane ----
                    textPane.setEditable(false);
                    scrollPaneForTextPane.setViewportView(textPane);
                }
                splitPane.setBottomComponent(scrollPaneForTextPane);
            } //======== splitPane ========.
            frameContentPane.add(splitPane, BorderLayout.CENTER);

            //======== bottompanel ========
            {
                bottompanel.setLayout(new FormLayout("20dlu," + "default,  4dlu, " + // view License
                        "default,100dlu, " + // Component Update
                        "default,  4dlu, " + // Apply
                        "default,  4dlu, " + // Reset
                        "default,  4dlu, " + // Cancel
                        "default " // Close
                        , "center:25dlu"));

                viewLicenseButton.setText("View License");
                bottompanel.add(viewLicenseButton, cc.xy(2, 1));

                //---- componentUpdateButton ----
                bottompanel.add(componentUpdateButton, cc.xy(6, 1));

                //---- applyButton ----
                applyButton.setText("Apply");
                bottompanel.add(applyButton, cc.xy(8, 1));

                //---- resetButton ----
                resetButton.setText("Reset");
                bottompanel.add(resetButton, cc.xy(10, 1));

                //---- closeButton ----
                closeButton.setText("Close");
                bottompanel.add(closeButton, cc.xy(12, 1));

            } //======== bottompanel ========.
            frameContentPane.add(bottompanel, BorderLayout.SOUTH);
        } //======== outerPanel ========
        frame.pack();
        frame.setLocationRelativeTo(frame.getOwner());
    } // ============ frame ============

    topPanel.setVisible(true);
    splitPane.setVisible(true);
    scrollPaneForTable.setVisible(true);
    table.setVisible(true);
    scrollPaneForTextPane.setVisible(true);
    textPane.setVisible(true);
    bottompanel.setVisible(true);
    sorter.setRowFilter(combinedFilter);
    frame.setVisible(true);
    splitPane.setDividerLocation(.7d);
}

From source file:org.omegat.gui.align.AlignPanelController.java

/**
 * Display the align tool. The tool is not modal, so this call will return immediately.
 * /*  www .  j  a v  a  2s .c o m*/
 * @param parent
 *            Parent window of the align tool
 */
public void show(Component parent) {
    frame = new AlignMenuFrame();
    frame.setTitle(OStrings.getString("ALIGNER_PANEL"));
    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            closeFrame(frame);
        }
    });

    panel = new AlignPanel();

    ActionListener comparisonListener = e -> {
        ComparisonMode newValue = (ComparisonMode) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.comparisonMode && confirmReset(frame)) {
            aligner.comparisonMode = newValue;
            reloadBeads();
        } else {
            panel.comparisonComboBox.setSelectedItem(aligner.comparisonMode);
        }
    };
    panel.comparisonComboBox.addActionListener(comparisonListener);
    panel.comparisonComboBox.setRenderer(new EnumRenderer<ComparisonMode>("ALIGNER_ENUM_COMPARISON_MODE_"));

    ActionListener algorithmListener = e -> {
        AlgorithmClass newValue = (AlgorithmClass) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.algorithmClass && confirmReset(frame)) {
            aligner.algorithmClass = newValue;
            reloadBeads();
        } else {
            panel.algorithmComboBox.setSelectedItem(aligner.algorithmClass);
        }
    };
    panel.algorithmComboBox.addActionListener(algorithmListener);
    panel.algorithmComboBox.setRenderer(new EnumRenderer<AlgorithmClass>("ALIGNER_ENUM_ALGORITHM_CLASS_"));

    ActionListener calculatorListener = e -> {
        CalculatorType newValue = (CalculatorType) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.calculatorType && confirmReset(frame)) {
            aligner.calculatorType = newValue;
            reloadBeads();
        } else {
            panel.calculatorComboBox.setSelectedItem(aligner.calculatorType);
        }
    };
    panel.calculatorComboBox.addActionListener(calculatorListener);
    panel.calculatorComboBox.setRenderer(new EnumRenderer<CalculatorType>("ALIGNER_ENUM_CALCULATOR_TYPE_"));

    ActionListener counterListener = e -> {
        CounterType newValue = (CounterType) ((JComboBox<?>) e.getSource()).getSelectedItem();
        if (newValue != aligner.counterType && confirmReset(frame)) {
            aligner.counterType = newValue;
            reloadBeads();
        } else {
            panel.counterComboBox.setSelectedItem(aligner.counterType);
        }
    };
    panel.counterComboBox.addActionListener(counterListener);
    panel.counterComboBox.setRenderer(new EnumRenderer<CounterType>("ALIGNER_ENUM_COUNTER_TYPE_"));

    ActionListener segmentingListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean newValue = ((AbstractButton) e.getSource()).isSelected();
            if (newValue != aligner.segment && confirmReset(frame)) {
                aligner.segment = newValue;
                reloadBeads();
            } else {
                panel.segmentingCheckBox.setSelected(aligner.segment);
                frame.segmentingItem.setSelected(aligner.segment);
            }
        }
    };
    panel.segmentingCheckBox.addActionListener(segmentingListener);
    frame.segmentingItem.addActionListener(segmentingListener);

    ActionListener segmentingRulesListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                SegmentationCustomizer customizer = new SegmentationCustomizer(false, SRX.getDefault(),
                        Core.getSegmenter().getSRX(), null);
                if (customizer.show(frame)) {
                    customizedSRX = customizer.getResult();
                    Core.setSegmenter(new Segmenter(customizedSRX));
                    reloadBeads();
                }
            }
        }
    };
    panel.segmentingRulesButton.addActionListener(segmentingRulesListener);
    frame.segmentingRulesItem.addActionListener(segmentingRulesListener);

    ActionListener filterSettingsListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                FiltersCustomizer customizer = new FiltersCustomizer(false,
                        FilterMaster.createDefaultFiltersConfig(), Core.getFilterMaster().getConfig(), null);
                if (customizer.show(frame)) {
                    customizedFilters = customizer.getResult();
                    Core.setFilterMaster(new FilterMaster(customizedFilters));
                    aligner.clearLoaded();
                    reloadBeads();
                }
            }
        }
    };
    panel.fileFilterSettingsButton.addActionListener(filterSettingsListener);
    frame.fileFilterSettingsItem.addActionListener(filterSettingsListener);

    TableCellRenderer renderer = new MultilineCellRenderer();
    panel.table.setDefaultRenderer(Object.class, renderer);
    panel.table.setDefaultRenderer(Boolean.class, renderer);
    panel.addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            resizeRows(panel.table);
        }
    });

    ActionListener oneAdjustListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            boolean up = e.getSource().equals(panel.moveUpButton) || e.getSource().equals(frame.moveUpItem);
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) {
                int trgRow = up ? model.prevBeadFromRow(rows[0]) : model.nextBeadFromRow(rows[rows.length - 1]);
                moveRows(rows, col, trgRow);
            } else {
                int offset = up ? -1 : 1;
                slideRows(rows, col, offset);
            }
        }
    };
    panel.moveUpButton.addActionListener(oneAdjustListener);
    frame.moveUpItem.addActionListener(oneAdjustListener);
    panel.moveDownButton.addActionListener(oneAdjustListener);
    frame.moveDownItem.addActionListener(oneAdjustListener);

    ActionListener mergeListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            if (rows.length == 1) {
                rows = new int[] { rows[0], model.nextNonEmptyCell(rows[0], col) };
            }
            int beads = model.beadsInRowSpan(rows);
            if (beads < 1) {
                // Do nothing
            } else if (beads == 1) {
                mergeRows(rows, col);
            } else {
                moveRows(rows, col, rows[0]);
            }
        }
    };
    panel.mergeButton.addActionListener(mergeListener);
    frame.mergeItem.addActionListener(mergeListener);

    ActionListener splitListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = panel.table.getSelectedRows();
            int col = panel.table.getSelectedColumn();
            BeadTableModel model = (BeadTableModel) panel.table.getModel();
            int beads = model.beadsInRowSpan(rows);
            if (beads != 1) {
                // Do nothing
            } else if (rows.length == 1) {
                splitRow(rows[0], col);
            } else {
                splitBead(rows, col);
            }
        }
    };
    panel.splitButton.addActionListener(splitListener);
    frame.splitItem.addActionListener(splitListener);

    ActionListener editListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            int row = panel.table.getSelectedRow();
            int col = panel.table.getSelectedColumn();
            editRow(row, col);
        }
    };
    panel.editButton.addActionListener(editListener);
    frame.editItem.addActionListener(editListener);

    ListSelectionListener selectionListener = new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e) {
            updateCommandAvailability(panel, frame);
        }
    };
    panel.table.getColumnModel().getSelectionModel().addListSelectionListener(selectionListener);
    panel.table.getSelectionModel().addListSelectionListener(selectionListener);

    ActionListener saveListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (!confirmSaveTMX(panel)) {
                return;
            }
            while (true) {
                JFileChooser chooser = new JFileChooser();
                chooser.setSelectedFile(new File(defaultSaveDir, getOutFileName()));
                chooser.setDialogTitle(OStrings.getString("ALIGNER_PANEL_DIALOG_SAVE"));
                if (JFileChooser.APPROVE_OPTION == chooser.showSaveDialog(frame)) {
                    File file = chooser.getSelectedFile();
                    if (file.isFile()) {
                        if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(frame,
                                StringUtil.format(OStrings.getString("ALIGNER_PANEL_DIALOG_OVERWRITE"),
                                        file.getName()),
                                OStrings.getString("ALIGNER_DIALOG_WARNING_TITLE"),
                                JOptionPane.WARNING_MESSAGE)) {
                            continue;
                        }
                    }
                    List<MutableBead> beads = ((BeadTableModel) panel.table.getModel()).getData();
                    try {
                        aligner.writePairsToTMX(file,
                                MutableBead.beadsToEntries(aligner.srcLang, aligner.trgLang, beads));
                        modified = false;
                    } catch (Exception ex) {
                        Log.log(ex);
                        JOptionPane.showMessageDialog(frame, OStrings.getString("ALIGNER_PANEL_SAVE_ERROR"),
                                OStrings.getString("ERROR_TITLE"), JOptionPane.ERROR_MESSAGE);
                    }
                }
                break;
            }
        }
    };
    panel.saveButton.addActionListener(saveListener);
    frame.saveItem.addActionListener(saveListener);

    ActionListener resetListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (confirmReset(frame)) {
                if (phase == Phase.ALIGN) {
                    aligner.restoreDefaults();
                }
                reloadBeads();
            }
        }
    };
    panel.resetButton.addActionListener(resetListener);
    frame.resetItem.addActionListener(resetListener);

    ActionListener reloadListener = e -> {
        if (confirmReset(frame)) {
            aligner.clearLoaded();
            reloadBeads();
        }
    };
    frame.reloadItem.addActionListener(reloadListener);

    ActionListener removeTagsListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            boolean newValue = ((AbstractButton) e.getSource()).isSelected();
            if (newValue != aligner.removeTags && confirmReset(frame)) {
                aligner.removeTags = newValue;
                aligner.clearLoaded();
                reloadBeads();
            } else {
                panel.removeTagsCheckBox.setSelected(aligner.removeTags);
                frame.removeTagsItem.setSelected(aligner.removeTags);
            }
        }
    };
    panel.removeTagsCheckBox.addActionListener(removeTagsListener);
    frame.removeTagsItem.addActionListener(removeTagsListener);

    panel.continueButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            phase = Phase.EDIT;
            updatePanel();
        }
    });

    ActionListener highlightListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            doHighlight = ((AbstractButton) e.getSource()).isSelected();
            updateHighlight();
        }
    };
    panel.highlightCheckBox.addActionListener(highlightListener);
    frame.highlightItem.addActionListener(highlightListener);

    ActionListener highlightPatternListener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            PatternPanelController patternEditor = new PatternPanelController(highlightPattern);
            highlightPattern = patternEditor.show(frame);
            Preferences.setPreference(Preferences.ALIGNER_HIGHLIGHT_PATTERN, highlightPattern.pattern());
            updateHighlight();
        }
    };
    panel.highlightPatternButton.addActionListener(highlightPatternListener);
    frame.highlightPatternItem.addActionListener(highlightPatternListener);

    frame.markAcceptedItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.ACCEPTED, panel.table.getSelectedRows());
        }
    });

    frame.markNeedsReviewItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.NEEDS_REVIEW, panel.table.getSelectedRows());
        }
    });

    frame.clearMarkItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setStatus(MutableBead.Status.DEFAULT, panel.table.getSelectedRows());
        }
    });

    frame.toggleSelectedItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleEnabled(panel.table.getSelectedRows());
        }
    });

    frame.closeItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            closeFrame(frame);
        }
    });

    frame.keepAllItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleAllEnabled(true);
        }
    });

    frame.keepNoneItem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            toggleAllEnabled(false);
        }
    });

    frame.realignPendingItem.addActionListener(e -> {
        realignPending();
    });

    frame.pinpointAlignStartItem.addActionListener(e -> {
        phase = Phase.PINPOINT;
        ppRow = panel.table.getSelectedRow();
        ppCol = panel.table.getSelectedColumn();
        panel.table.clearSelection();
        updatePanel();
    });

    frame.pinpointAlignEndItem.addActionListener(e -> {
        pinpointAlign(panel.table.getSelectedRow(), panel.table.getSelectedColumn());
    });

    frame.pinpointAlignCancelItem.addActionListener(e -> {
        phase = Phase.EDIT;
        ppRow = -1;
        ppCol = -1;
        panel.table.repaint();
        updatePanel();
    });

    panel.table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (phase == Phase.PINPOINT) {
                JTable table = (JTable) e.getSource();
                int row = table.rowAtPoint(e.getPoint());
                int col = table.columnAtPoint(e.getPoint());
                pinpointAlign(row, col);
            }
        }
    });

    frame.resetItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() | KeyEvent.SHIFT_DOWN_MASK));
    frame.realignPendingItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_R, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    frame.saveItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    frame.closeItem.setAccelerator(
            KeyStroke.getKeyStroke(KeyEvent.VK_W, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));

    // emacs-like keys for table navigation
    // See javax.swing.plaf.BasicTableUI.Actions for supported action names.
    setKeyboardShortcut(panel.table, "selectNextRow", 'n');
    setKeyboardShortcut(panel.table, "selectNextRowExtendSelection", 'N');
    setKeyboardShortcut(panel.table, "selectPreviousRow", 'p');
    setKeyboardShortcut(panel.table, "selectPreviousRowExtendSelection", 'P');
    setKeyboardShortcut(panel.table, "selectNextColumn", 'f');
    setKeyboardShortcut(panel.table, "selectNextColumnExtendSelection", 'F');
    setKeyboardShortcut(panel.table, "selectPreviousColumn", 'b');
    setKeyboardShortcut(panel.table, "selectPreviousColumnExtendSelection", 'B');

    panel.table.setTransferHandler(new AlignTransferHandler());
    panel.table.addPropertyChangeListener("dropLocation", new DropLocationListener());
    if (Preferences.isPreference(Preferences.PROJECT_FILES_USE_FONT)) {
        try {
            String fontName = Preferences.getPreference(Preferences.TF_SRC_FONT_NAME);
            int fontSize = Integer.parseInt(Preferences.getPreference(Preferences.TF_SRC_FONT_SIZE));
            panel.table.setFont(new Font(fontName, Font.PLAIN, fontSize));
        } catch (Exception e) {
            Log.log(e);
        }
    }

    // Set initial state
    updateHighlight();
    updatePanel();
    reloadBeads();

    frame.add(panel);
    frame.pack();
    frame.setMinimumSize(frame.getSize());
    frame.setLocationRelativeTo(parent);
    frame.setVisible(true);
}

From source file:scrabble.frmStartup.java

@Override
public void windowClosing(WindowEvent e) {

    if (e.getSource() == frmGame) {
        this.setVisible(true);
        frmGame.dispose();/*w  w  w .  j a  v a 2 s.c  om*/
    }

}

From source file:uk.ac.babraham.SeqMonk.Filters.GeneSetFilter.GeneSetIntensityDifferenceFilter.java

public void windowClosed(WindowEvent e) {

    if (e.getSource() instanceof GeneSetDisplay) {

        System.err.println("not doing it from the filter");

        /*   GeneSetDisplay display = (GeneSetDisplay)(e.getSource());
           if(display.currentSelectedProbeList != null){
              if(display.currentSelectedProbeList[0] != null){
                 display.currentSelectedProbeList[0].delete();
                 display.currentSelectedProbeList = null;
              }   /*from w w  w .  ja v a2  s .  co  m*/
           }         
        */ }

    /*   if(e.getSource().equals(geneSetDisplay)){
          //System.err.println("yes, it's a geneSetDisplay");                     
          //System.err.println("trying to delete probelist...");
          if(geneSetDisplay != null && geneSetDisplay.currentSelectedProbeList != null){
                  
    geneSetDisplay.currentSelectedProbeList[0].delete();
    geneSetDisplay.currentSelectedProbeList = null;               
          }      
          selectedProbeLists = null;            
       }      
    */ progressCancelled();
    // TODO Auto-generated method stub

}