Example usage for java.awt.event ActionEvent getID

List of usage examples for java.awt.event ActionEvent getID

Introduction

In this page you can find the example usage for java.awt.event ActionEvent getID.

Prototype

public int getID() 

Source Link

Document

Returns the event type.

Usage

From source file:org.nekorp.workflow.desktop.view.AppMainWindow.java

/**
 * call this somewhere in your GUI construction
 *///from   ww  w  .  j  av a 2  s  .c om
private void setupKeyShortcut() {
    KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK);
    actionMap.put(key1, new AbstractAction("guardar") {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (editorMonitor.hasChange()) {
                try {
                    aplication.guardaServicio();
                } catch (IllegalArgumentException ex) {
                    //no lo guardo.
                }
            }
        }
    });
    //        key1 = KeyStroke.getKeyStroke(KeyEvent.VK_Z, KeyEvent.CTRL_DOWN_MASK);
    //        actionMap.put(key1, new AbstractAction("deshacer") {
    //            @Override
    //            public void actionPerformed(ActionEvent e) {
    //                if (editorMonitor.hasChange()) {
    //                    editorMonitor.undo();
    //                }
    //            }
    //        });
    //        key1 = KeyStroke.getKeyStroke(KeyEvent.VK_Y, KeyEvent.CTRL_DOWN_MASK);
    //        actionMap.put(key1, new AbstractAction("rehacer") {
    //            @Override
    //            public void actionPerformed(ActionEvent e) {
    //                editorMonitor.redo();
    //            }
    //        });
    // add more actions..

    KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    kfm.addKeyEventDispatcher(new KeyEventDispatcher() {
        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
            if (actionMap.containsKey(keyStroke)) {
                final Action a = actionMap.get(keyStroke);
                final ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), null);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        a.actionPerformed(ae);
                    }
                });
                return true;
            }
            return false;
        }
    });
}

From source file:edu.ku.brc.specify.tasks.subpane.qb.QueryFieldPanel.java

protected PickListCriteriaCombo createPickList(final Component saveBtn) {
    PickListCriteriaCombo result = new PickListCriteriaCombo(pickList);
    if (!ownerQuery.isPromptMode()) {
        result.addActionListener(new ActionListener() {

            /* (non-Javadoc)
             * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
             *//*from   w w  w . j  a v  a  2 s .  c  o m*/
            @Override
            public void actionPerformed(ActionEvent e) {
                if (e.getID() == 1001/*ComboBoxChanged*/) {
                    if (saveBtn != null) {
                        saveBtn.setEnabled(true);
                    }
                }
            }

        });
    }
    return result;
}

From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java

/**
 * Wenn ein element meint, was zu melden...
 *//*  w  ww  .ja v a  2s.  co m*/
@Override
public void actionPerformed(ActionEvent ev) {
    if (ignoreAction)
        return;
    // /////////////////////////////////////////////////////////////////////////
    // Meine Actions
    if (ev.getID() > ActionEvent.ACTION_FIRST) {
        processMessageActions(ev);
        return;
    }
    // /////////////////////////////////////////////////////////////////////////
    // MEN
    else if (ev.getSource() instanceof JMenuItem) {
        processMenuActions(ev);
        return;
    }
    // /////////////////////////////////////////////////////////////////////////
    // Button
    else if (ev.getSource() instanceof JButton) {
        processButtonActions(ev);
        return;
    }
    // /////////////////////////////////////////////////////////////////////////
    // Combobox
    else if (ev.getSource() instanceof JComboBox) {
        processComboBoxActions(ev);
        return;
    }
}

From source file:de.dmarcini.submatix.pclogger.gui.MainCommGUI.java

/**
 * Bearbeitet meine "Messages" Project: SubmatixBTConfigPC Package: de.dmarcini.submatix.pclogger.gui
 * //www. jav a 2 s  .c om
 * @author Dirk Marciniak (dirk_marciniak@arcor.de) Stand: 07.01.2012
 * @param ev
 *          Avtion event
 */
