Example usage for javax.swing JComboBox getSelectedItem

List of usage examples for javax.swing JComboBox getSelectedItem

Introduction

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

Prototype

public Object getSelectedItem() 

Source Link

Document

Returns the current selected item.

Usage

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

void showHideSubparameters(final JComboBox combobox, final SubmodelInfo info) {
    if (!combobox.isDisplayable()) {
        return;//w  w  w .  j a  v  a2s  .  c  om
    }
    final ClassElement classElement = (ClassElement) combobox.getSelectedItem();

    info.setActualType(classElement.clazz, classElement.instance);
    final int level = calculateParameterLevel(info);
    for (int i = singleRunParametersPanel.getComponentCount() - 1; i >= level + 1; --i)
        singleRunParametersPanel.remove(i);

    if (classElement.clazz != null) {
        try {
            final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> subparameters = ParameterTreeUtils
                    .fetchSubparameters(currentModelHandler, info);
            String title = "Configure " + info.getName().replaceAll("([A-Z])", " $1").trim();
            createAndDisplayAParameterPanel(subparameters, title, info, true, currentModelHandler);
        } catch (final ModelInformationException e) {
            info.setActualType(null, null);
            JOptionPane.showMessageDialog(wizard, new JLabel(e.getMessage()), "Error while analyizing model",
                    JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            combobox.setSelectedIndex(0);
        }
    }

    parametersScrollPane.invalidate();
    parametersScrollPane.validate();
    final JScrollBar horizontalScrollBar = parametersScrollPane.getHorizontalScrollBar();
    horizontalScrollBar.setValue(horizontalScrollBar.getMaximum());
}

From source file:edu.virginia.iath.oxygenplugins.juel.JUELPluginMenu.java

public JUELPluginMenu(StandalonePluginWorkspace spw, LocalOptions ops) {
    super(name, true);
    ws = spw;/*from  ww  w .  ja  va  2s.c  o m*/
    options = ops;

    // setup the options
    //options.readStorage();

    // Find names
    JMenuItem search = new JMenuItem("Find Name");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Name";

            final JTextField lastName = new JTextField("", 30);
            lastName.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL("http://juel.iath.virginia.edu/academical_db/people/find_people?term="
                                + lastName.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String name = cur.getString("label");
                            String id = String.format("P%05d", cur.getInt("value"));
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for last name, then choose a full name from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Last Name: "));
            addPanelInner.add(lastName);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);

    // Find places
    search = new JMenuItem("Find Place");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Place";

            final JTextField searchText = new JTextField("", 30);
            searchText.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL(
                                "http://academical.village.virginia.edu/academical_db/places/find_places?term="
                                        + searchText.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String id = String.format("PL%04d", cur.getInt("value"));
                            String name = cur.getString("label") + " (" + id + ")";
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for a place name, then choose one from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Keyword: "));
            addPanelInner.add(searchText);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);

    // Find corporate bodies
    search = new JMenuItem("Find Corporate Body");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Corporate Body";

            final JTextField searchText = new JTextField("", 30);
            searchText.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL(
                                "http://academical.village.virginia.edu/academical_db/corporate_bodies/find?term="
                                        + searchText.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String id = String.format("CB%04d", cur.getInt("value"));
                            String name = cur.getString("label") + " (" + id + ")";
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for a corporate body, then one from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Keyword: "));
            addPanelInner.add(searchText);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);

    // Find Courses
    search = new JMenuItem("Find Course");
    search.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent selection) {
            String label = "Find Course";

            final JTextField searchText = new JTextField("", 30);
            searchText.setPreferredSize(new Dimension(350, 25));
            //JTextField projectName = new JTextField("", 30);

            final JComboBox possibleVals = new JComboBox();
            possibleVals.setEnabled(false);
            possibleVals.setPreferredSize(new Dimension(350, 25));

            JButton search = new JButton("Search");
            search.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent selection) {
                    // query the database
                    try {
                        String json = "";
                        String line;
                        URL url = new URL(
                                "http://academical.village.virginia.edu/academical_db/courses/find?term="
                                        + searchText.getText());
                        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                        while ((line = in.readLine()) != null) {
                            json += line;
                        }
                        JSONArray obj = new JSONArray(json);

                        // Read the JSON and update possibleVals
                        possibleVals.removeAllItems();
                        possibleVals.setEnabled(false);

                        for (int i = 0; i < obj.length(); i++) {
                            JSONObject cur = obj.getJSONObject(i);
                            String id = String.format("C%04d", cur.getInt("value"));
                            String name = cur.getString("label") + " (" + id + ")";
                            possibleVals.addItem(new ComboBoxObject(name, id));
                            possibleVals.setEnabled(true);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        possibleVals.setEnabled(false);
                    }

                    return;
                }
            });
            search.setPreferredSize(new Dimension(100, 25));

            JButton insert = new JButton("Insert");
            insert.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent sel) {
                    // Insert into the page
                    // Get the selected value, grab the ID, then insert into the document

                    // Get the editor
                    WSTextEditorPage ed = null;
                    WSEditor editorAccess = ws
                            .getCurrentEditorAccess(StandalonePluginWorkspace.MAIN_EDITING_AREA);
                    if (editorAccess != null && editorAccess.getCurrentPage() instanceof WSTextEditorPage) {
                        ed = (WSTextEditorPage) editorAccess.getCurrentPage();
                    }

                    String result = "key=\"" + ((ComboBoxObject) possibleVals.getSelectedItem()).id + "\"";

                    // Update the text in the document
                    ed.beginCompoundUndoableEdit();
                    int selectionOffset = ed.getSelectionStart();
                    ed.deleteSelection();
                    javax.swing.text.Document doc = ed.getDocument();
                    try {
                        if (selectionOffset > 0 && !doc.getText(selectionOffset - 1, 1).equals(" "))
                            result = " " + result;
                        if (selectionOffset > 0 && !doc.getText(selectionOffset, 1).equals(" ")
                                && !doc.getText(selectionOffset, 1).equals(">"))
                            result = result + " ";
                        doc.insertString(selectionOffset, result, javax.swing.text.SimpleAttributeSet.EMPTY);
                    } catch (javax.swing.text.BadLocationException b) {
                        // Okay if it doesn't work
                    }
                    ed.endCompoundUndoableEdit();

                    return;
                }
            });
            insert.setPreferredSize(new Dimension(100, 25));

            java.awt.GridLayout layoutOuter = new java.awt.GridLayout(3, 1);
            java.awt.FlowLayout layout = new java.awt.FlowLayout(FlowLayout.RIGHT); // rows, columns

            JPanel addPanel = new JPanel();
            JPanel addPanelInner = new JPanel();
            addPanel.setLayout(layoutOuter);
            addPanel.add(new JLabel("Search for a course, then choose one from the list below"));
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Search Keyword: "));
            addPanelInner.add(searchText);
            addPanelInner.add(search);
            addPanel.add(addPanelInner);
            addPanelInner = new JPanel();
            addPanelInner.setLayout(layout);
            addPanelInner.add(new JLabel("Narrow Search: "));
            addPanelInner.add(possibleVals);
            addPanelInner.add(insert);
            addPanel.add(addPanelInner);

            JOptionPane.showMessageDialog((java.awt.Frame) ws.getParentFrame(), addPanel, label,
                    JOptionPane.PLAIN_MESSAGE);

        }
    });
    this.add(search);
}

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

