Example usage for javax.swing JComboBox getSelectedIndex

List of usage examples for javax.swing JComboBox getSelectedIndex

Introduction

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

Prototype

@Transient
public int getSelectedIndex() 

Source Link

Document

Returns the first item in the list that matches the given item.

Usage

From source file:search2go.UIFrame.java

private void blast(JTextField queries, JFormattedTextField eValue, JTextField db, JTextField threads,
        JComboBox type, JTextArea output, boolean fullProcess) throws IOException {
    Path queriesPath = new Path(queries.getText());
    Path dbPath = new Path(db.getText());
    String threadNo = threads.getText();
    String blastType = type.getSelectedItem().toString().replace("BLAST", "");

    currentProj.setQueries(queriesPath.toEscString());
    currentProj.setPathToDB(dbPath.toEscString());
    currentProj.setThreadNo(Integer.parseInt(threadNo));
    currentProj.setBlastTypeIndex(type.getSelectedIndex());
    currentProj.setEthreshold(Integer.parseInt(txtBlastE.getText()));

    blastSequence = new ProcessSequence(currentProj, new ProcessSequenceEnd() {
        @Override//from   w  ww.  j av a  2s.c  om
        public void run() {
            output.append("BLAST Done! Please proceed to Mapping\n");
            prgBlast.setIndeterminate(false);
            currentProj.setAvailable(true);
            currentProj.setStage(1);
            if (fullProcess) {
                map(txtBitScoreFP, eValue, cbxDBIDFP, txtFullOutput, true);
            }
            blastButton.restore();
        }
    });

    Path outLoc = new Path(currentProj.getPath());
    outLoc.append("BLAST_Results.xml");
    Process blastProcess = new Process(output, outLoc);

    blastProcess.setBaseCommand("");
    blastProcess.setScriptCommand(type.getSelectedItem().toString().toLowerCase());
    blastProcess.addParameter("query", queriesPath.toEscString());
    blastProcess.addParameter("db", dbPath.toEscString());
    blastProcess.addParameter("num_threads", threadNo);
    if (!eValue.getText().equals(""))
        blastProcess.addParameter("evalue", eValue.getText());
    blastProcess.addParameter("outfmt", Integer.toString(5));

    blastSequence.addProcess(blastProcess);

    try {
        blastSequence.start();
        blastButton.setStopTargets(blastSequence);
        if (!fullProcess)
            blastButton.activate();
        currentProj.setStage(0);
        output.setText("Searching...\n");
        prgBlast.setIndeterminate(true);
    } catch (IOException ex) {
        javax.swing.JOptionPane.showMessageDialog(this, "Error running BLAST search.");
    }
}

From source file:AppearanceExplorer.java

IntChooser(String name, String[] initChoiceNames, int[] initChoiceValues, int initValue) {
    if ((initChoiceValues != null) && (initChoiceNames.length != initChoiceValues.length)) {
        throw new IllegalArgumentException("Name and Value arrays must have the same length");
    }/* w ww .j ava  2 s .c  o  m*/
    choiceNames = new String[initChoiceNames.length];
    choiceValues = new int[initChoiceNames.length];
    System.arraycopy(initChoiceNames, 0, choiceNames, 0, choiceNames.length);
    if (initChoiceValues != null) {
        System.arraycopy(initChoiceValues, 0, choiceValues, 0, choiceNames.length);
    } else {
        for (int i = 0; i < initChoiceNames.length; i++) {
            choiceValues[i] = i;
        }
    }

    // Create the combo box, select the init value
    combo = new JComboBox(choiceNames);
    combo.setSelectedIndex(current);
    combo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JComboBox cb = (JComboBox) e.getSource();
            int index = cb.getSelectedIndex();
            setValueIndex(index);
        }
    });

    // set the initial value
    current = 0;
    setValue(initValue);

    // layout to align left
    setLayout(new BorderLayout());
    Box box = new Box(BoxLayout.X_AXIS);
    add(box, BorderLayout.WEST);

    box.add(new JLabel(name));
    box.add(combo);
}