private void processMessageActions(ActionEvent ev) {
    String cmd = ev.getActionCommand();
    int actionId = ev.getID();
    //
    // wenn ich auf eine Nachricht warten soll, um das "WARTE"-Fenster zu schliessen
    //
    if (waitForMessage != 0) {
        // timer ereignis UND das Fenster ist offen
        if ((actionId == ProjectConst.MESSAGE_TICK) && (wDial != null)) {
            // ist der Timeout um?
            if (wDial.isTimeout()) {
                lg.error("dialog window timeout is over!");
                wDial.dispose();
                wDial = null;
                showErrorDialog(LangStrings.getString("MainCommGUI.errorDialog.timeout"));
                // den Merker auf null setzen!
                waitForMessage = 0;
            }
        }
        if (waitForMessage == actionId) {
            // es ist die Nachricht, auf die ich waren soll
            if (wDial != null) {
                wDial.dispose();
                wDial = null;
            }
            // den Merker auf null setzen!
            waitForMessage = 0;
        }
    }
    switch (actionId) {
    // /////////////////////////////////////////////////////////////////////////
    // Virtuelle Ports verndert
    case ProjectConst.MESSAGE_PORT_STATE_CHANGE:
        lg.debug("VIRTUAL PORT CHANGED command!");
        if (ev.getSource() instanceof VirtualSerialPortsFinder) {
            VirtualSerialPortsFinder finder = (VirtualSerialPortsFinder) ev.getSource();
            connectionPanel.setNewVirtDeviceList(finder.getComboBoxModel());
            connectionPanel.setVirtDevicesBoxEnabled(true);
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Info anzeigen...
    case ProjectConst.MESSAGE_TOAST:
        lg.debug("TOAST command!");
        connectionPanel.setToastMessage(cmd);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Hab was gelesen!
    case ProjectConst.MESSAGE_READ:
        lg.debug("READ Command!");
        // soll den reader Thread und die GUI nicht blockieren
        // daher nur in die Liste schmeissen (die ist thread-sicher)
        if ((!cmd.isEmpty()) && (!cmd.equals("\n"))) {
            messagesList.add(cmd);
            lg.debug("RECIVED: <" + cmd + ">");
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Gertename ausgelesen
    case ProjectConst.MESSAGE_MANUFACTURER_READ:
        lg.info("Device Manufacturer Name from SPX42 <" + cmd + "> recived...");
        currentConfig.setDeviceName(cmd);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Firmwareversion gelesen!
    case ProjectConst.MESSAGE_FWVERSION_READ:
        lg.info("Firmware Version <" + cmd + "> recived...");
        currentConfig.setFirmwareVersion(cmd);
        configPanel.setFirmwareLabel(cmd);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Seriennummer vom SPX42
    case ProjectConst.MESSAGE_SERIAL_READ:
        lg.info("Serial Number from SPX42 recived...");
        configPanel.setSerialNumber(cmd);
        currentConfig.setSerial(cmd);
        // bei Verbindung mit einem virtuellen Device muss ich noch einen Namen eintragen. Das ist dann die Seriennummer
        if (btComm.getConnectedDevice().equals("virtual")) {
            btComm.setNameForVirtualDevice(cmd);
            // jetzt guck mal, ob ein Alias vorhanden ist
            if (null == databaseUtil.getAliasForNameConn(cmd)) {
                // dann muss ich den auch noch eintragen
                databaseUtil.addAliasForNameConn(cmd, cmd, "virtual");
            }
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Decompressionseinstellungen gelesen
    case ProjectConst.MESSAGE_DECO_READ:
        lg.info("DECO propertys from SPX42 recived...");
        if (wDial != null) {
            wDial.incrementProgress();
        }
        if (currentConfig.setDecoGf(cmd)) {
            lg.info("DECO propertys set to GUI...");
            configPanel.setDecoGradient();
            lg.info("DECO propertys set to GUI...OK");
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Einheiten Einstellungen vom SPX42 gelesen
    case ProjectConst.MESSAGE_UNITS_READ:
        lg.info("UNITS propertys from SPX42 recived...");
        if (wDial != null) {
            wDial.incrementProgress();
        }
        if (currentConfig.setUnits(cmd)) {
            lg.info("UNITS propertys set to GUI...");
            configPanel.setUnits();
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Displayeinstellungen gelesen
    case ProjectConst.MESSAGE_DISPLAY_READ:
        lg.info("DISPLAY propertys from SPX42 recived...");
        if (wDial != null) {
            wDial.incrementProgress();
        }
        if (currentConfig.setDisplay(cmd)) {
            lg.info("DISPLAY propertys set to GUI...");
            configPanel.setDisplayPropertys();
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Einstellungen zum O2 Setpint gelesen
    case ProjectConst.MESSAGE_SETPOINT_READ:
        lg.info("SETPOINT propertys from SPX42 recived...");
        if (wDial != null) {
            wDial.incrementProgress();
        }
        if (currentConfig.setSetpoint(cmd)) {
            lg.info("SETPOINT propertys set to GUI...");
            configPanel.setSetpoint();
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Einstellungen fr Individuell gelesen (Extra-Lizenz erforderlich )
    case ProjectConst.MESSAGE_INDIVID_READ:
        lg.info("INDIVIDUAL propertys from SPX42 recived...");
        if (wDial != null) {
            wDial.incrementProgress();
        }
        if (currentConfig.setIndividuals(cmd)) {
            lg.info("INDIVIDUAL propertys set to GUI...");
            configPanel.setIndividuals(true);
        } else {
            configPanel.setIndividuals(false);
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Der Lizenzstatus
    case ProjectConst.MESSAGE_LICENSE_STATE_READ:
        lg.info("lizense state from SPX42 recived...");
        currentConfig.setLicenseStatus(cmd);
        licenseState = currentConfig.getLicenseState();
        customConfig = currentConfig.getCustomEnabled();
        gasConfigPanel.setLicenseState(licenseState, customConfig);
        gasConfigPanel.setLicenseLabel();
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Versuche Verbindung mit Bluetooht Gert
    case ProjectConst.MESSAGE_CONNECTING:
        lg.info("CONNECTING...");
        setElementsInactive(true);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Device wurde verbunden
    case ProjectConst.MESSAGE_CONNECTED:
        lg.info("CONNECT");
        setElementsConnected(true);
        // Gleich mal Fragen, wer da dran ist!
        btComm.askForDeviceName();
        btComm.askForSerialNumber();
        btComm.askForLicenseFromSPX();
        btComm.writeDateTimeToDevice(new DateTime());
        btComm.askForFirmwareVersion();
        connectionPanel.setAliasesEditable(false);
        connectionPanel.refreshAliasTable();
        gasConfigPanel.setPanelOnlineMode(true);
        // warte, bis die Nachricht FWVERSION_READ kommt, um das wartefenster zu schliessen
        waitForMessage = ProjectConst.MESSAGE_FWVERSION_READ;
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Device wurde getrennt
    case ProjectConst.MESSAGE_DISCONNECTED:
        lg.info("DISCONNECT");
        if (wDial != null) {
            wDial.dispose();
            wDial = null;
        }
        setElementsConnected(false);
        configPanel.setAllConfigPanlelsEnabled(false);
        gasConfigPanel.setPanelOnlineMode(false);
        connectionPanel.refreshAliasTable();
        connectionPanel.setAliasesEditable(true);
        if (tabbedPane.getSelectedIndex() != programTabs.TAB_CONNECT.ordinal()) {
            showWarnBox(LangStrings.getString("MainCommGUI.warnDialog.connectionClosed"));
        }
        if (tabbedPane.getSelectedIndex() != programTabs.TAB_LOGGRAPH.ordinal()) {
            // wen nicht grad loggrafik angezeigt wird, auf den Connecttab wechseln
            tabbedPane.setSelectedIndex(programTabs.TAB_CONNECT.ordinal());
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Kein Gert zum Verbinden gefunden!
    case ProjectConst.MESSAGE_BTNODEVCONN:
        lg.error("no device found...");
        showWarnBox(LangStrings.getString("MainCommGUI.warnDialog.notDeviceSelected.text"));
        setElementsConnected(false);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Lebenszeichen mit Ackuspannugn empfangen
    case ProjectConst.MESSAGE_SPXALIVE:
        lg.info("acku value from spx42 recived...");
        setAckuValue(cmd);
        if (savedConfig == null) {
            currentConfig.setWasInit(true);
        }
        savedConfig = new SPX42Config(currentConfig);
        configPanel.setAllConfigPanlelsEnabled(true);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht, da da etwas passiert, also Hinweisbox weiterzhlen lassen
    case ProjectConst.MESSAGE_PROCESS_NEXT:
        if (wDial != null) {
            if (cmd == null) {
                wDial.incrementProgress();
            } else {
                wDial.setProgress(cmd);
            }
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht, da die Hinweisbox geschlossen werden kann
    case ProjectConst.MESSAGE_PROCESS_END:
        if (wDial != null) {
            wDial.dispose();
            wDial = null;
        }
        if (cmd != null) {
            if (cmd.equals("config_write")) {
                savedConfig = new SPX42Config(currentConfig);
            }
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht ber den Empfang einer Gaseinstellung
    case ProjectConst.MESSAGE_GAS_READ:
        // Gibts schon ein GasListObjekt
        SPX42GasList currGasList = gasConfigPanel.getCurrGasList();
        if (currGasList == null) {
            lg.warn("not alloacated gaslist in gasEditPanel yet!");
            return;
        }
        // lt sich das Teil parsen?
        if (currGasList.setGas(cmd)) {
            // ist alle initialisiert?
            if (currGasList.isInitialized()) {
                // wenn die Gaskiste initialisiert ist
                gasConfigPanel.initGasesFromCurrent();
                // dann kann das fenster ja wech!
                if (wDial != null) {
                    wDial.dispose();
                    wDial = null;
                }
            }
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht Syncronisation wird beendet
    case ProjectConst.MESSAGE_SYCSTAT_OFF:
        lg.warn("SPX42 switched SYNC OFF! Connetion will failure....");
        // disconnect!
        btComm.disconnectDevice();
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht Gase wurden erfolgreich geschrieben
    case ProjectConst.MESSAGE_GAS_WRITTEN:
        lg.debug("gas written to SPX...");
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht ein Logbuch Verzeichniseintrag wurde gelesen
    case ProjectConst.MESSAGE_DIRENTRY_READ:
        lg.debug("logdir entry recived...");
        String decodet = decodeLogDirEntry(cmd);
        if (decodet != null) {
            logListPanel.addLogdirEntry(decodet);
        }
        if (!logListPanel.isReadingComplete()) {
            // hab noch zu tun...
            if (wDial != null) {
                wDial.incrementProgress();
            }
        } else {
            // dann kann das fenster ja wech!
            if (wDial != null) {
                wDial.dispose();
                wDial = null;
            }
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht: Start einer Logdatenbermittling
    case ProjectConst.MESSAGE_LOGENTRY_START:
        lg.debug("start transfer logentry <" + cmd + ">...");
        logListPanel.startTransfer(cmd, currentConfig.getUnitSystem());
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht: Logzeile bertragen
    case ProjectConst.MESSAGE_LOGENTRY_LINE:
        lg.debug("recive one log line from SPX...");
        logListPanel.addLogLineFromSPX(cmd);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht: Logzeile bertragen
    case ProjectConst.MESSAGE_LOGENTRY_STOP:
        lg.debug("logfile transfer done...");
        // Ab auf die Platte ind die DB damit!
        logListPanel.writeCacheToDatabase();
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht: Logdirectory aus Cache neu aufbauen
    case ProjectConst.MESSAGE_LOGDIRFROMCACHE:
        lg.debug("log directory from cache rebuilding...");
        logListPanel.addLogDirFromCache();
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht: Daten gesichert....
    case ProjectConst.MESSAGE_DB_SUCCESS:
        lg.debug("loglist transfer success...");
        // dann kann das fenster ja wech!
        if (wDial != null) {
            wDial.dispose();
            wDial = null;
        }
        if (btComm != null) {
            if (btComm.isConnected()) {
                Integer[] logListEntry = logListPanel.getNextEntryToRead();
                if (logListEntry != null) {
                    // unterscheide Update oder Neu
                    computeLogRequest(logListEntry);
                } else {
                    // Da sind keine Eintrge mehr zu lesen. Mach ein Update der Logverzeichnisliste
                    if (btComm != null) {
                        if (btComm.isConnected()) {
                            // Kann ich vom Cache lesen?
                            if (logListPanel.canReadFromCache()) {
                                // Baue die Liste mit dem Cache wieder auf
                                ev = new ActionEvent(this, ProjectConst.MESSAGE_LOGDIRFROMCACHE, "from_ache");
                                actionPerformed(ev);
                            } else {
                                // lese die Liste der Logeintrge neu ein
                                if (logListPanel.prepareReadLogdir(btComm.getConnectedDevice())) {
                                    // Sag dem SPX er soll alles schicken
                                    wDial = new PleaseWaitDialog(
                                            LangStrings.getString("PleaseWaitDialog.title"),
                                            LangStrings.getString("PleaseWaitDialog.readLogDir"));
                                    wDial.setVisible(true);
                                    wDial.setTimeout(120 * 1000);
                                    btComm.readLogDirectoryFromSPX();
                                }
                            }
                        } else {
                            showWarnBox(LangStrings.getString("MainCommGUI.warnDialog.notConnected.text"));
                        }
                    }
                }
            } else {
                showWarnBox(LangStrings.getString("MainCommGUI.warnDialog.notConnected.text"));
            }
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nachricht: Datenbankfehler....
    case ProjectConst.MESSAGE_DB_FAIL:
        lg.debug("loglist transfer failed...");
        // dann kann das fenster ja wech!
        if (wDial != null) {
            wDial.dispose();
            wDial = null;
        }
        if (cmd != null) {
            showErrorDialog(LangStrings.getString("spx42LoglistPanel.logListLabel.text") + "\n" + cmd);
        } else {
            showErrorDialog(LangStrings.getString("spx42LoglistPanel.logListLabel.text"));
        }
        logListPanel.removeFailedDataset();
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Der 10-Sekunden Ticker
    case ProjectConst.MESSAGE_TICK:
        if (SpxPcloggerProgramConfig.developDebug)
            lg.debug("TICK!");
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Ich soll mit BT Device direkt verbinden
    case ProjectConst.MESSAGE_CONNECTBTDEVICE:
        if (btComm != null) {
            waitForMessage = 0; // auf erst mal nix warten...
            connectSPX(cmd);
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Ich soll mit BT Device direkt verbinden
    case ProjectConst.MESSAGE_CONNECTVIRTDEVICE:
        if (btComm != null) {
            waitForMessage = 0; // auf erst mal nix warten...
            connectVirtSPX(cmd);
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Trenne Verbindung
    case ProjectConst.MESSAGE_DISCONNECTBTDEVICE:
        if (btComm != null) {
            disconnectSPX();
        }
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Timeout bei Schreiben auf Gert
    case ProjectConst.MESSAGE_COMMTIMEOUT:
        lg.error("TIMEOUT (write to comm) recived! Disconnect!");
        System.exit(-1);
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Firmware nicht untersttzt beim schreiben
    case ProjectConst.MESSAGE_FWNOTSUPPORTED:
        if (wDial != null) {
            wDial.dispose();
            wDial = null;
        }
        showErrorDialog("Firmware not supported");
        break;
    // /////////////////////////////////////////////////////////////////////////
    // Nichts traf zu....
    default:
        lg.warn("unknown message recived!");
        break;
    }
    return;
}

From source file:org.apache.jmeter.gui.action.Save.java

@Override
public void doAction(ActionEvent e) throws IllegalUserActionException {
    HashTree subTree = null;/*from   ww  w. ja  v  a 2  s.co m*/
    boolean fullSave = false; // are we saving the whole tree?
    if (!commands.contains(e.getActionCommand())) {
        throw new IllegalUserActionException("Invalid user command:" + e.getActionCommand());
    }
    if (e.getActionCommand().equals(ActionNames.SAVE_AS)) {
        JMeterTreeNode[] nodes = GuiPackage.getInstance().getTreeListener().getSelectedNodes();
        if (nodes.length > 1) {
            JMeterUtils.reportErrorToUser(JMeterUtils.getResString("save_as_error"), // $NON-NLS-1$
                    JMeterUtils.getResString("save_as")); // $NON-NLS-1$
            return;
        }
        subTree = GuiPackage.getInstance().getCurrentSubTree();
    } else if (e.getActionCommand().equals(ActionNames.SAVE_AS_TEST_FRAGMENT)) {
        JMeterTreeNode[] nodes = GuiPackage.getInstance().getTreeListener().getSelectedNodes();
        if (checkAcceptableForTestFragment(nodes)) {
            subTree = GuiPackage.getInstance().getCurrentSubTree();
            // Create Test Fragment node
            TestElement element = GuiPackage.getInstance()
                    .createTestElement(TestFragmentControllerGui.class.getName());
            HashTree hashTree = new ListedHashTree();
            HashTree tfTree = hashTree.add(new JMeterTreeNode(element, null));
            for (JMeterTreeNode node : nodes) {
                // Clone deeply current node
                TreeCloner cloner = new TreeCloner(false);
                GuiPackage.getInstance().getTreeModel().getCurrentSubTree(node).traverse(cloner);
                // Add clone to tfTree
                tfTree.add(cloner.getClonedTree());
            }

            subTree = hashTree;

        } else {
            JMeterUtils.reportErrorToUser(JMeterUtils.getResString("save_as_test_fragment_error"), // $NON-NLS-1$
                    JMeterUtils.getResString("save_as_test_fragment")); // $NON-NLS-1$
            return;
        }
    } else {
        fullSave = true;
        HashTree testPlan = GuiPackage.getInstance().getTreeModel().getTestPlan();
        // If saveWorkBench 
        if (isWorkbenchSaveable()) {
            HashTree workbench = GuiPackage.getInstance().getTreeModel().getWorkBench();
            testPlan.add(workbench);
        }
        subTree = testPlan;
    }

    String updateFile = GuiPackage.getInstance().getTestPlanFile();
    if (!ActionNames.SAVE.equals(e.getActionCommand()) || updateFile == null) {
        JFileChooser chooser = FileDialoger.promptToSaveFile(updateFile == null
                ? GuiPackage.getInstance().getTreeListener().getCurrentNode().getName() + JMX_FILE_EXTENSION
                : updateFile);
        if (chooser == null) {
            return;
        }
        updateFile = chooser.getSelectedFile().getAbsolutePath();
        // Make sure the file ends with proper extension
        if (FilenameUtils.getExtension(updateFile).isEmpty()) {
            updateFile = updateFile + JMX_FILE_EXTENSION;
        }
        // Check if the user is trying to save to an existing file
        File f = new File(updateFile);
        if (f.exists()) {
            int response = JOptionPane.showConfirmDialog(GuiPackage.getInstance().getMainFrame(),
                    JMeterUtils.getResString("save_overwrite_existing_file"), // $NON-NLS-1$
                    JMeterUtils.getResString("save?"), // $NON-NLS-1$
                    JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
            if (response == JOptionPane.CLOSED_OPTION || response == JOptionPane.NO_OPTION) {
                return; // Do not save, user does not want to overwrite
            }
        }

        if (!e.getActionCommand().equals(ActionNames.SAVE_AS)) {
            GuiPackage.getInstance().setTestPlanFile(updateFile);
        }
    }

    // backup existing file according to jmeter/user.properties settings
    List<File> expiredBackupFiles = EMPTY_FILE_LIST;
    File fileToBackup = new File(updateFile);
    try {
        expiredBackupFiles = createBackupFile(fileToBackup);
    } catch (Exception ex) {
        log.error("Failed to create a backup for " + fileToBackup.getName(), ex); //$NON-NLS-1$
    }

    try {
        convertSubTree(subTree);
    } catch (Exception err) {
        log.warn("Error converting subtree " + err);
    }

    FileOutputStream ostream = null;
    try {
        ostream = new FileOutputStream(updateFile);
        SaveService.saveTree(subTree, ostream);
        if (fullSave) { // Only update the stored copy of the tree for a full save
            subTree = GuiPackage.getInstance().getTreeModel().getTestPlan(); // refetch, because convertSubTree affects it
            if (isWorkbenchSaveable()) {
                HashTree workbench = GuiPackage.getInstance().getTreeModel().getWorkBench();
                subTree.add(workbench);
            }
            ActionRouter.getInstance()
                    .doActionNow(new ActionEvent(subTree, e.getID(), ActionNames.SUB_TREE_SAVED));
        }

        // delete expired backups : here everything went right so we can
        // proceed to deletion
        for (File expiredBackupFile : expiredBackupFiles) {
            try {
                FileUtils.deleteQuietly(expiredBackupFile);
            } catch (Exception ex) {
                log.warn("Failed to delete backup file " + expiredBackupFile.getName()); //$NON-NLS-1$
            }
        }
    } catch (Throwable ex) {
        log.error("Error saving tree:", ex);
        if (ex instanceof Error) {
            throw (Error) ex;
        }
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        throw new IllegalUserActionException("Couldn't save test plan to file: " + updateFile, ex);
    } finally {
        JOrphanUtils.closeQuietly(ostream);
    }
    GuiPackage.getInstance().updateCurrentGui();
}

From source file:org.apache.jmeter.gui.action.SearchTreeDialog.java

/**
 * @param e {@link ActionEvent}/* www  . j  a v a  2s  . c  om*/
 */
private void doSearch(ActionEvent e) {
    boolean expand = e.getSource() == searchAndExpandButton;
    String wordToSearch = searchTF.getText();
    if (StringUtils.isEmpty(wordToSearch)) {
        return;
    } else {
        this.lastSearch = wordToSearch;
    }

    // reset previous result
    ActionRouter.getInstance().doActionNow(new ActionEvent(e.getSource(), e.getID(), ActionNames.SEARCH_RESET));
    // do search
    Searcher searcher = null;
    if (isRegexpCB.isSelected()) {
        searcher = new RegexpSearcher(isCaseSensitiveCB.isSelected(), searchTF.getText());
    } else {
        searcher = new RawTextSearcher(isCaseSensitiveCB.isSelected(), searchTF.getText());
    }
    GuiPackage guiPackage = GuiPackage.getInstance();
    JMeterTreeModel jMeterTreeModel = guiPackage.getTreeModel();
    Set<JMeterTreeNode> nodes = new HashSet<>();
    for (JMeterTreeNode jMeterTreeNode : jMeterTreeModel.getNodesOfType(Searchable.class)) {
        try {
            if (jMeterTreeNode.getUserObject() instanceof Searchable) {
                Searchable searchable = (Searchable) jMeterTreeNode.getUserObject();
                List<JMeterTreeNode> matchingNodes = jMeterTreeNode.getPathToThreadGroup();
                List<String> searchableTokens = searchable.getSearchableTokens();
                boolean result = searcher.search(searchableTokens);
                if (result) {
                    nodes.addAll(matchingNodes);
                }
            }
        } catch (Exception ex) {
            logger.error("Error occured searching for word:" + wordToSearch, ex);
        }
    }
    GuiPackage guiInstance = GuiPackage.getInstance();
    JTree jTree = guiInstance.getMainFrame().getTree();

    for (JMeterTreeNode jMeterTreeNode : nodes) {
        jMeterTreeNode.setMarkedBySearch(true);
        if (expand) {
            jTree.expandPath(new TreePath(jMeterTreeNode.getPath()));
        }
    }
    GuiPackage.getInstance().getMainFrame().repaint();
    searchTF.requestFocusInWindow();
    this.setVisible(false);
}

From source file:org.apache.jmeter.gui.MainFrame.java

/**
 * Handles click on warnIndicator/*  w w w . j a va  2  s .c om*/
 */
@Override
public void actionPerformed(ActionEvent event) {
    if (event.getSource() == warnIndicator) {
        ActionRouter.getInstance().doActionNow(
                new ActionEvent(event.getSource(), event.getID(), ActionNames.LOGGER_PANEL_ENABLE_DISABLE));
    }
}

From source file:org.apache.jmeter.visualizers.RespTimeGraphVisualizer.java

@Override
public void actionPerformed(ActionEvent event) {
    boolean forceReloadData = false;
    final Object eventSource = event.getSource();
    if (eventSource == displayButton) {
        actionMakeGraph();// ww  w  . j a v a  2s  . co m
    } else if (eventSource == saveGraph) {
        saveGraphToFile = true;
        try {
            ActionRouter.getInstance().getAction(ActionNames.SAVE_GRAPHICS, SaveGraphics.class.getName())
                    .doAction(new ActionEvent(this, event.getID(), ActionNames.SAVE_GRAPHICS));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    } else if (eventSource == syncWithName) {
        graphTitle.setText(namePanel.getName());
    } else if (eventSource == dynamicGraphSize) {
        enableDynamicGraph(dynamicGraphSize.isSelected());
    } else if (eventSource == samplerSelection) {
        enableSamplerSelection(samplerSelection.isSelected());
        if (!samplerSelection.isSelected()) {
            // Force reload data
            forceReloadData = true;
        }
    }
    // Not 'else if' because forceReloadData 
    if (eventSource == applyFilterBtn || eventSource == intervalButton || forceReloadData) {
        if (eventSource == intervalButton) {
            intervalValue = Integer.parseInt(intervalField.getText());
        }
        if (eventSource == applyFilterBtn && samplerSelection.isSelected()
                && samplerMatchLabel.getText() != null && samplerMatchLabel.getText().length() > 0) {
            pattern = createPattern(samplerMatchLabel.getText());
        } else if (forceReloadData) {
            pattern = null;
            matcher = null;
        }
        if (getFile() != null && getFile().length() > 0) {
            // Reload data from file
            clearData();
            FilePanel filePanel = (FilePanel) getFilePanel();
            filePanel.actionPerformed(event);
        } else {
            // Reload data form internal list of results
            synchronized (lockInterval) {
                if (internalList.size() >= 2) {
                    List<RespTimeGraphDataBean> tempList = new ArrayList<>();
                    tempList.addAll(internalList);
                    this.clearData();
                    for (RespTimeGraphDataBean data : tempList) {
                        SampleResult sr = new SampleResult(data.getStartTime(), data.getTime());
                        sr.setSampleLabel(data.getSamplerLabel());
                        this.add(sr);
                    }
                }
            }
        }
    }
}

From source file:org.apache.jmeter.visualizers.StatGraphVisualizer.java

@Override
public void actionPerformed(ActionEvent event) {
    boolean forceReloadData = false;
    final Object eventSource = event.getSource();
    if (eventSource == displayButton) {
        actionMakeGraph();//from   w w w  . j a  v  a  2s . c  om
    } else if (eventSource == saveGraph) {
        saveGraphToFile = true;
        try {
            ActionRouter.getInstance().getAction(ActionNames.SAVE_GRAPHICS, SaveGraphics.class.getName())
                    .doAction(new ActionEvent(this, event.getID(), ActionNames.SAVE_GRAPHICS));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    } else if (eventSource == saveTable) {
        JFileChooser chooser = FileDialoger.promptToSaveFile("statistics.csv"); //$NON-NLS-1$
        if (chooser == null) {
            return;
        }
        FileWriter writer = null;
        try {
            writer = new FileWriter(chooser.getSelectedFile()); // TODO Charset ?
            CSVSaveService.saveCSVStats(getAllTableData(model, FORMATS), writer,
                    saveHeaders.isSelected() ? getLabels(COLUMNS) : null);
        } catch (IOException e) {
            JMeterUtils.reportErrorToUser(e.getMessage(), "Error saving data");
        } finally {
            JOrphanUtils.closeQuietly(writer);
        }
    } else if (eventSource == chooseForeColor) {
        Color color = JColorChooser.showDialog(null, JMeterUtils.getResString("aggregate_graph_choose_color"), //$NON-NLS-1$
                colorBarGraph);
        if (color != null) {
            colorForeGraph = color;
        }
    } else if (eventSource == syncWithName) {
        graphTitle.setText(namePanel.getName());
    } else if (eventSource == dynamicGraphSize) {
        // if use dynamic graph size is checked, we disable the dimension fields
        if (dynamicGraphSize.isSelected()) {
            graphWidth.setEnabled(false);
            graphHeight.setEnabled(false);
        } else {
            graphWidth.setEnabled(true);
            graphHeight.setEnabled(true);
        }
    } else if (eventSource == columnSelection) {
        if (columnSelection.isSelected()) {
            columnMatchLabel.setEnabled(true);
            applyFilterBtn.setEnabled(true);
            caseChkBox.setEnabled(true);
            regexpChkBox.setEnabled(true);
        } else {
            columnMatchLabel.setEnabled(false);
            applyFilterBtn.setEnabled(false);
            caseChkBox.setEnabled(false);
            regexpChkBox.setEnabled(false);
            // Force reload data
            forceReloadData = true;
        }
    }
    // Not 'else if' because forceReloadData 
    if (eventSource == applyFilterBtn || forceReloadData) {
        if (columnSelection.isSelected() && columnMatchLabel.getText() != null
                && columnMatchLabel.getText().length() > 0) {
            pattern = createPattern(columnMatchLabel.getText());
        } else if (forceReloadData) {
            pattern = null;
            matcher = null;
        }
        if (getFile() != null && getFile().length() > 0) {
            clearData();
            FilePanel filePanel = (FilePanel) getFilePanel();
            filePanel.actionPerformed(event);
        }
    } else if (eventSource instanceof JButton) {
        // Changing color for column
        JButton btn = ((JButton) eventSource);
        if (btn.getName() != null) {
            try {
                BarGraph bar = eltList.get(Integer.parseInt(btn.getName()));
                Color color = JColorChooser.showDialog(null, bar.getLabel(), bar.getBackColor());
                if (color != null) {
                    bar.setBackColor(color);
                    btn.setBackground(bar.getBackColor());
                }
            } catch (NumberFormatException nfe) {
            } // nothing to do
        }
    }
}

From source file:org.bitbucket.mlopatkin.android.logviewer.widgets.UiHelper.java

/**
 * Creates a wrapper around an existing action of the component to be used
 * in menus./*from  w  w  w  .jav  a2s.c  o m*/
 * 
 * @param c
 *            base component
 * @param actionKey
 *            key in the component's ActionMap
 * @param caption
 *            caption of the action wrapper
 * @param acceleratorKey
 *            accelerator key of the action wrapper
 * @return action that translates its
 *         {@link Action#actionPerformed(ActionEvent)} to the underlaying
 *         existing action.
 */
public static Action createActionWrapper(final JComponent c, final String actionKey, String caption,
        final String acceleratorKey) {
    final Action baseAction = c.getActionMap().get(actionKey);
    Action result = new AbstractAction(caption) {
        {
            putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(acceleratorKey));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            ActionEvent newEvent = new ActionEvent(c, e.getID(), actionKey, e.getWhen(), e.getModifiers());
            baseAction.actionPerformed(newEvent);
        }

        @Override
        public void setEnabled(boolean newValue) {
            super.setEnabled(newValue);
            baseAction.setEnabled(newValue);
        }
    };
    return result;
}