/** {@inheritDoc} 
 *///  w w  w .  j  av  a  2 s  .  c om
@Override
public boolean onButtonPress(final Button button) {
    if (Button.NEXT.equals(button)) {
        ParameterTree parameterTree = null;
        if (tabbedPane.getSelectedIndex() == SINGLE_RUN_GUI_TABINDEX) {
            currentModelHandler.setIntelliMethodPlugin(null);
            parameterTree = new ParameterTree();
            final Set<ParameterInfo> invalids = new HashSet<ParameterInfo>();

            @SuppressWarnings("rawtypes")
            final Enumeration treeValues = parameterValueComponentTree.breadthFirstEnumeration();
            treeValues.nextElement(); // root element
            while (treeValues.hasMoreElements()) {
                final DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeValues.nextElement();
                @SuppressWarnings("unchecked")
                final Pair<ParameterInfo, JComponent> userData = (Pair<ParameterInfo, JComponent>) node
                        .getUserObject();
                final ParameterInfo parameterInfo = userData.getFirst();
                final JComponent valueContainer = userData.getSecond();

                if (parameterInfo instanceof ISubmodelGUIInfo) {
                    final ISubmodelGUIInfo sgi = (ISubmodelGUIInfo) parameterInfo;
                    if (sgi.getParent() != null) {
                        final DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) node.getParent();
                        @SuppressWarnings("unchecked")
                        final Pair<ParameterInfo, JComponent> parentUserData = (Pair<ParameterInfo, JComponent>) parentNode
                                .getUserObject();
                        final SubmodelInfo parentParameterInfo = (SubmodelInfo) parentUserData.getFirst();
                        if (invalids.contains(parentParameterInfo)
                                || !classEquals(parentParameterInfo.getActualType(), sgi.getParentValue())) {
                            invalids.add(parameterInfo);
                            continue;
                        }
                    }
                }

                if (parameterInfo.isBoolean()) {
                    final JCheckBox checkBox = (JCheckBox) valueContainer;
                    parameterInfo.setValue(checkBox.isSelected());
                } else if (parameterInfo.isEnum()) {
                    final JComboBox comboBox = (JComboBox) valueContainer;
                    parameterInfo.setValue(comboBox.getSelectedItem());
                } else if (parameterInfo instanceof MasonChooserParameterInfo) {
                    final JComboBox comboBox = (JComboBox) valueContainer;
                    parameterInfo.setValue(comboBox.getSelectedIndex());
                } else if (parameterInfo instanceof SubmodelInfo) {
                    // we don't need the SubmodelInfo parameters anymore (all descendant parameters are in the tree too)
                    // but we need to check that an actual type is provided
                    final SubmodelInfo smi = (SubmodelInfo) parameterInfo;
                    final JComboBox comboBox = (JComboBox) ((JPanel) valueContainer).getComponent(0);
                    final ClassElement selected = (ClassElement) comboBox.getSelectedItem();
                    smi.setActualType(selected.clazz, selected.instance);

                    if (smi.getActualType() == null) {
                        final String errorMsg = "Please select a type from the dropdown list of "
                                + smi.getName().replaceAll("([A-Z])", " $1");
                        JOptionPane.showMessageDialog(wizard, new JLabel(errorMsg), "Error",
                                JOptionPane.ERROR_MESSAGE);
                        return false;
                    }

                    //continue;
                } else if (parameterInfo.isFile()) {
                    final JTextField textField = (JTextField) valueContainer.getComponent(0);
                    if (textField.getText().trim().isEmpty())
                        log.warn("Empty string was specified as file parameter "
                                + parameterInfo.getName().replaceAll("([A-Z])", " $1"));

                    final File file = new File(textField.getToolTipText());
                    if (!file.exists()) {
                        final String errorMsg = "Please specify an existing file parameter "
                                + parameterInfo.getName().replaceAll("([A-Z])", " $1");
                        JOptionPane.showMessageDialog(wizard, new JLabel(errorMsg), "Error",
                                JOptionPane.ERROR_MESSAGE);
                        return false;
                    }

                    parameterInfo.setValue(
                            ParameterInfo.getValue(textField.getToolTipText(), parameterInfo.getType()));
                } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                    final JTextField textField = (JTextField) valueContainer.getComponent(0);
                    parameterInfo.setValue(
                            ParameterInfo.getValue(textField.getText().trim(), parameterInfo.getType()));
                } else {
                    final JTextField textField = (JTextField) valueContainer;
                    parameterInfo
                            .setValue(ParameterInfo.getValue(textField.getText(), parameterInfo.getType()));
                    if ("String".equals(parameterInfo.getType()) && parameterInfo.getValue() == null)
                        parameterInfo.setValue(textField.getText().trim());
                }

                final AbstractParameterInfo<?> batchParameterInfo = InfoConverter
                        .parameterInfo2ParameterInfo(parameterInfo);
                parameterTree.addNode(batchParameterInfo);
            }

            dashboard.setOnLineCharts(onLineChartsCheckBox.isSelected());
            dashboard.setDisplayAdvancedCharts(advancedChartsCheckBox.isSelected());
        }

        if (tabbedPane.getSelectedIndex() == PARAMSWEEP_GUI_TABINDEX) {
            currentModelHandler.setIntelliMethodPlugin(null);
            boolean success = true;
            if (editedNode != null)
                success = modify();

            if (success) {
                String invalidInfoName = checkInfos(true);
                if (invalidInfoName != null) {
                    Utilities.userAlert(sweepPanel,
                            "Please select a type from the dropdown list of " + invalidInfoName);
                    return false;
                }

                invalidInfoName = checkInfos(false);
                if (invalidInfoName != null) {
                    Utilities.userAlert(sweepPanel, "Please specify a file for parameter " + invalidInfoName);
                    return false;
                }

                if (needWarning()) {
                    final int result = Utilities.askUser(sweepPanel, false, "Warning",
                            "There are two or more combination boxes that contains non-constant parameters."
                                    + " Parameters are unsynchronized:",
                            "simulation may exit before all parameter values are assigned.", " ",
                            "To explore all possible combinations you must use only one combination box.", " ",
                            "Do you want to run simulation with these parameter settings?");
                    if (result == 0) {
                        return false;
                    }
                }

                try {
                    parameterTree = createParameterTreeFromParamSweepGUI();

                    final ParameterNode rootNode = parameterTree.getRoot();
                    dumpParameterTree(rootNode);

                    //                  dashboard.setOnLineCharts(onLineChartsCheckBoxPSW.isSelected());
                } catch (final ModelInformationException e) {
                    JOptionPane.showMessageDialog(wizard, new JLabel(e.getMessage()),
                            "Error while creating runs", JOptionPane.ERROR_MESSAGE);
                    e.printStackTrace();
                    return false;
                }
            } else
                return false;
        }

        if (tabbedPane.getSelectedIndex() == GASEARCH_GUI_TABINDEX) {
            final IIntelliDynamicMethodPlugin gaPlugin = (IIntelliDynamicMethodPlugin) gaSearchHandler;
            currentModelHandler.setIntelliMethodPlugin(gaPlugin);
            boolean success = gaSearchPanel.closeActiveModification();

            if (success) {
                String invalidInfoName = checkInfosInGeneTree();
                if (invalidInfoName != null) {
                    Utilities.userAlert(sweepPanel,
                            "Please select a type from the dropdown list of " + invalidInfoName);
                    return false;
                }

                final String[] errors = gaSearchHandler.checkGAModel();
                if (errors != null) {
                    Utilities.userAlert(sweepPanel, (Object[]) errors);
                    return false;
                }

                final DefaultMutableTreeNode parameterTreeRootNode = new DefaultMutableTreeNode();
                final IIntelliContext ctx = new DashboardIntelliContext(parameterTreeRootNode,
                        gaSearchHandler.getChromosomeTree());
                gaPlugin.alterParameterTree(ctx);
                parameterTree = InfoConverter.node2ParameterTree(parameterTreeRootNode);
                dashboard.setOptimizationDirection(gaSearchHandler.getFitnessFunctionDirection());

            } else
                return false;
        }

        currentModelHandler.setParameters(parameterTree);
    }

    return true;
}