From source file:br.com.bgslibrary.gui.MainFrame.java

private void changeParam(String pname, javax.swing.JComboBox comboBox, String filePath) {
    if (comboBox.getSelectedIndex() > 0) {
        String value = comboBox.getSelectedItem().toString();
        changeParam(pname, value, filePath);
    } else/*  w  w  w  . j  av  a  2 s  .c o m*/
        changeParam(pname, "\"\"", filePath);
}

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

private void saveSubTree(@SuppressWarnings("rawtypes") final Enumeration children,
        final List<Parameter> parameterList, final List<SubmodelParameter> submodelParameterList,
        final Set<ParameterInfo> invalids) throws IOException {

    final ObjectFactory factory = new ObjectFactory();
    while (children.hasMoreElements()) {
        final DefaultMutableTreeNode node = (DefaultMutableTreeNode) children.nextElement();

        @SuppressWarnings("unchecked")
        final Pair<ParameterInfo, JComponent> userData = (Pair<ParameterInfo, JComponent>) node.getUserObject();
        final ParameterInfo parameterInfo = userData.getFirst();
        final JComponent valueContainer = userData.getSecond();

        Parameter parameter = null;
        SubmodelParameter submodelParameter = null;
        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;
                }/* ww  w . java 2s  .c o m*/
            }
        }

        if (parameterInfo instanceof SubmodelInfo) {
            submodelParameter = factory.createSubmodelParameter();
            submodelParameter.setName(parameterInfo.getName());
        } else {
            parameter = factory.createParameter();
            parameter.setName(parameterInfo.getName());
        }

        if (parameterInfo.isBoolean()) {
            final JCheckBox checkBox = (JCheckBox) valueContainer;
            parameter.getContent().add(String.valueOf(checkBox.isSelected()));
        } else if (parameterInfo.isEnum()) {
            final JComboBox comboBox = (JComboBox) valueContainer;
            parameter.getContent().add(String.valueOf(comboBox.getSelectedItem()));
        } else if (parameterInfo instanceof MasonChooserParameterInfo) {
            final JComboBox comboBox = (JComboBox) valueContainer;
            parameter.getContent().add(String.valueOf(comboBox.getSelectedIndex()));
        } else if (parameterInfo instanceof SubmodelInfo) {
            final JComboBox comboBox = (JComboBox) ((JPanel) valueContainer).getComponent(0);
            final ClassElement selectedElement = (ClassElement) comboBox.getSelectedItem();

            if (selectedElement.clazz == null)
                throw new IOException("No type is selected for parameter "
                        + parameterInfo.getName().replaceAll("([A-Z])", " $1") + ".");

            submodelParameter.setType(selectedElement.clazz.getName());
            saveSubTree(node.children(), submodelParameter.getParameterList(),
                    submodelParameter.getSubmodelParameterList(), invalids);
        } else if (parameterInfo.isFile()) {
            final JTextField textField = (JTextField) valueContainer.getComponent(0);
            parameter.getContent().add(textField.getToolTipText());
        } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
            final JTextField textField = (JTextField) valueContainer.getComponent(0);
            parameter.getContent().add(textField.getText().trim());
        } else {
            final JTextField textField = (JTextField) valueContainer;
            String text = String.valueOf(ParameterInfo.getValue(textField.getText(), parameterInfo.getType()));
            if ("String".equals(parameterInfo.getType()) && parameterInfo.getValue() == null)
                text = textField.getText().trim();
            parameter.getContent().add(text);
        }

        if (parameter != null)
            parameterList.add(parameter);
        else if (submodelParameter != null)
            submodelParameterList.add(submodelParameter);
    }
}

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

/** {@inheritDoc} 
 *//*from   w w w  .j a v a 2  s .  co  m*/
@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.osparking.osparking.Settings_System.java