From source file:com.nikonhacker.gui.EmulatorUI.java

private void openChipOptionsDialog(final int chip) {

    // ------------------------ Disassembly options

    JPanel disassemblyOptionsPanel = new JPanel(new MigLayout("", "[left,grow][left,grow]"));

    // Prepare sample code area
    final RSyntaxTextArea listingArea = new RSyntaxTextArea(20, 90);
    SourceCodeFrame.prepareAreaFormat(chip, listingArea);

    final List<JCheckBox> outputOptionsCheckBoxes = new ArrayList<JCheckBox>();
    ActionListener areaRefresherListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            try {
                Set<OutputOption> sampleOptions = EnumSet.noneOf(OutputOption.class);
                dumpOptionCheckboxes(outputOptionsCheckBoxes, sampleOptions);
                int baseAddress = framework.getPlatform(chip).getCpuState().getResetAddress();
                int lastAddress = baseAddress;
                Memory sampleMemory = new DebuggableMemory(false);
                sampleMemory.map(baseAddress, 0x100, true, true, true);
                StringWriter writer = new StringWriter();
                Disassembler disassembler;
                if (chip == Constants.CHIP_FR) {
                    sampleMemory.store16(lastAddress, 0x1781); // PUSH    RP
                    lastAddress += 2;/* w  w  w  .  j av  a 2  s . co m*/
                    sampleMemory.store16(lastAddress, 0x8FFE); // PUSH    (FP,AC,R12,R11,R10,R9,R8)
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x83EF); // ANDCCR  #0xEF
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x9F80); // LDI:32  #0x68000000,R0
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x6800);
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x0000);
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x2031); // LD      @(FP,0x00C),R1
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0xB581); // LSL     #24,R1
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x1A40); // DMOVB   R13,@0x40
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x9310); // ORCCR   #0x10
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x8D7F); // POP     (R8,R9,R10,R11,R12,AC,FP)
                    lastAddress += 2;
                    sampleMemory.store16(lastAddress, 0x0781); // POP    RP
                    lastAddress += 2;

                    disassembler = new Dfr();
                    disassembler.setDebugPrintWriter(new PrintWriter(new StringWriter())); // Ignore
                    disassembler.setOutputFileName(null);
                    disassembler.processOptions(new String[] { "-m", "0x" + Format.asHex(baseAddress, 8) + "-0x"
                            + Format.asHex(lastAddress, 8) + "=CODE" });
                } else {
                    sampleMemory.store32(lastAddress, 0x340B0001); // li      $t3, 0x0001
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x17600006); // bnez    $k1, 0xBFC00020
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x00000000); //  nop
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x54400006); // bnezl   $t4, 0xBFC00028
                    lastAddress += 4;
                    sampleMemory.store32(lastAddress, 0x3C0C0000); //  ?lui   $t4, 0x0000
                    lastAddress += 4;

                    int baseAddress16 = lastAddress;
                    int lastAddress16 = baseAddress16;
                    sampleMemory.store32(lastAddress16, 0xF70064F6); // save    $ra,$s0,$s1,$s2-$s7,$fp, 0x30
                    lastAddress16 += 4;
                    sampleMemory.store16(lastAddress16, 0x6500); // nop
                    lastAddress16 += 2;
                    sampleMemory.store32(lastAddress16, 0xF7006476); // restore $ra,$s0,$s1,$s2-$s7,$fp, 0x30
                    lastAddress16 += 4;
                    sampleMemory.store16(lastAddress16, 0xE8A0); // ret
                    lastAddress16 += 2;

                    disassembler = new Dtx();
                    disassembler.setDebugPrintWriter(new PrintWriter(new StringWriter())); // Ignore
                    disassembler.setOutputFileName(null);
                    disassembler.processOptions(new String[] { "-m",
                            "0x" + Format.asHex(baseAddress, 8) + "-0x" + Format.asHex(lastAddress, 8)
                                    + "=CODE:32",
                            "-m", "0x" + Format.asHex(baseAddress16, 8) + "-0x" + Format.asHex(lastAddress16, 8)
                                    + "=CODE:16" });
                }
                disassembler.setOutputOptions(sampleOptions);
                disassembler.setMemory(sampleMemory);
                disassembler.initialize();
                disassembler.setOutWriter(writer);
                disassembler.disassembleMemRanges();
                disassembler.cleanup();
                listingArea.setText("");
                listingArea.append(writer.toString());
                listingArea.setCaretPosition(0);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

    int i = 1;
    for (OutputOption outputOption : OutputOption.allFormatOptions) {
        JCheckBox checkBox = makeOutputOptionCheckBox(chip, outputOption, prefs.getOutputOptions(chip), false);
        if (checkBox != null) {
            outputOptionsCheckBoxes.add(checkBox);
            disassemblyOptionsPanel.add(checkBox, (i % 2 == 0) ? "wrap" : "");
            checkBox.addActionListener(areaRefresherListener);
            i++;
        }
    }
    if (i % 2 == 0) {
        disassemblyOptionsPanel.add(new JLabel(), "wrap");
    }

    // Force a refresh
    areaRefresherListener.actionPerformed(new ActionEvent(outputOptionsCheckBoxes.get(0), 0, ""));

    //        disassemblyOptionsPanel.add(new JLabel("Sample output:", SwingConstants.LEADING), "gapbottom 1, span, split 2, aligny center");
    //        disassemblyOptionsPanel.add(new JSeparator(), "span 2,wrap");
    disassemblyOptionsPanel.add(new JSeparator(), "span 2, gapleft rel, growx, wrap");
    disassemblyOptionsPanel.add(new JLabel("Sample output:"), "span 2,wrap");
    disassemblyOptionsPanel.add(new JScrollPane(listingArea), "span 2,wrap");
    disassemblyOptionsPanel.add(new JLabel("Tip: hover over the option checkboxes for help"),
            "span 2, center, wrap");

    // ------------------------ Emulation options

    JPanel emulationOptionsPanel = new JPanel(new VerticalLayout(5, VerticalLayout.LEFT));
    emulationOptionsPanel.add(new JLabel());
    JLabel warningLabel = new JLabel(
            "NOTE: these options only take effect after reloading the firmware (or performing a 'Stop and reset')");
    warningLabel.setBackground(Color.RED);
    warningLabel.setOpaque(true);
    warningLabel.setForeground(Color.WHITE);
    warningLabel.setHorizontalAlignment(SwingConstants.CENTER);
    emulationOptionsPanel.add(warningLabel);
    emulationOptionsPanel.add(new JLabel());

    final JCheckBox writeProtectFirmwareCheckBox = new JCheckBox("Write-protect firmware");
    writeProtectFirmwareCheckBox.setSelected(prefs.isFirmwareWriteProtected(chip));
    emulationOptionsPanel.add(writeProtectFirmwareCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, any attempt to write to the loaded firmware area will result in an Emulator error. This can help trap spurious writes"));

    final JCheckBox dmaSynchronousCheckBox = new JCheckBox("Make DMA synchronous");
    dmaSynchronousCheckBox.setSelected(prefs.isDmaSynchronous(chip));
    emulationOptionsPanel.add(dmaSynchronousCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, DMA operations will be performed immediately, pausing the CPU. Otherwise they are performed in a separate thread."));

    final JCheckBox autoEnableTimersCheckBox = new JCheckBox("Auto enable timers");
    autoEnableTimersCheckBox.setSelected(prefs.isAutoEnableTimers(chip));
    emulationOptionsPanel.add(autoEnableTimersCheckBox);
    emulationOptionsPanel
            .add(new JLabel("If checked, timers will be automatically enabled upon reset or firmware load."));

    // Log memory messages
    final JCheckBox logMemoryMessagesCheckBox = new JCheckBox("Log memory messages");
    logMemoryMessagesCheckBox.setSelected(prefs.isLogMemoryMessages(chip));
    emulationOptionsPanel.add(logMemoryMessagesCheckBox);
    emulationOptionsPanel
            .add(new JLabel("If checked, messages related to memory will be logged to the console."));

    // Log serial messages
    final JCheckBox logSerialMessagesCheckBox = new JCheckBox("Log serial messages");
    logSerialMessagesCheckBox.setSelected(prefs.isLogSerialMessages(chip));
    emulationOptionsPanel.add(logSerialMessagesCheckBox);
    emulationOptionsPanel.add(
            new JLabel("If checked, messages related to serial interfaces will be logged to the console."));

    // Log register messages
    final JCheckBox logRegisterMessagesCheckBox = new JCheckBox("Log register messages");
    logRegisterMessagesCheckBox.setSelected(prefs.isLogRegisterMessages(chip));
    emulationOptionsPanel.add(logRegisterMessagesCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, warnings related to unimplemented register addresses will be logged to the console."));

    // Log pin messages
    final JCheckBox logPinMessagesCheckBox = new JCheckBox("Log pin messages");
    logPinMessagesCheckBox.setSelected(prefs.isLogPinMessages(chip));
    emulationOptionsPanel.add(logPinMessagesCheckBox);
    emulationOptionsPanel.add(new JLabel(
            "If checked, warnings related to unimplemented I/O pins will be logged to the console."));

    emulationOptionsPanel.add(new JSeparator(JSeparator.HORIZONTAL));

    // Alt mode upon Debug
    JPanel altDebugPanel = new JPanel(new FlowLayout());
    Object[] altDebugMode = EnumSet.allOf(EmulationFramework.ExecutionMode.class).toArray();
    final JComboBox altModeForDebugCombo = new JComboBox(new DefaultComboBoxModel(altDebugMode));
    for (int j = 0; j < altDebugMode.length; j++) {
        if (altDebugMode[j].equals(prefs.getAltExecutionModeForSyncedCpuUponDebug(chip))) {
            altModeForDebugCombo.setSelectedIndex(j);
        }
    }
    altDebugPanel.add(new JLabel(Constants.CHIP_LABEL[1 - chip] + " mode when " + Constants.CHIP_LABEL[chip]
            + " runs in sync Debug: "));
    altDebugPanel.add(altModeForDebugCombo);
    emulationOptionsPanel.add(altDebugPanel);
    emulationOptionsPanel
            .add(new JLabel("If 'sync mode' is selected, this is the mode the " + Constants.CHIP_LABEL[1 - chip]
                    + " chip will run in when running the " + Constants.CHIP_LABEL[chip] + " in Debug mode"));

    // Alt mode upon Step
    JPanel altStepPanel = new JPanel(new FlowLayout());
    Object[] altStepMode = EnumSet.allOf(EmulationFramework.ExecutionMode.class).toArray();
    final JComboBox altModeForStepCombo = new JComboBox(new DefaultComboBoxModel(altStepMode));
    for (int j = 0; j < altStepMode.length; j++) {
        if (altStepMode[j].equals(prefs.getAltExecutionModeForSyncedCpuUponStep(chip))) {
            altModeForStepCombo.setSelectedIndex(j);
        }
    }
    altStepPanel.add(new JLabel(Constants.CHIP_LABEL[1 - chip] + " mode when " + Constants.CHIP_LABEL[chip]
            + " runs in sync Step: "));
    altStepPanel.add(altModeForStepCombo);
    emulationOptionsPanel.add(altStepPanel);
    emulationOptionsPanel
            .add(new JLabel("If 'sync mode' is selected, this is the mode the " + Constants.CHIP_LABEL[1 - chip]
                    + " chip will run in when running the " + Constants.CHIP_LABEL[chip] + " in Step mode"));

    // ------------------------ Prepare tabbed pane

    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab(Constants.CHIP_LABEL[chip] + " Disassembly Options", null, disassemblyOptionsPanel);
    tabbedPane.addTab(Constants.CHIP_LABEL[chip] + " Emulation Options", null, emulationOptionsPanel);

    if (chip == Constants.CHIP_TX) {
        JPanel chipSpecificOptionsPanel = new JPanel(new VerticalLayout(5, VerticalLayout.LEFT));

        chipSpecificOptionsPanel.add(new JLabel("Eeprom status upon startup:"));

        ActionListener eepromInitializationRadioActionListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                prefs.setEepromInitMode(Prefs.EepromInitMode.valueOf(e.getActionCommand()));
            }
        };
        JRadioButton blank = new JRadioButton("Blank");
        blank.setActionCommand(Prefs.EepromInitMode.BLANK.name());
        blank.addActionListener(eepromInitializationRadioActionListener);
        if (Prefs.EepromInitMode.BLANK.equals(prefs.getEepromInitMode()))
            blank.setSelected(true);
        JRadioButton persistent = new JRadioButton("Persistent across sessions");
        persistent.setActionCommand(Prefs.EepromInitMode.PERSISTENT.name());
        persistent.addActionListener(eepromInitializationRadioActionListener);
        if (Prefs.EepromInitMode.PERSISTENT.equals(prefs.getEepromInitMode()))
            persistent.setSelected(true);
        JRadioButton lastLoaded = new JRadioButton("Last Loaded");
        lastLoaded.setActionCommand(Prefs.EepromInitMode.LAST_LOADED.name());
        lastLoaded.addActionListener(eepromInitializationRadioActionListener);
        if (Prefs.EepromInitMode.LAST_LOADED.equals(prefs.getEepromInitMode()))
            lastLoaded.setSelected(true);

        ButtonGroup group = new ButtonGroup();
        group.add(blank);
        group.add(persistent);
        group.add(lastLoaded);

        chipSpecificOptionsPanel.add(blank);
        chipSpecificOptionsPanel.add(persistent);
        chipSpecificOptionsPanel.add(lastLoaded);

        chipSpecificOptionsPanel.add(new JLabel("Front panel type:"));
        final JComboBox frontPanelNameCombo = new JComboBox(new String[] { "D5100_small", "D5100_large" });
        if (prefs.getFrontPanelName() != null) {
            frontPanelNameCombo.setSelectedItem(prefs.getFrontPanelName());
        }
        frontPanelNameCombo.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                prefs.setFrontPanelName((String) frontPanelNameCombo.getSelectedItem());
            }
        });
        chipSpecificOptionsPanel.add(frontPanelNameCombo);

        emulationOptionsPanel.add(new JSeparator(JSeparator.HORIZONTAL));

        tabbedPane.addTab(Constants.CHIP_LABEL[chip] + " specific options", null, chipSpecificOptionsPanel);
    }

    // ------------------------ Show it

    if (JOptionPane.OK_OPTION == JOptionPane.showOptionDialog(this, tabbedPane,
            Constants.CHIP_LABEL[chip] + " options", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE,
            null, null, JOptionPane.DEFAULT_OPTION)) {
        // save output options
        dumpOptionCheckboxes(outputOptionsCheckBoxes, prefs.getOutputOptions(chip));
        // apply
        TxCPUState.initRegisterLabels(prefs.getOutputOptions(chip));

        // save other prefs
        prefs.setFirmwareWriteProtected(chip, writeProtectFirmwareCheckBox.isSelected());
        prefs.setDmaSynchronous(chip, dmaSynchronousCheckBox.isSelected());
        prefs.setAutoEnableTimers(chip, autoEnableTimersCheckBox.isSelected());
        prefs.setLogRegisterMessages(chip, logRegisterMessagesCheckBox.isSelected());
        prefs.setLogSerialMessages(chip, logSerialMessagesCheckBox.isSelected());
        prefs.setLogPinMessages(chip, logPinMessagesCheckBox.isSelected());
        prefs.setLogMemoryMessages(chip, logMemoryMessagesCheckBox.isSelected());
        prefs.setAltExecutionModeForSyncedCpuUponDebug(chip,
                (EmulationFramework.ExecutionMode) altModeForDebugCombo.getSelectedItem());
        prefs.setAltExecutionModeForSyncedCpuUponStep(chip,
                (EmulationFramework.ExecutionMode) altModeForStepCombo.getSelectedItem());

    }
}

From source file:search2go.UIFrame.java

private void map(JFormattedTextField bitScore, JFormattedTextField eValue, JComboBox originDB, JTextArea output,
        boolean fullProcess) {
    currentProj.setSelectedDBIndex(originDB.getSelectedIndex());
    currentProj.setBitScoreThreshold(Integer.parseInt(bitScore.getText()));
    currentProj.setEthreshold(Integer.parseInt(txtMapE.getText()));
    mapSequence = new ProcessSequence(currentProj, new ProcessSequenceEnd() {
        @Override/*from w w  w.ja  v a  2s  .c om*/
        public void run() {
            if (!output.getText().contains(
                    "No valid hits found. Please retry with lower bit score or higher e-value thresholds.")) {
                if (currentProj.willDoCC())
                    currentProj.setStage(0, 2);
                if (currentProj.willDoBP())
                    currentProj.setStage(1, 2);
                if (currentProj.willDoBP())
                    currentProj.setStage(2, 2);
                output.append("Mapping done! Please proceed to Identification.\n");
                if (fullProcess) {
                    output.append("Identifying...\n");
                    identify(true);
                }
            }
            currentProj.setAvailable(true);
            prgMapping.setIndeterminate(false);
            mapButton.restore();
        }
    });

    Process mapProcess = new Process(output);

    Path mapScriptPath = new Path("Processes");
    mapScriptPath.append("MapFromBlast.py");
    mapProcess.setScriptCommand(mapScriptPath.toEscString());

    mapSequence.addProcess(mapProcess);
    mapProcess.addParameter("dir", currentProj.getPath().toEscString());
    if (!bitScore.getText().equals(""))
        mapProcess.addParameter("bs", bitScore.getText());
    if (!eValue.getText().equals(""))
        mapProcess.addParameter("e", eValue.getText());
    mapProcess.addParameter("id", originDB.getSelectedItem().toString().replaceAll(" ", ""));
    Path blastLoc = new Path(currentProj.getPath());
    blastLoc.append("BLAST_Results.xml");
    mapProcess.addParameter("o", blastLoc.toString());
    mapProcess.addParameter("gdb", currentProj.getTargetDBString());

    try {
        mapSequence.start();
        mapButton.setStopTargets(mapSequence);
        if (!fullProcess)
            mapButton.activate();
        if (currentProj.willDoCC())
            currentProj.setStage(0, 1);
        if (currentProj.willDoBP())
            currentProj.setStage(1, 1);
        if (currentProj.willDoBP())
            currentProj.setStage(2, 1);
        System.out.println(currentProj.getStage());
        output.setText("Mapping...\n");
        prgMapping.setIndeterminate(true);
    } catch (IOException ex) {
        javax.swing.JOptionPane.showMessageDialog(this, "Error running mapping program.");
    }
}