private void setButtonEnabled_If_DeviceTypeChanged(int gate, DeviceType devType) {
    JComboBox comboBx = ((JComboBox) getComponentByName(devType.toString() + gate + "_TypeCBox"));
    int selectedType = comboBx.getSelectedIndex();

    if (selectedType == deviceType[devType.ordinal()][gate]) {
        changedControls.remove(comboBx);
    } else {/*from  ww w .j a  va  2  s . co m*/
        changedControls.add(comboBx);
    }
}

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

private void setButtonEnabled_If_ConnTypeChanged(int gate, DeviceType devType) {
    JComboBox comboBx = ((JComboBox) getComponentByName(devType.toString() + gate + "_connTypeCBox"));
    int connType = comboBx.getSelectedIndex();

    if (connType == connectionType[devType.ordinal()][gate]) {
        changedControls.remove(comboBx);
    } else {//from www.  j a v  a2 s . c  o m
        changedControls.add(comboBx);
    }
}

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

private int saveGateDevices(boolean[] majorChange) {
    Connection conn = null;/*from   ww  w.ja  va 2s.c  o  m*/
    PreparedStatement updateSettings = null;
    int result = 0;
    int updateRowCount = 0;

    //<editor-fold desc="-- Create update statement">
    StringBuffer sb = new StringBuffer("Update gatedevices SET ");

    sb.append("  gatename = ? ");
    sb.append("  , cameraType = ?");
    sb.append("  , cameraIP = ? ");
    sb.append("  , cameraPort = ?");
    sb.append("  , e_boardType = ? ");
    sb.append("  , e_boardConnType = ? ");
    sb.append("  , e_boardCOM_ID = ? ");
    sb.append("  , e_boardIP = ? ");
    sb.append("  , e_boardPort = ? ");
    sb.append("  , gatebarType = ? ");
    sb.append("  , gatebarConnType = ? ");
    sb.append("  , gatebarCOM_ID = ? ");
    sb.append("  , gatebarIP = ? ");
    sb.append("  , gatebarPort = ? ");
    sb.append("WHERE GateID = ?");
    //</editor-fold>

    for (int gateID = 1; gateID <= gateCount; gateID++) {
        try {
            conn = JDBCMySQL.getConnection();
            updateSettings = conn.prepareStatement(sb.toString());

            int pIndex = 1;
            JComboBox cBox;

            //<editor-fold defaultstate="collapsed" desc="--Provide actual values to the UPDATE">
            updateSettings.setString(pIndex++,
                    ((JTextField) componentMap.get("TextFieldGateName" + gateID)).getText().trim());

            for (DeviceType type : DeviceType.values()) {
                cBox = (JComboBox) componentMap.get(type.toString() + gateID + "_TypeCBox");

                int newSubType = cBox.getSelectedIndex();
                Object newSubTypeObj = cBox.getSelectedItem();

                if (newSubType != deviceType[type.ordinal()][gateID]) {
                    majorChange[0] = true;
                }

                updateSettings.setInt(pIndex++, cBox == null ? 0 : newSubType);
                if (type != Camera) {
                    cBox = (JComboBox) componentMap.get(type.toString() + gateID + "_connTypeCBox");

                    updateSettings.setInt(pIndex++, cBox == null ? 0 : cBox.getSelectedIndex());

                    cBox = (JComboBox) componentMap.get(type.toString() + gateID + "_comID_CBox");
                    updateSettings.setString(pIndex++, cBox == null ? "" : (String) cBox.getSelectedItem());
                }
                String ipAddrStr = ((JTextField) componentMap.get(type.toString() + gateID + "_IP_TextField"))
                        .getText().trim();
                updateSettings.setString(pIndex++, ipAddrStr);

                giveWarningForRealDevice(gateID, type, newSubTypeObj, ipAddrStr);

                String portStr = "";
                if (newSubType == SIMULATOR) {
                    // Simulator port number is determined programmatically. So, leave the original value alone.
                    portStr = devicePort[type.ordinal()][gateID];
                } else {
                    portStr = ((JTextField) componentMap.get(type.toString() + gateID + "_Port_TextField"))
                            .getText().trim();
                }
                updateSettings.setString(pIndex++, portStr);
            }
            updateSettings.setInt(pIndex++, gateID);
            // </editor-fold>

            result = updateSettings.executeUpdate();

        } catch (SQLException se) {
            Globals.logParkingException(Level.SEVERE, se, "(Save gate & device settings)");
        } finally {
            // <editor-fold defaultstate="collapsed" desc="--Return resources and display the save result">
            closeDBstuff(conn, updateSettings, null, "(Save gate & device settings)");

            if (result == 1) {
                updateRowCount++;
            }
            // </editor-fold>
        }
    }
    return updateRowCount;
}