From source file:userinterface.properties.GUIGraphHandler.java

public void defineConstantsAndPlot(Expression expr, JPanel graph, String seriesName, Boolean isNewGraph,
        boolean is2D) {

    JDialog dialog;/*from ww  w . ja  v a  2  s .com*/
    JButton ok, cancel;
    JScrollPane scrollPane;
    ConstantPickerList constantList;
    JComboBox<String> xAxis, yAxis;

    //init everything
    dialog = new JDialog(GUIPrism.getGUI());
    dialog.setTitle("Define constants and select axes");
    dialog.setSize(500, 400);
    dialog.setLocationRelativeTo(GUIPrism.getGUI());
    dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
    dialog.setModal(true);

    constantList = new ConstantPickerList();
    scrollPane = new JScrollPane(constantList);

    xAxis = new JComboBox<String>();
    yAxis = new JComboBox<String>();

    ok = new JButton("Ok");
    ok.setMnemonic('O');
    cancel = new JButton("Cancel");
    cancel.setMnemonic('C');

    //add all components to their dedicated panels
    JPanel exprPanel = new JPanel(new FlowLayout());
    exprPanel.setBorder(new TitledBorder("Function"));
    exprPanel.add(new JLabel(expr.toString()));

    JPanel axisPanel = new JPanel();
    axisPanel.setBorder(new TitledBorder("Select axis constants"));
    axisPanel.setLayout(new BoxLayout(axisPanel, BoxLayout.Y_AXIS));
    JPanel xAxisPanel = new JPanel(new FlowLayout());
    xAxisPanel.add(new JLabel("X axis:"));
    xAxisPanel.add(xAxis);
    JPanel yAxisPanel = new JPanel(new FlowLayout());
    yAxisPanel.add(new JLabel("Y axis:"));
    yAxisPanel.add(yAxis);
    axisPanel.add(xAxisPanel);
    axisPanel.add(yAxisPanel);

    JPanel constantPanel = new JPanel(new BorderLayout());
    constantPanel.setBorder(new TitledBorder("Please define the following constants"));
    constantPanel.add(scrollPane, BorderLayout.CENTER);
    constantPanel.add(new ConstantHeader(), BorderLayout.NORTH);

    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    bottomPanel.add(ok);
    bottomPanel.add(cancel);

    //fill the axes components

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        xAxis.addItem(expr.getAllConstants().get(i));

        if (!is2D)
            yAxis.addItem(expr.getAllConstants().get(i));
    }

    if (!is2D) {
        yAxis.setSelectedIndex(1);
    }

    //fill the constants table

    for (int i = 0; i < expr.getAllConstants().size(); i++) {

        ConstantLine line = new ConstantLine(expr.getAllConstants().get(i), TypeDouble.getInstance());
        constantList.addConstant(line);

        if (!is2D) {
            if (line.getName().equals(xAxis.getSelectedItem().toString())
                    || line.getName().equals(yAxis.getSelectedItem().toString())) {

                line.doFuncEnables(false);
            } else {
                line.doFuncEnables(true);
            }
        }

    }

    //do enables

    if (is2D) {
        yAxis.setEnabled(false);
    }

    ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok");
    ok.getActionMap().put("ok", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            ok.doClick();
        }
    });

    cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            "cancel");
    cancel.getActionMap().put("cancel", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            cancel.doClick();
        }
    });

    //add action listeners

    xAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (is2D) {
                return;
            }

            String item = xAxis.getSelectedItem().toString();

            if (item.equals(yAxis.getSelectedItem().toString())) {

                int index = yAxis.getSelectedIndex();

                if (index != yAxis.getItemCount() - 1) {
                    yAxis.setSelectedIndex(++index);
                } else {
                    yAxis.setSelectedIndex(--index);
                }

            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    yAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            String item = yAxis.getSelectedItem().toString();

            if (item.equals(xAxis.getSelectedItem().toString())) {

                int index = xAxis.getSelectedIndex();

                if (index != xAxis.getItemCount() - 1) {
                    xAxis.setSelectedIndex(++index);
                } else {
                    xAxis.setSelectedIndex(--index);
                }
            }

            for (int i = 0; i < constantList.getNumConstants(); i++) {

                ConstantLine line = constantList.getConstantLine(i);

                if (line.getName().equals(xAxis.getSelectedItem().toString())
                        || line.getName().equals(yAxis.getSelectedItem().toString())) {

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {

                constantList.checkValid();

            } catch (PrismException e2) {
                JOptionPane.showMessageDialog(dialog,
                        "<html> One or more of the defined constants are invalid. <br><br> <font color=red>Error: </font>"
                                + e2.getMessage() + "</html>",
                        "Parse Error", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (is2D) {

                // it will always be a parametric graph in 2d case
                ParametricGraph pGraph = (ParametricGraph) graph;

                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());

                if (xAxisConstant == null) {
                    //should never happen
                    JOptionPane.showMessageDialog(dialog, "The selected axis is invalid.", "Error",
                            JOptionPane.ERROR_MESSAGE);
                    return;
                }

                double xStartValue = Double.parseDouble(xAxisConstant.getStartValue());
                double xEndValue = Double.parseDouble(xAxisConstant.getEndValue());
                double xStepValue = Double.parseDouble(xAxisConstant.getStepValue());

                int seriesCount = 0;

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getName().equals(xAxis.getSelectedItem().toString())) {
                        seriesCount++;
                    } else {

                        seriesCount += line.getTotalNumOfValues();

                    }
                }

                // if there will be too many series to be plotted, ask the user if they are sure they know what they are doing
                if (seriesCount > 10) {

                    int res = JOptionPane.showConfirmDialog(dialog,
                            "This configuration will create " + seriesCount + " series. Continue?", "Confirm",
                            JOptionPane.YES_NO_OPTION);

                    if (res == JOptionPane.NO_OPTION) {
                        return;
                    }

                }

                Values singleValuesGlobal = new Values();

                //add the single values to a global values list

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                // we just have one variable so we can plot directly
                if (constantList.getNumConstants() == 1
                        || singleValuesGlobal.getNumValues() == constantList.getNumConstants() - 1) {

                    SeriesKey key = pGraph.addSeries(seriesName);

                    pGraph.hideShape(key);
                    pGraph.getXAxisSettings().setHeading(xAxis.getSelectedItem().toString());
                    pGraph.getYAxisSettings().setHeading("function");

                    for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                        double ans = -1;

                        Values vals = new Values();
                        vals.addValue(xAxis.getSelectedItem().toString(), x);

                        for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                            try {
                                vals.addValue(singleValuesGlobal.getName(ii),
                                        singleValuesGlobal.getDoubleValue(ii));
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                        }

                        try {
                            ans = expr.evaluateDouble(vals);
                        } catch (PrismLangException e1) {
                            e1.printStackTrace();
                        }

                        pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));

                    }

                    if (isNewGraph) {
                        addGraph(pGraph);
                    }

                    dialog.dispose();
                    return;
                }

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line == xAxisConstant || singleValuesGlobal.contains(line.getName())) {
                        continue;
                    }

                    double lineStart = Double.parseDouble(line.getStartValue());
                    double lineEnd = Double.parseDouble(line.getEndValue());
                    double lineStep = Double.parseDouble(line.getStepValue());

                    for (double j = lineStart; j < lineEnd; j += lineStep) {

                        SeriesKey key = pGraph.addSeries(seriesName);
                        pGraph.hideShape(key);

                        for (double x = xStartValue; x <= xEndValue; x += xStepValue) {

                            double ans = -1;

                            Values vals = new Values();
                            vals.addValue(xAxis.getSelectedItem().toString(), x);
                            vals.addValue(line.getName(), j);

                            for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) {

                                try {
                                    vals.addValue(singleValuesGlobal.getName(ii),
                                            singleValuesGlobal.getDoubleValue(ii));
                                } catch (PrismLangException e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }

                            }

                            for (int ii = 0; ii < constantList.getNumConstants(); ii++) {

                                if (constantList.getConstantLine(ii) == xAxisConstant
                                        || singleValuesGlobal
                                                .contains(constantList.getConstantLine(ii).getName())
                                        || constantList.getConstantLine(ii) == line) {

                                    continue;
                                }

                                ConstantLine temp = constantList.getConstantLine(ii);
                                double val = Double.parseDouble(temp.getStartValue());

                                vals.addValue(temp.getName(), val);
                            }

                            try {
                                ans = expr.evaluateDouble(vals);
                            } catch (PrismLangException e1) {
                                e1.printStackTrace();
                            }

                            pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans));
                        }
                    }

                }

                if (isNewGraph) {
                    addGraph(graph);
                }
            } else {

                // this will always be a parametric graph for the 3d case
                ParametricGraph3D pGraph = (ParametricGraph3D) graph;

                //add the graph to the gui
                addGraph(pGraph);

                //Get the constants we want to put on the x and y axis
                ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString());
                ConstantLine yAxisConstant = constantList.getConstantLine(yAxis.getSelectedItem().toString());

                //add the single values to a global values list

                Values singleValuesGlobal = new Values();

                for (int i = 0; i < constantList.getNumConstants(); i++) {

                    ConstantLine line = constantList.getConstantLine(i);

                    if (line.getTotalNumOfValues() == 1) {

                        double singleValue = Double.parseDouble(line.getSingleValue());
                        singleValuesGlobal.addValue(line.getName(), singleValue);
                    }
                }

                pGraph.setGlobalValues(singleValuesGlobal);
                pGraph.setAxisConstants(xAxis.getSelectedItem().toString(), yAxis.getSelectedItem().toString());
                pGraph.setBounds(xAxisConstant.getStartValue(), xAxisConstant.getEndValue(),
                        yAxisConstant.getStartValue(), yAxisConstant.getEndValue());

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        //plot the graph
                        pGraph.plot(expr.toString(), xAxis.getSelectedItem().toString(), "Function",
                                yAxis.getSelectedItem().toString());

                        //calculate the sampling rates from the step sizes as given by the user

                        int xSamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));
                        int ySamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue())
                                - Double.parseDouble(xAxisConstant.getStartValue()))
                                / Double.parseDouble(xAxisConstant.getStepValue()));

                        pGraph.setSamplingRates(xSamples, ySamples);
                    }
                });

            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            dialog.dispose();
        }
    });

    //add everything to the dialog show the dialog

    dialog.add(exprPanel);
    dialog.add(axisPanel);
    dialog.add(constantPanel);
    dialog.add(bottomPanel);
    dialog.setVisible(true);

}

From source file:com.osparking.osparking.Settings_System.java

private void changeTCP_VS_COM(DeviceType devType, int gateNo) {
    String devPrefix = devType.name() + gateNo;
    JComboBox comboBx = ((JComboBox) getComponentByName(devPrefix + "_connTypeCBox"));
    String item = (String) comboBx.getSelectedItem();
    Component comIDcbBox = getComponentByName(devPrefix + "_comID_CBox");
    Component comPortLabel = getComponentByName(devPrefix + "_comLabel");
    Component ipAddrCompo = getComponentByName(devPrefix + "_IP_TextField");
    Component portCompo = getComponentByName(devPrefix + "_Port_TextField");

    JPanel devicePanel = (JPanel) getComponentByName(devPrefix + "Panel");

    if (item.equals(ConnectionType.TCP_IP.getLabel())) {
        devicePanel.remove(comIDcbBox);/*from  w  w  w  .j a  va  2 s . com*/
        devicePanel.remove(comPortLabel);
        devicePanel.add(ipAddrCompo);
        devicePanel.add(portCompo);
    } else if (item.equals(ConnectionType.RS_232.getLabel())) {
        devicePanel.remove(portCompo);
        devicePanel.remove(ipAddrCompo);
        devicePanel.add(comPortLabel);
        devicePanel.add(comIDcbBox);

        String IDstr = deviceComID[devType.ordinal()][gateNo];
        if (IDstr.length() == 0) {
            ((JComboBox) comIDcbBox).setSelectedIndex(0);
        } else {
            ((JComboBox) comIDcbBox).setSelectedIndex(Integer.parseInt(IDstr) - 1);
        }
    }
    devicePanel.repaint();
}