From source file:com.net2plan.gui.utils.viewEditTopolTables.specificTables.AdvancedJTable_demand.java

private List<JComponent> getExtraOptions(final int row, final Object itemId) {
    List<JComponent> options = new LinkedList<JComponent>();
    final int numRows = model.getRowCount();
    final NetPlan netPlan = callback.getDesign();
    final List<Demand> tableVisibleDemands = getVisibleElementsInTable();

    JMenuItem offeredTrafficToAll = new JMenuItem("Set offered traffic to all");
    offeredTrafficToAll.addActionListener(new ActionListener() {
        @Override//  w  w w. j av  a2  s.  c  om
        public void actionPerformed(ActionEvent e) {
            double h_d;

            while (true) {
                String str = JOptionPane.showInputDialog(null, "Offered traffic volume",
                        "Set traffic value to all demands in the table", JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    h_d = Double.parseDouble(str);
                    if (h_d < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog("Please, introduce a non-negative number",
                            "Error setting offered traffic");
                }
            }

            NetPlan netPlan = callback.getDesign();

            try {
                for (Demand d : tableVisibleDemands)
                    d.setOfferedTraffic(h_d);
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(),
                        "Unable to set offered traffic to all demands in the table");
            }
        }
    });
    options.add(offeredTrafficToAll);

    JMenuItem scaleOfferedTrafficToAll = new JMenuItem("Scale offered traffic all demands in the table");
    scaleOfferedTrafficToAll.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            double scalingFactor;

            while (true) {
                String str = JOptionPane.showInputDialog(null,
                        "Scaling factor to multiply to all offered traffics", "Scale offered traffic",
                        JOptionPane.QUESTION_MESSAGE);
                if (str == null)
                    return;

                try {
                    scalingFactor = Double.parseDouble(str);
                    if (scalingFactor < 0)
                        throw new RuntimeException();

                    break;
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog("Please, introduce a non-negative number",
                            "Error setting offered traffic");
                }
            }

            try {
                for (Demand d : tableVisibleDemands)
                    d.setOfferedTraffic(d.getOfferedTraffic() * scalingFactor);
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale demand offered traffics");
            }
        }
    });
    options.add(scaleOfferedTrafficToAll);

    JMenuItem setServiceTypes = new JMenuItem(
            "Set traversed resource types (to one or all demands in the table)");
    setServiceTypes.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            NetPlan netPlan = callback.getDesign();
            try {
                Demand d = netPlan.getDemandFromId((Long) itemId);
                String[] headers = StringUtils.arrayOf("Order", "Type");
                Object[][] data = { null, null };
                DefaultTableModel model = new ClassAwareTableModelImpl(data, headers);
                AdvancedJTable table = new AdvancedJTable(model);
                JButton addRow = new JButton("Add new traversed resource type");
                addRow.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Object[] newRow = { table.getRowCount(), "" };
                        ((DefaultTableModel) table.getModel()).addRow(newRow);
                    }
                });
                JButton removeRow = new JButton("Remove selected");
                removeRow.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        ((DefaultTableModel) table.getModel()).removeRow(table.getSelectedRow());
                        for (int t = 0; t < table.getRowCount(); t++)
                            table.getModel().setValueAt(t, t, 0);
                    }
                });
                JButton removeAllRows = new JButton("Remove all");
                removeAllRows.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        while (table.getRowCount() > 0)
                            ((DefaultTableModel) table.getModel()).removeRow(0);
                    }
                });
                List<String> oldTraversedResourceTypes = d.getServiceChainSequenceOfTraversedResourceTypes();
                Object[][] newData = new Object[oldTraversedResourceTypes.size()][headers.length];
                for (int i = 0; i < oldTraversedResourceTypes.size(); i++) {
                    newData[i][0] = i;
                    newData[i][1] = oldTraversedResourceTypes.get(i);
                }
                ((DefaultTableModel) table.getModel()).setDataVector(newData, headers);
                JPanel pane = new JPanel();
                JPanel pane2 = new JPanel();
                pane.setLayout(new BorderLayout());
                pane2.setLayout(new BorderLayout());
                pane.add(new JScrollPane(table), BorderLayout.CENTER);
                pane2.add(addRow, BorderLayout.WEST);
                pane2.add(removeRow, BorderLayout.EAST);
                pane2.add(removeAllRows, BorderLayout.SOUTH);
                pane.add(pane2, BorderLayout.SOUTH);
                final String[] optionsArray = new String[] { "Set to selected demand", "Set to all demands",
                        "Cancel" };
                int result = JOptionPane.showOptionDialog(null, pane, "Set traversed resource types",
                        JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, optionsArray,
                        optionsArray[0]);
                if ((result != 0) && (result != 1))
                    return;
                final boolean setToAllDemands = (result == 1);
                List<String> newTraversedResourcesTypes = new LinkedList<>();
                for (int j = 0; j < table.getRowCount(); j++) {
                    String travResourceType = table.getModel().getValueAt(j, 1).toString();
                    newTraversedResourcesTypes.add(travResourceType);
                }
                if (setToAllDemands) {
                    for (Demand dd : tableVisibleDemands)
                        if (!dd.getRoutes().isEmpty())
                            throw new Net2PlanException(
                                    "It is not possible to set the resource types traversed to demands with routes");
                    for (Demand dd : tableVisibleDemands)
                        dd.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes);
                } else {
                    if (!d.getRoutes().isEmpty())
                        throw new Net2PlanException(
                                "It is not possible to set the resource types traversed to demands with routes");
                    d.setServiceChainSequenceOfTraversedResourceTypes(newTraversedResourcesTypes);
                }
                callback.getVisualizationState().resetPickedState();
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            } catch (Throwable ex) {
                ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set traversed resource types");
            }
        }

    });
    options.add(setServiceTypes);

    if (itemId != null && netPlan.isMultilayer()) {
        final long demandId = (long) itemId;
        if (netPlan.getDemandFromId(demandId).isCoupled()) {
            JMenuItem decoupleDemandItem = new JMenuItem("Decouple demand");
            decoupleDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    netPlan.getDemandFromId(demandId).decouple();
                    model.setValueAt("", row, 3);
                    callback.getVisualizationState().resetPickedState();
                    callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.DEMAND));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                }
            });

            options.add(decoupleDemandItem);
        } else {
            JMenuItem createUpperLayerLinkFromDemandItem = new JMenuItem("Create upper layer link from demand");
            createUpperLayerLinkFromDemandItem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                    final JComboBox layerSelector = new WiderJComboBox();
                    for (long layerId : layerIds) {
                        if (layerId == netPlan.getNetworkLayerDefault().getId())
                            continue;

                        final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                        String layerLabel = "Layer " + layerId;
                        if (!layerName.isEmpty())
                            layerLabel += " (" + layerName + ")";

                        layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                    }

                    layerSelector.setSelectedIndex(0);

                    JPanel pane = new JPanel();
                    pane.add(new JLabel("Select layer: "));
                    pane.add(layerSelector);

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the upper layer to create the link",
                                JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                    .getObject();
                            netPlan.getDemandFromId(demandId)
                                    .coupleToNewLinkCreated(netPlan.getNetworkLayerFromId(layerId));
                            callback.getVisualizationState()
                                    .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                            callback.updateVisualizationAfterChanges(
                                    Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error creating upper layer link from demand");
                        }
                    }
                }
            });

            options.add(createUpperLayerLinkFromDemandItem);

            JMenuItem coupleDemandToLink = new JMenuItem("Couple demand to upper layer link");
            coupleDemandToLink.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                    final JComboBox layerSelector = new WiderJComboBox();
                    final JComboBox linkSelector = new WiderJComboBox();
                    for (long layerId : layerIds) {
                        if (layerId == netPlan.getNetworkLayerDefault().getId())
                            continue;

                        final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                        String layerLabel = "Layer " + layerId;
                        if (!layerName.isEmpty())
                            layerLabel += " (" + layerName + ")";

                        layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                    }

                    layerSelector.addItemListener(new ItemListener() {
                        @Override
                        public void itemStateChanged(ItemEvent e) {
                            if (layerSelector.getSelectedIndex() >= 0) {
                                long selectedLayerId = (Long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer selectedLayer = netPlan.getNetworkLayerFromId(selectedLayerId);

                                linkSelector.removeAllItems();
                                Collection<Link> links_thisLayer = netPlan.getLinks(selectedLayer);
                                for (Link link : links_thisLayer) {
                                    if (link.isCoupled())
                                        continue;

                                    String originNodeName = link.getOriginNode().getName();
                                    String destinationNodeName = link.getDestinationNode().getName();

                                    linkSelector.addItem(StringLabeller.unmodifiableOf(link.getId(),
                                            "e" + link.getIndex() + " [n" + link.getOriginNode().getIndex()
                                                    + " (" + originNodeName + ") -> n"
                                                    + link.getDestinationNode().getIndex() + " ("
                                                    + destinationNodeName + ")]"));
                                }
                            }

                            if (linkSelector.getItemCount() == 0) {
                                linkSelector.setEnabled(false);
                            } else {
                                linkSelector.setSelectedIndex(0);
                                linkSelector.setEnabled(true);
                            }
                        }
                    });

                    layerSelector.setSelectedIndex(-1);
                    layerSelector.setSelectedIndex(0);

                    JPanel pane = new JPanel(new MigLayout("", "[][grow]", "[][]"));
                    pane.add(new JLabel("Select layer: "));
                    pane.add(layerSelector, "growx, wrap");
                    pane.add(new JLabel("Select link: "));
                    pane.add(linkSelector, "growx, wrap");

                    while (true) {
                        int result = JOptionPane.showConfirmDialog(null, pane,
                                "Please select the upper layer link", JOptionPane.OK_CANCEL_OPTION,
                                JOptionPane.QUESTION_MESSAGE);
                        if (result != JOptionPane.OK_OPTION)
                            return;

                        try {
                            long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                    .getObject();
                            long linkId;
                            try {
                                linkId = (long) ((StringLabeller) linkSelector.getSelectedItem()).getObject();
                            } catch (Throwable ex) {
                                throw new RuntimeException("No link was selected");
                            }

                            netPlan.getDemandFromId(demandId)
                                    .coupleToUpperLayerLink(netPlan.getLinkFromId(linkId));
                            callback.getVisualizationState().resetPickedState();
                            callback.updateVisualizationAfterChanges(
                                    Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                            callback.getUndoRedoNavigationManager().addNetPlanChange();
                            break;
                        } catch (Throwable ex) {
                            ErrorHandling.showErrorDialog(ex.getMessage(),
                                    "Error coupling upper layer link to demand");
                        }
                    }
                }
            });

            options.add(coupleDemandToLink);
        }

        if (numRows > 1) {
            JMenuItem decoupleAllDemandsItem = null;
            JMenuItem createUpperLayerLinksFromDemandsItem = null;

            final Set<Demand> coupledDemands = tableVisibleDemands.stream().filter(d -> d.isCoupled())
                    .collect(Collectors.toSet());
            if (!coupledDemands.isEmpty()) {
                decoupleAllDemandsItem = new JMenuItem("Decouple all demands");
                decoupleAllDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (Demand d : new LinkedHashSet<Demand>(coupledDemands))
                            d.decouple();
                        int numRows = model.getRowCount();
                        for (int i = 0; i < numRows; i++)
                            model.setValueAt("", i, 3);
                        callback.getVisualizationState().resetPickedState();
                        callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.DEMAND));
                        callback.getUndoRedoNavigationManager().addNetPlanChange();
                    }
                });
            }

            if (coupledDemands.size() < tableVisibleDemands.size()) {
                createUpperLayerLinksFromDemandsItem = new JMenuItem(
                        "Create upper layer links from uncoupled demands");
                createUpperLayerLinksFromDemandsItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                        final JComboBox layerSelector = new WiderJComboBox();
                        for (long layerId : layerIds) {
                            if (layerId == netPlan.getNetworkLayerDefault().getId())
                                continue;

                            final String layerName = netPlan.getNetworkLayerFromId(layerId).getName();
                            String layerLabel = "Layer " + layerId;
                            if (!layerName.isEmpty())
                                layerLabel += " (" + layerName + ")";

                            layerSelector.addItem(StringLabeller.of(layerId, layerLabel));
                        }

                        layerSelector.setSelectedIndex(0);

                        JPanel pane = new JPanel();
                        pane.add(new JLabel("Select layer: "));
                        pane.add(layerSelector);

                        while (true) {
                            int result = JOptionPane.showConfirmDialog(null, pane,
                                    "Please select the upper layer to create links",
                                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                            if (result != JOptionPane.OK_OPTION)
                                return;

                            try {
                                long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                NetworkLayer layer = netPlan.getNetworkLayerFromId(layerId);
                                for (Demand demand : tableVisibleDemands)
                                    if (!demand.isCoupled())
                                        demand.coupleToNewLinkCreated(layer);

                                callback.getVisualizationState()
                                        .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                                callback.updateVisualizationAfterChanges(
                                        Sets.newHashSet(NetworkElementType.DEMAND, NetworkElementType.LINK));
                                callback.getUndoRedoNavigationManager().addNetPlanChange();
                                break;
                            } catch (Throwable ex) {
                                ErrorHandling.showErrorDialog(ex.getMessage(),
                                        "Error creating upper layer links");
                            }
                        }
                    }
                });
            }

            if (!options.isEmpty()
                    && (decoupleAllDemandsItem != null || createUpperLayerLinksFromDemandsItem != null)) {
                options.add(new JPopupMenu.Separator());
                if (decoupleAllDemandsItem != null)
                    options.add(decoupleAllDemandsItem);
                if (createUpperLayerLinksFromDemandsItem != null)
                    options.add(createUpperLayerLinksFromDemandsItem);
            }

        }
    }

    return options;
}