From source file:com.mirth.connect.client.ui.Frame.java

/**
 * Get the strings which identifies the encoding selected by the user.
 * /*w  w w. ja  va2  s .c  o  m*/
 * This method is called from each connector.
 */
public String getSelectedEncodingForConnector(javax.swing.JComboBox charsetEncodingCombobox) {
    try {
        return ((CharsetEncodingInformation) charsetEncodingCombobox.getSelectedItem()).getCanonicalName();
    } catch (Throwable t) {
        alertInformation(this, "Error " + t);
        return UIConstants.DEFAULT_ENCODING_OPTION;
    }
}

From source file:com.osparking.osparking.Settings_System.java

private boolean someCOMportIDsame(int gateNo, DeviceType deviceType, ArrayList<COM_ID_Usage> com_ID_usageList) {
    JComboBox cBox = (JComboBox) componentMap.get(deviceType.toString() + gateNo + "_connTypeCBox");
    String connType = (String) cBox.getSelectedItem();
    if (!connType.equals(ConnectionType.RS_232.getLabel())) {
        return false;
    }//from   w  w w.j av a  2s . c o m

    cBox = (JComboBox) componentMap.get(deviceType.toString() + gateNo + "_comID_CBox");
    String currCOM_ID = (String) cBox.getSelectedItem();

    for (COM_ID_Usage usage : com_ID_usageList) {
        if (usage.COM_ID.equals(currCOM_ID)) {
            String msg = OVERLAPPED_PORT_DIALOG_1.getContent() + System.lineSeparator()
                    + OVERLAPPED_PORT_DIALOG_2.getContent() + System.lineSeparator()
                    + OVERLAPPED_PORT_DIALOG_3.getContent() + System.lineSeparator() + System.lineSeparator()
                    + DEVICE_LABEL.getContent() + " 1 : " + GATE_LABEL.getContent() + " " + usage.gateNo + ", "
                    + usage.deviceType + System.lineSeparator() + DEVICE_LABEL.getContent() + " 2 : "
                    + GATE_LABEL.getContent() + " " + gateNo + ", " + deviceType + System.lineSeparator()
                    + OVERLAPPED_PORT_DIALOG_4.getContent() + "COM" + usage.COM_ID + System.lineSeparator();
            int response = JOptionPane.showConfirmDialog(this, msg, OVERLAPPED_PORT_TITLE.getContent(),
                    YES_NO_OPTION, ERROR_MESSAGE);

            if (response == YES_OPTION) {
                return false;
            } else {
                return true;
            }
        }
    }
    com_ID_usageList.add(new COM_ID_Usage(gateNo, deviceType, currCOM_ID));

    return false;
}

From source file:com.osparking.osparking.Settings_System.java

private void EBoardSettingsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EBoardSettingsButtonActionPerformed
    int tabIndex = GatesTabbedPane.getSelectedIndex();
    JComboBox typeCBox = (JComboBox) componentMap.get("E_Board" + (tabIndex + 1) + "_TypeCBox");
    E_BoardType eBoardType = (E_BoardType) typeCBox.getSelectedItem();

    eBoardDialog = new JDialog(this, eBoardType + " " + E_BOARD_SETTINGS_FRAME_TITLE.getContent(), true);
    if (eBoardType == E_BoardType.Simulator) {
        getE_BoardDialog().getContentPane().add((new Settings_EBoard(mainForm, this)).getContentPane());
        getE_BoardDialog().setResizable(false);
    } else if (eBoardType == E_BoardType.LEDnotice) {
        Settings_LEDnotice ledNotice = new Settings_LEDnotice(mainForm, this, tabIndex + 1);
        getE_BoardDialog().getContentPane().add(ledNotice.getContentPane());
        getE_BoardDialog().setPreferredSize(ledNotice.getPreferredSize());
        getE_BoardDialog().setResizable(false);
    }/*from   w w w. j av a2  s. c o m*/
    getE_BoardDialog().pack();

    /**
     * Place E-board settings frame around invoking button and inside monitor.
     */
    Point buttonPoint = EBoardSettingsButton.getLocationOnScreen();
    int idealX = buttonPoint.x + EBoardSettingsButton.getSize().width + 10;
    int moniWidth = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
    int maxX = moniWidth - (int) getE_BoardDialog().getSize().getWidth();
    int finalX = idealX;
    int finalY = buttonPoint.y - (int) getE_BoardDialog().getSize().getHeight() / 2;

    if (idealX > maxX) {
        finalX = maxX;
        finalY = buttonPoint.y - (int) getE_BoardDialog().getSize().getHeight() - 10;
    }
    getE_BoardDialog().setLocation(finalX, finalY);

    getE_BoardDialog().setVisible(true);
}