From source file:com.marginallyclever.makelangelo.MainGUI.java

protected boolean ChooseImageConversionOptions(boolean isDXF) {
    final JDialog driver = new JDialog(mainframe, translator.get("ConversionOptions"), true);
    driver.setLayout(new GridBagLayout());

    final String[] choices = machineConfiguration.getKnownMachineNames();
    final JComboBox<String> machine_choice = new JComboBox<String>(choices);
    machine_choice.setSelectedIndex(machineConfiguration.getCurrentMachineIndex());

    final JSlider input_paper_margin = new JSlider(JSlider.HORIZONTAL, 0, 50,
            100 - (int) (machineConfiguration.paper_margin * 100));
    input_paper_margin.setMajorTickSpacing(10);
    input_paper_margin.setMinorTickSpacing(5);
    input_paper_margin.setPaintTicks(false);
    input_paper_margin.setPaintLabels(true);

    //final JCheckBox allow_metrics = new JCheckBox(String.valueOf("I want to add the distance drawn to the // total"));
    //allow_metrics.setSelected(allowMetrics);

    final JCheckBox reverse_h = new JCheckBox(translator.get("FlipForGlass"));
    reverse_h.setSelected(machineConfiguration.reverseForGlass);
    final JButton cancel = new JButton(translator.get("Cancel"));
    final JButton save = new JButton(translator.get("Start"));

    String[] filter_names = new String[image_converters.size()];
    Iterator<Filter> fit = image_converters.iterator();
    int i = 0;/*  ww  w . ja va 2s.  c  om*/
    while (fit.hasNext()) {
        Filter f = fit.next();
        filter_names[i++] = f.GetName();
    }

    final JComboBox<String> input_draw_style = new JComboBox<String>(filter_names);
    input_draw_style.setSelectedIndex(GetDrawStyle());

    GridBagConstraints c = new GridBagConstraints();
    //c.gridwidth=4;    c.gridx=0;  c.gridy=0;  driver.add(allow_metrics,c);

    int y = 0;
    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 0;
    c.gridy = y;
    driver.add(new JLabel(translator.get("MenuLoadMachineConfig")), c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 2;
    c.gridx = 1;
    c.gridy = y++;
    driver.add(machine_choice, c);

    if (!isDXF) {
        c.anchor = GridBagConstraints.EAST;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = y;
        driver.add(new JLabel(translator.get("ConversionStyle")), c);
        c.anchor = GridBagConstraints.WEST;
        c.gridwidth = 3;
        c.gridx = 1;
        c.gridy = y++;
        driver.add(input_draw_style, c);
    }

    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 0;
    c.gridy = y;
    driver.add(new JLabel(translator.get("PaperMargin")), c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 3;
    c.gridx = 1;
    c.gridy = y++;
    driver.add(input_paper_margin, c);

    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 1;
    c.gridx = 1;
    c.gridy = y++;
    driver.add(reverse_h, c);
    c.anchor = GridBagConstraints.EAST;
    c.gridwidth = 1;
    c.gridx = 2;
    c.gridy = y;
    driver.add(save, c);
    c.anchor = GridBagConstraints.WEST;
    c.gridwidth = 1;
    c.gridx = 3;
    c.gridy = y++;
    driver.add(cancel, c);

    startConvertingNow = false;

    ActionListener driveButtons = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Object subject = e.getSource();
            if (subject == save) {
                long new_uid = Long.parseLong(choices[machine_choice.getSelectedIndex()]);
                machineConfiguration.LoadConfig(new_uid);
                SetDrawStyle(input_draw_style.getSelectedIndex());
                machineConfiguration.paper_margin = (100 - input_paper_margin.getValue()) * 0.01;
                machineConfiguration.reverseForGlass = reverse_h.isSelected();
                machineConfiguration.SaveConfig();

                // if we aren't connected, don't show the new 
                if (connectionToRobot != null && !connectionToRobot.isRobotConfirmed()) {
                    // Force update of graphics layout.
                    previewPane.updateMachineConfig();
                    // update window title
                    mainframe.setTitle(
                            translator.get("TitlePrefix") + Long.toString(machineConfiguration.robot_uid)
                                    + translator.get("TitleNotConnected"));
                }
                startConvertingNow = true;
                driver.dispose();
            }
            if (subject == cancel) {
                driver.dispose();
            }
        }
    };

    save.addActionListener(driveButtons);
    cancel.addActionListener(driveButtons);
    driver.getRootPane().setDefaultButton(save);
    driver.pack();
    driver.setVisible(true);

    return startConvertingNow;
}