Example usage for javax.swing JComboBox addItemListener

List of usage examples for javax.swing JComboBox addItemListener

Introduction

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

Prototype

public void addItemListener(ItemListener aListener) 

Source Link

Document

Adds an ItemListener.

Usage

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/*from  w w w  .ja  va2s . 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.osparking.osparking.Settings_System.java

private void prepareComPortControls() {
    E_Board1_comLabel = new javax.swing.JLabel();
    E_Board2_comLabel = new javax.swing.JLabel();
    E_Board3_comLabel = new javax.swing.JLabel();
    E_Board4_comLabel = new javax.swing.JLabel();
    GateBar1_comLabel = new javax.swing.JLabel();
    GateBar2_comLabel = new javax.swing.JLabel();
    GateBar3_comLabel = new javax.swing.JLabel();
    GateBar4_comLabel = new javax.swing.JLabel();

    E_Board1_comLabel.setName("E_Board1_comLabel"); // E_Board1_comLabel
    E_Board2_comLabel.setName("E_Board2_comLabel");
    E_Board3_comLabel.setName("E_Board3_comLabel");
    E_Board4_comLabel.setName("E_Board4_comLabel");
    GateBar1_comLabel.setName("GateBar1_comLabel");
    GateBar2_comLabel.setName("GateBar2_comLabel");
    GateBar3_comLabel.setName("GateBar3_comLabel");
    GateBar4_comLabel.setName("GateBar4_comLabel");

    augmentComponentMap(E_Board1_comLabel, componentMap);
    augmentComponentMap(E_Board2_comLabel, componentMap);
    augmentComponentMap(E_Board3_comLabel, componentMap);
    augmentComponentMap(E_Board4_comLabel, componentMap);
    augmentComponentMap(GateBar1_comLabel, componentMap);
    augmentComponentMap(GateBar2_comLabel, componentMap);
    augmentComponentMap(GateBar3_comLabel, componentMap);
    augmentComponentMap(GateBar4_comLabel, componentMap);

    initComPortIDLabel(E_Board1_comLabel);
    initComPortIDLabel(E_Board2_comLabel);
    initComPortIDLabel(E_Board3_comLabel);
    initComPortIDLabel(E_Board4_comLabel);
    initComPortIDLabel(GateBar1_comLabel);
    initComPortIDLabel(GateBar2_comLabel);
    initComPortIDLabel(GateBar3_comLabel);
    initComPortIDLabel(GateBar4_comLabel);

    E_Board1_comID_CBox = new JComboBox();
    E_Board2_comID_CBox = new JComboBox();
    E_Board3_comID_CBox = new JComboBox();
    E_Board4_comID_CBox = new JComboBox();
    GateBar1_comID_CBox = new JComboBox();
    GateBar2_comID_CBox = new JComboBox();
    GateBar3_comID_CBox = new JComboBox();
    GateBar4_comID_CBox = new JComboBox();

    E_Board1_comID_CBox.setName("E_Board1_comID_CBox");
    E_Board2_comID_CBox.setName("E_Board2_comID_CBox");
    E_Board3_comID_CBox.setName("E_Board3_comID_CBox");
    E_Board4_comID_CBox.setName("E_Board4_comID_CBox");
    GateBar1_comID_CBox.setName("GateBar1_comID_CBox");
    GateBar2_comID_CBox.setName("GateBar2_comID_CBox");
    GateBar3_comID_CBox.setName("GateBar3_comID_CBox");
    GateBar4_comID_CBox.setName("GateBar4_comID_CBox");

    augmentComponentMap(E_Board1_comID_CBox, componentMap);
    augmentComponentMap(E_Board2_comID_CBox, componentMap);
    augmentComponentMap(E_Board3_comID_CBox, componentMap);
    augmentComponentMap(E_Board4_comID_CBox, componentMap);
    augmentComponentMap(GateBar1_comID_CBox, componentMap);
    augmentComponentMap(GateBar2_comID_CBox, componentMap);
    augmentComponentMap(GateBar3_comID_CBox, componentMap);
    augmentComponentMap(GateBar4_comID_CBox, componentMap);

    //<editor-fold desc="-- Initialize other properties of COM ID combobox">
    for (int gate = 1; gate <= gateCount; gate++) {
        for (final DeviceType devType : DeviceType.values()) {
            String name = devType.name() + gate + "_comID_CBox";
            final JComboBox comIDcBox = ((JComboBox) getComponentByName(name));

            if (comIDcBox != null) {
                comIDcBox.setFont(new java.awt.Font(font_Type, font_Style, font_Size));
                comIDcBox.setModel(new javax.swing.DefaultComboBoxModel(
                        new String[] { "1", "2", "3", "4", "5", "6", "7", "8" }));
                comIDcBox.setMinimumSize(new java.awt.Dimension(50, CBOX_HEIGHT));
                comIDcBox.setPreferredSize(new java.awt.Dimension(50, CBOX_HEIGHT));
                final int gateNo = gate;

                comIDcBox.addItemListener(new java.awt.event.ItemListener() {
                    public void itemStateChanged(java.awt.event.ItemEvent evt) {
                        if (evt.getStateChange() == ItemEvent.SELECTED) {
                            String COM_ID = (String) comIDcBox.getSelectedItem();
                            if (COM_ID.equals(deviceComID[devType.ordinal()][gateNo])) {
                                changedControls.remove(comIDcBox);
                            } else {
                                changedControls.add(comIDcBox);
                            }/*from   www  .  jav  a 2 s .  co  m*/
                        }
                    }
                });
            }
        }
    }
    //</editor-fold>
}

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

private List<JComponent> getExtraOptions(final int row, final Object itemId) {
    List<JComponent> options = new LinkedList<JComponent>();

    final List<Link> rowVisibleLinks = getVisibleElementsInTable();
    final NetPlan netPlan = callback.getDesign();

    if (itemId != null) {
        final long linkId = (long) itemId;

        JMenuItem lengthToEuclidean_thisLink = new JMenuItem("Set link length to node-pair Euclidean distance");
        lengthToEuclidean_thisLink.addActionListener(new ActionListener() {
            @Override/*from  w w w . j  av a2s.  co m*/
            public void actionPerformed(ActionEvent e) {
                Link link = netPlan.getLinkFromId(linkId);
                Node originNode = link.getOriginNode();
                Node destinationNode = link.getDestinationNode();
                double euclideanDistance = netPlan.getNodePairEuclideanDistance(originNode, destinationNode);
                link.setLengthInKm(euclideanDistance);
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            }
        });

        options.add(lengthToEuclidean_thisLink);

        JMenuItem lengthToHaversine_allNodes = new JMenuItem(
                "Set link length to node-pair Haversine distance (longitude-latitude) in km");
        lengthToHaversine_allNodes.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Link link = netPlan.getLinkFromId(linkId);
                Node originNode = link.getOriginNode();
                Node destinationNode = link.getDestinationNode();
                double haversineDistanceInKm = netPlan.getNodePairHaversineDistanceInKm(originNode,
                        destinationNode);
                link.setLengthInKm(haversineDistanceInKm);
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            }
        });

        options.add(lengthToHaversine_allNodes);

        JMenuItem scaleLinkLength_thisLink = new JMenuItem("Scale link length");
        scaleLinkLength_thisLink.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double scaleFactor;

                while (true) {
                    String str = JOptionPane.showInputDialog(null, "(Multiplicative) Scale factor",
                            "Scale link length", JOptionPane.QUESTION_MESSAGE);
                    if (str == null)
                        return;

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

                        break;
                    } catch (Throwable ex) {
                        ErrorHandling.showErrorDialog(
                                "Non-valid scale value. Please, introduce a non-negative number",
                                "Error setting scale factor");
                    }
                }

                netPlan.getLinkFromId(linkId)
                        .setLengthInKm(netPlan.getLinkFromId(linkId).getLengthInKm() * scaleFactor);
                callback.updateVisualizationAfterChanges(Collections.singleton(NetworkElementType.LINK));
                callback.getUndoRedoNavigationManager().addNetPlanChange();
            }
        });

        options.add(scaleLinkLength_thisLink);

        if (netPlan.isMultilayer()) {
            Link link = netPlan.getLinkFromId(linkId);
            if (link.getCoupledDemand() != null) {
                JMenuItem decoupleLinkItem = new JMenuItem("Decouple link (if coupled to unicast demand)");
                decoupleLinkItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        netPlan.getLinkFromId(linkId).getCoupledDemand().decouple();
                        model.setValueAt("", row, 20);
                        callback.getVisualizationState().resetPickedState();
                        callback.updateVisualizationAfterChanges(
                                Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND));
                        callback.getUndoRedoNavigationManager().addNetPlanChange();
                    }
                });

                options.add(decoupleLinkItem);
            } else {
                JMenuItem createLowerLayerDemandFromLinkItem = new JMenuItem(
                        "Create lower layer demand from link");
                createLowerLayerDemandFromLinkItem.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 lower layer to create the demand",
                                    JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
                            if (result != JOptionPane.OK_OPTION)
                                return;

                            try {
                                long layerId = (long) ((StringLabeller) layerSelector.getSelectedItem())
                                        .getObject();
                                Link link = netPlan.getLinkFromId(linkId);
                                netPlan.addDemand(link.getOriginNode(), link.getDestinationNode(),
                                        link.getCapacity(), link.getAttributes(),
                                        netPlan.getNetworkLayerFromId(layerId));
                                callback.getVisualizationState().resetPickedState();
                                callback.updateVisualizationAfterChanges(
                                        Sets.newHashSet(NetworkElementType.DEMAND));
                                callback.getUndoRedoNavigationManager().addNetPlanChange();
                                break;
                            } catch (Throwable ex) {
                                ErrorHandling.showErrorDialog(ex.getMessage(),
                                        "Error creating lower layer demand from link");
                            }
                        }
                    }
                });

                options.add(createLowerLayerDemandFromLinkItem);

                JMenuItem coupleLinkToDemand = new JMenuItem("Couple link to lower layer demand");
                coupleLinkToDemand.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Collection<Long> layerIds = netPlan.getNetworkLayerIds();
                        final JComboBox layerSelector = new WiderJComboBox();
                        final JComboBox demandSelector = 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();

                                    demandSelector.removeAllItems();
                                    for (Demand demand : netPlan
                                            .getDemands(netPlan.getNetworkLayerFromId(selectedLayerId))) {
                                        if (demand.isCoupled())
                                            continue;

                                        long ingressNodeId = demand.getIngressNode().getId();
                                        long egressNodeId = demand.getEgressNode().getId();
                                        String ingressNodeName = demand.getIngressNode().getName();
                                        String egressNodeName = demand.getEgressNode().getName();

                                        demandSelector.addItem(StringLabeller.unmodifiableOf(demand.getId(),
                                                "d" + demand.getId() + " [n" + ingressNodeId + " ("
                                                        + ingressNodeName + ") -> n" + egressNodeId + " ("
                                                        + egressNodeName + ")]"));
                                    }
                                }

                                if (demandSelector.getItemCount() == 0) {
                                    demandSelector.setEnabled(false);
                                } else {
                                    demandSelector.setSelectedIndex(0);
                                    demandSelector.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 demand: "));
                        pane.add(demandSelector, "growx, wrap");

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

                            try {
                                long demandId;
                                try {
                                    demandId = (long) ((StringLabeller) demandSelector.getSelectedItem())
                                            .getObject();
                                } catch (Throwable ex) {
                                    throw new RuntimeException("No demand was selected");
                                }

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

                options.add(coupleLinkToDemand);
            }
        }
    }

    if (rowVisibleLinks.size() > 1) {
        if (!options.isEmpty())
            options.add(new JPopupMenu.Separator());

        JMenuItem caFixValue = new JMenuItem("Set capacity to all");
        caFixValue.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double u_e;

                while (true) {
                    String str = JOptionPane.showInputDialog(null, "Capacity value",
                            "Set capacity to all table links", JOptionPane.QUESTION_MESSAGE);
                    if (str == null)
                        return;

                    try {
                        u_e = Double.parseDouble(str);
                        if (u_e < 0)
                            throw new NumberFormatException();

                        break;
                    } catch (NumberFormatException ex) {
                        ErrorHandling.showErrorDialog(
                                "Non-valid capacity value. Please, introduce a non-negative number",
                                "Error setting capacity value");
                    }
                }

                try {
                    for (Link link : rowVisibleLinks)
                        link.setCapacity(u_e);
                    callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set capacity to all links");
                }
            }
        });

        options.add(caFixValue);

        JMenuItem caFixValueUtilization = new JMenuItem("Set capacity to match a given utilization");
        caFixValueUtilization.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double utilization;

                while (true) {
                    String str = JOptionPane.showInputDialog(null, "Link utilization value",
                            "Set capacity to all table links to match a given utilization",
                            JOptionPane.QUESTION_MESSAGE);
                    if (str == null)
                        return;

                    try {
                        utilization = Double.parseDouble(str);
                        if (utilization <= 0)
                            throw new NumberFormatException();

                        break;
                    } catch (NumberFormatException ex) {
                        ErrorHandling.showErrorDialog(
                                "Non-valid link utilization value. Please, introduce a strictly positive number",
                                "Error setting link utilization value");
                    }
                }

                try {
                    for (Link link : rowVisibleLinks)
                        link.setCapacity(link.getOccupiedCapacity() / utilization);
                    callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(),
                            "Unable to set capacity to all links according to a given link utilization");
                }
            }
        });

        options.add(caFixValueUtilization);

        JMenuItem lengthToAll = new JMenuItem("Set link length to all");
        lengthToAll.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double l_e;

                while (true) {
                    String str = JOptionPane.showInputDialog(null, "Link length value (in km)",
                            "Set link length to all table links", JOptionPane.QUESTION_MESSAGE);
                    if (str == null)
                        return;

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

                        break;
                    } catch (Throwable ex) {
                        ErrorHandling.showErrorDialog(
                                "Non-valid link length value. Please, introduce a non-negative number",
                                "Error setting link length");
                    }
                }

                NetPlan netPlan = callback.getDesign();

                try {
                    for (Link link : rowVisibleLinks)
                        link.setLengthInKm(l_e);
                    callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to set link length to all links");
                }
            }
        });

        options.add(lengthToAll);

        JMenuItem lengthToEuclidean_allLinks = new JMenuItem(
                "Set all table link lengths to node-pair Euclidean distance");
        lengthToEuclidean_allLinks.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    for (Link link : rowVisibleLinks)
                        link.setLengthInKm(netPlan.getNodePairEuclideanDistance(link.getOriginNode(),
                                link.getDestinationNode()));
                    callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(),
                            "Unable to set link length value to all links");
                }
            }
        });

        options.add(lengthToEuclidean_allLinks);

        JMenuItem lengthToHaversine_allLinks = new JMenuItem(
                "Set all table link lengths to node-pair Haversine distance (longitude-latitude) in km");
        lengthToHaversine_allLinks.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                NetPlan netPlan = callback.getDesign();

                try {
                    for (Link link : rowVisibleLinks) {
                        link.setLengthInKm(netPlan.getNodePairHaversineDistanceInKm(link.getOriginNode(),
                                link.getDestinationNode()));
                    }
                    callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(),
                            "Unable to set link length value to all links");
                }
            }
        });

        options.add(lengthToHaversine_allLinks);

        JMenuItem scaleLinkLength_allLinks = new JMenuItem("Scale all table link lengths");
        scaleLinkLength_allLinks.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double scaleFactor;

                while (true) {
                    String str = JOptionPane.showInputDialog(null, "(Multiplicative) Scale factor",
                            "Scale (all) link length", JOptionPane.QUESTION_MESSAGE);
                    if (str == null)
                        return;

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

                        break;
                    } catch (Throwable ex) {
                        ErrorHandling.showErrorDialog(
                                "Non-valid scale value. Please, introduce a non-negative number",
                                "Error setting scale factor");
                    }
                }

                NetPlan netPlan = callback.getDesign();

                try {
                    for (Link link : rowVisibleLinks)
                        link.setLengthInKm(link.getLengthInKm() * scaleFactor);
                    callback.updateVisualizationAfterChanges(Sets.newHashSet(NetworkElementType.LINK));
                    callback.getUndoRedoNavigationManager().addNetPlanChange();
                } catch (Throwable ex) {
                    ErrorHandling.showErrorDialog(ex.getMessage(), "Unable to scale link length");
                }
            }
        });

        options.add(scaleLinkLength_allLinks);

        if (netPlan.isMultilayer()) {
            final Set<Link> coupledLinks = rowVisibleLinks.stream().filter(e -> e.isCoupled())
                    .collect(Collectors.toSet());
            if (!coupledLinks.isEmpty()) {
                JMenuItem decoupleAllLinksItem = new JMenuItem("Decouple all table links");
                decoupleAllLinksItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        for (Link link : coupledLinks)
                            if (link.getCoupledDemand() == null)
                                link.getCoupledMulticastDemand().decouple();
                            else
                                link.getCoupledDemand().decouple();
                        int numRows = model.getRowCount();
                        for (int i = 0; i < numRows; i++)
                            model.setValueAt("", i, 20);
                        callback.getVisualizationState().resetPickedState();
                        callback.updateVisualizationAfterChanges(
                                Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND));
                        callback.getUndoRedoNavigationManager().addNetPlanChange();
                    }
                });

                options.add(decoupleAllLinksItem);
            }

            if (coupledLinks.size() < rowVisibleLinks.size()) {
                JMenuItem createLowerLayerDemandsFromLinksItem = new JMenuItem(
                        "Create lower layer unicast demands from uncoupled links");
                createLowerLayerDemandsFromLinksItem.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JComboBox layerSelector = new WiderJComboBox();
                        for (NetworkLayer layer : netPlan.getNetworkLayers()) {
                            if (layer.getId() == netPlan.getNetworkLayerDefault().getId())
                                continue;

                            final String layerName = layer.getName();
                            String layerLabel = "Layer " + layer.getId();
                            if (!layerName.isEmpty())
                                layerLabel += " (" + layerName + ")";

                            layerSelector.addItem(StringLabeller.of(layer.getId(), 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 lower layer to create demands",
                                    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 (Link link : rowVisibleLinks)
                                    if (!link.isCoupled())
                                        link.coupleToNewDemandCreated(layer);
                                callback.getVisualizationState()
                                        .recomputeCanvasTopologyBecauseOfLinkOrNodeAdditionsOrRemovals();
                                callback.updateVisualizationAfterChanges(
                                        Sets.newHashSet(NetworkElementType.LINK, NetworkElementType.DEMAND));
                                callback.getUndoRedoNavigationManager().addNetPlanChange();
                                break;
                            } catch (Throwable ex) {
                                ErrorHandling.showErrorDialog(ex.getMessage(),
                                        "Error creating lower layer demands");
                            }
                        }
                    }
                });

                options.add(createLowerLayerDemandsFromLinksItem);
            }
        }
    }
    return options;
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java

private JPanel getExecutionTypePanel(final ModelGraph graph, final ViewState state) {
    JPanel panel = new JPanel();
    panel.setBorder(new EtchedBorder());
    panel.setLayout(new BorderLayout());
    panel.add(new JLabel("ExecutionType:"), BorderLayout.WEST);
    JComboBox comboBox = new JComboBox();
    if (graph.hasChildren()) {
        comboBox.addItem("parallel");
        comboBox.addItem("sequential");
    } else if (graph.getModel().getExecutionType().equals("task")) {
        comboBox.addItem("parallel");
        comboBox.addItem("sequential");
        comboBox.addItem("task");
    } else if (graph.isCondition() || graph.getModel().getExecutionType().equals("condition")) {
        comboBox.addItem("parallel");
        comboBox.addItem("sequential");
        comboBox.addItem("condition");
    } else {//from   ww w . j av  a 2 s.com
        comboBox.addItem("parallel");
        comboBox.addItem("sequential");
        comboBox.addItem("task");
    }
    comboBox.setSelectedItem(graph.getModel().getExecutionType());
    comboBox.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (!graph.getModel().getExecutionType().equals(e.getItem())) {
                graph.getModel().setExecutionType((String) e.getItem());
                DefaultPropView.this.notifyListeners();
                DefaultPropView.this.refreshView(state);
            }
        }
    });
    panel.add(comboBox, BorderLayout.CENTER);
    return panel;
}

From source file:org.encog.workbench.tabs.visualize.bayesian.BayesianStructureTab.java

public BayesianStructureTab(BayesianNetwork method) {
    super(null);// w w w  .j  a  v  a2 s.c o  m

    // Graph<V, E> where V is the type of the vertices
    // and E is the type of the edges
    this.graph = buildGraph(method);

    Layout<DrawnEvent, DrawnEventConnection> layout = new KKLayout(graph);

    vv = new VisualizationViewer<DrawnEvent, DrawnEventConnection>(layout);

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller<DrawnEvent>());
    vv.getRenderer().getVertexLabelRenderer().setPositioner(new InsidePositioner());
    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.N);

    vv.setVertexToolTipTransformer(new Transformer<DrawnEvent, String>() {
        public String transform(DrawnEvent edge) {
            return edge.getToolTip();
        }
    });

    Transformer<DrawnEvent, Paint> vertexPaint = new Transformer<DrawnEvent, Paint>() {
        public Paint transform(DrawnEvent neuron) {
            return Color.white;
        }
    };

    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    this.setLayout(new BorderLayout());
    add(panel, BorderLayout.CENTER);
    final AbstractModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    vv.setGraphMouse(graphMouse);

    vv.addKeyListener(graphMouse.getModeKeyListener());
    vv.getRenderContext().setVertexFillPaintTransformer(vertexPaint);

    final ScalingControl scaler = new CrossoverScalingControl();

    Class[] combos = getCombos();
    final JComboBox jcb = new JComboBox(combos);
    // use a renderer to shorten the layout name presentation
    jcb.setRenderer(new DefaultListCellRenderer() {
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {
            String valueString = value.toString();
            valueString = valueString.substring(valueString.lastIndexOf('.') + 1);
            return super.getListCellRendererComponent(list, valueString, index, isSelected, cellHasFocus);
        }
    });
    jcb.addActionListener(new LayoutChooser(jcb, vv));
    jcb.setSelectedItem(FRLayout.class);

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JButton reset = new JButton("reset");
    reset.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.LAYOUT).setToIdentity();
            vv.getRenderContext().getMultiLayerTransformer().getTransformer(Layer.VIEW).setToIdentity();
        }
    });

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(((DefaultModalGraphMouse<Integer, Number>) vv.getGraphMouse()).getModeListener());

    JPanel controls = new JPanel();
    controls.setLayout(new FlowLayout(FlowLayout.LEFT));
    controls.add(plus);
    controls.add(minus);
    controls.add(reset);
    controls.add(modeBox);
    controls.add(jcb);
    Border border = BorderFactory.createEtchedBorder();
    controls.setBorder(border);
    add(controls, BorderLayout.NORTH);

}

From source file:org.languagetool.gui.ConfigurationDialog.java

@NotNull
private JPanel getMotherTonguePanel(GridBagConstraints cons) {
    JPanel motherTonguePanel = new JPanel();
    if (insideOffice) {
        motherTonguePanel.setLayout(new GridBagLayout());
        GridBagConstraints cons1 = new GridBagConstraints();
        cons1.insets = new Insets(0, 0, 0, 0);
        cons1.gridx = 0;//from   w  ww. ja v a 2  s  . c o  m
        cons1.gridy = 0;
        cons1.anchor = GridBagConstraints.WEST;
        cons1.fill = GridBagConstraints.NONE;
        cons1.weightx = 0.0f;
        JRadioButton[] radioButtons = new JRadioButton[2];
        ButtonGroup numParaGroup = new ButtonGroup();
        radioButtons[0] = new JRadioButton(Tools.getLabel(messages.getString("guiUseDocumentLanguage")));
        radioButtons[0].setActionCommand("DocLang");
        radioButtons[0].setSelected(true);

        radioButtons[1] = new JRadioButton(Tools.getLabel(messages.getString("guiSetLanguageTo")));
        radioButtons[1].setActionCommand("SelectLang");

        JComboBox<String> motherTongueBox = new JComboBox<>(getPossibleMotherTongues());
        if (config.getMotherTongue() != null) {
            motherTongueBox.setSelectedItem(config.getMotherTongue().getTranslatedName(messages));
        }
        motherTongueBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Language motherTongue;
                    if (motherTongueBox.getSelectedItem() instanceof String) {
                        motherTongue = getLanguageForLocalizedName(
                                motherTongueBox.getSelectedItem().toString());
                    } else {
                        motherTongue = (Language) motherTongueBox.getSelectedItem();
                    }
                    config.setMotherTongue(motherTongue);
                    config.setUseDocLanguage(false);
                    radioButtons[1].setSelected(true);
                }
            }
        });

        for (int i = 0; i < 2; i++) {
            numParaGroup.add(radioButtons[i]);
        }

        if (config.getUseDocLanguage()) {
            radioButtons[0].setSelected(true);
        } else {
            radioButtons[1].setSelected(true);
        }

        radioButtons[0].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                config.setUseDocLanguage(true);
            }
        });

        radioButtons[1].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                config.setUseDocLanguage(false);
                Language motherTongue;
                if (motherTongueBox.getSelectedItem() instanceof String) {
                    motherTongue = getLanguageForLocalizedName(motherTongueBox.getSelectedItem().toString());
                } else {
                    motherTongue = (Language) motherTongueBox.getSelectedItem();
                }
                config.setMotherTongue(motherTongue);
            }
        });
        motherTonguePanel.add(radioButtons[0], cons1);
        cons1.gridy++;
        motherTonguePanel.add(radioButtons[1], cons1);
        cons1.gridx = 1;
        motherTonguePanel.add(motherTongueBox, cons1);
    } else {
        motherTonguePanel.add(new JLabel(messages.getString("guiMotherTongue")), cons);
        JComboBox<String> motherTongueBox = new JComboBox<>(getPossibleMotherTongues());
        if (config.getMotherTongue() != null) {
            motherTongueBox.setSelectedItem(config.getMotherTongue().getTranslatedName(messages));
        }
        motherTongueBox.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                if (e.getStateChange() == ItemEvent.SELECTED) {
                    Language motherTongue;
                    if (motherTongueBox.getSelectedItem() instanceof String) {
                        motherTongue = getLanguageForLocalizedName(
                                motherTongueBox.getSelectedItem().toString());
                    } else {
                        motherTongue = (Language) motherTongueBox.getSelectedItem();
                    }
                    config.setMotherTongue(motherTongue);
                }
            }
        });
        motherTonguePanel.add(motherTongueBox, cons);
    }
    return motherTonguePanel;
}

From source file:org.metacsp.utility.UI.SearchTreeFrame.java

public SearchTreeFrame(DelegateForest<MetaVariable, ConstraintNetwork> graph) {

    this.graph = graph;
    treeLayout = new TreeLayout<MetaVariable, ConstraintNetwork>(graph);
    radialLayout = new RadialTreeLayout<MetaVariable, ConstraintNetwork>(graph);
    radialLayout.setSize(new Dimension(600, 600));
    vv = new VisualizationViewer<MetaVariable, ConstraintNetwork>(treeLayout, new Dimension(600, 600));
    vv.setBackground(Color.white);
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<MetaVariable, ConstraintNetwork>());
    vv.getRenderContext().setVertexLabelTransformer(new Transformer<MetaVariable, String>() {
        @Override//from   ww w  . j a  v a  2s. co m
        public String transform(MetaVariable arg0) {
            return arg0.toString();
        }
    });

    vv.setVertexToolTipTransformer(new Transformer<MetaVariable, String>() {
        @Override
        public String transform(MetaVariable arg0) {
            return arg0.toString();
        }
    });

    //vv.getRenderContext().setArrowFillPaintTransformer(new ConstantTransformer(Color.lightGray));
    vv.getRenderContext().setArrowFillPaintTransformer(new Transformer<ConstraintNetwork, Paint>() {
        @Override
        public Paint transform(ConstraintNetwork arg0) {
            return Color.lightGray;
        }
    });

    //System.out.println(graph.getVertices());
    rings = new Rings();

    Container content = getContentPane();
    final GraphZoomScrollPane panel = new GraphZoomScrollPane(vv);
    content.add(panel);

    final DefaultModalGraphMouse<?, ?> graphMouse = new DefaultModalGraphMouse<Object, Object>();

    vv.setGraphMouse(graphMouse);

    JComboBox modeBox = graphMouse.getModeComboBox();
    modeBox.addItemListener(graphMouse.getModeListener());
    graphMouse.setMode(Mode.TRANSFORMING);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JToggleButton radial = new JToggleButton("Radial");
    radial.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {

                LayoutTransition<MetaVariable, ConstraintNetwork> lt = new LayoutTransition<MetaVariable, ConstraintNetwork>(
                        vv, treeLayout, radialLayout);
                Animator animator = new Animator(lt);
                animator.start();
                vv.getRenderContext().getMultiLayerTransformer().setToIdentity();
                vv.addPreRenderPaintable(rings);
            } else {
                LayoutTransition<MetaVariable, ConstraintNetwork> lt = new LayoutTransition<MetaVariable, ConstraintNetwork>(
                        vv, radialLayout, treeLayout);
                Animator animator = new Animator(lt);
                animator.start();
                vv.getRenderContext().getMultiLayerTransformer().setToIdentity();
                vv.removePreRenderPaintable(rings);
            }
            vv.repaint();
        }
    });

    JPanel scaleGrid = new JPanel(new GridLayout(1, 0));
    scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom"));

    JPanel controls = new JPanel();
    scaleGrid.add(plus);
    scaleGrid.add(minus);
    controls.add(radial);
    controls.add(scaleGrid);
    controls.add(modeBox);

    content.add(controls, BorderLayout.SOUTH);
}

From source file:org.openmicroscopy.shoola.agents.fsimporter.chooser.LocationDialog.java

/**
 * Populates the JComboBox with the items provided adding hover tooltips,
 * selecting the specified item and attaching the listener.
 * /*ww  w .  ja v  a  2s  . c om*/
 * @param comboBox The JComboBox to populate
 * @param listItems The items to populate the box with
 * @param select The item to select in the JComboBox
 * @param itemListener An item listener to add for the JComboBox
 */
private void displayItems(JComboBox comboBox, List<DataNode> listItems, DataNode select,
        ItemListener itemListener) {
    if (comboBox == null || listItems == null)
        return;
    //Only add the item the user can actually select
    if (itemListener != null)
        comboBox.removeItemListener(itemListener);
    comboBox.removeAllItems();

    List<String> tooltips = new ArrayList<String>(listItems.size());
    List<String> lines;
    ExperimenterData exp;
    SelectableComboBoxModel model = new SelectableComboBoxModel();
    Selectable<DataNode> selected = null;

    GroupData group = getSelectedGroup();
    ExperimenterData user = getSelectedUser();
    long userID = -1;
    if (user != null)
        userID = user.getId();
    ExperimenterData loggedIn = ImporterAgent.getUserDetails();
    boolean isAdmin = ImporterAgent.isAdministrator();
    long loggedInID = loggedIn.getId();
    boolean userIsAdmin = isAdmin(userID);
    for (DataNode node : listItems) {
        exp = getExperimenter(node.getOwner());
        lines = new ArrayList<String>();
        if (exp != null) {
            lines.add("<b>Owner: </b>" + EditorUtil.formatExperimenter(exp));
        }
        lines.addAll(UIUtilities.wrapStyleWord(node.getFullName()));
        tooltips.add(UIUtilities.formatToolTipText(lines));

        boolean selectable = true;
        if (!node.isDefaultNode()) {
            selectable = canLink(node.getDataObject(), userID, group, loggedInID, isAdmin, userIsAdmin);
        }

        Selectable<DataNode> comboBoxItem = new Selectable<DataNode>(node, selectable);
        if (select != null && node.getDataObject().getId() == select.getDataObject().getId())
            selected = comboBoxItem;

        model.addElement(comboBoxItem);
    }

    ComboBoxToolTipRenderer renderer = createComboboxRenderer();
    renderer.setTooltips(tooltips);
    comboBox.setModel(model);
    comboBox.setRenderer(renderer);

    if (selected != null)
        comboBox.setSelectedItem(selected);

    if (itemListener != null)
        comboBox.addItemListener(itemListener);
}

From source file:org.openmicroscopy.shoola.agents.fsimporter.chooser.LocationDialog.java

/**
 * Populates the JComboBox with the user details provided, 
 * selecting the logged in user and attaching the item listener.
 * /* www.j  a v  a2  s .c o  m*/
 * @param comboBox The JComboBox to populate
 * @param group The group being displayed
 * @param itemListener An item listener to add for the JComboBox
 * @param userID The id of the user.
 */
private void displayUsers(JComboBox comboBox, GroupData group, ItemListener itemListener, long userID) {

    if (comboBox == null || group == null)
        return;

    if (itemListener != null)
        comboBox.removeItemListener(itemListener);
    comboBox.removeAllItems();

    DefaultComboBoxModel model = new SelectableComboBoxModel();
    Selectable<ExperimenterDisplay> selected = null;

    List<ExperimenterData> members = sort(group.getExperimenters());
    boolean canImportAs;
    Selectable<ExperimenterDisplay> item;
    List<String> tooltips = new ArrayList<String>(members.size());
    List<String> lines;
    for (ExperimenterData user : members) {
        canImportAs = canImportForUserInGroup(user, group);
        item = new Selectable<ExperimenterDisplay>(new ExperimenterDisplay(user), canImportAs);
        if (user.getId() == userID)
            selected = item;
        lines = new ArrayList<String>();
        lines.addAll(UIUtilities.wrapStyleWord(EditorUtil.formatExperimenter(user)));
        tooltips.add(UIUtilities.formatToolTipText(lines));
        model.addElement(item);
    }
    ComboBoxToolTipRenderer renderer = createComboboxRenderer();
    renderer.setTooltips(tooltips);
    comboBox.setModel(model);
    comboBox.setRenderer(renderer);

    if (selected != null)
        comboBox.setSelectedItem(selected);

    if (itemListener != null)
        comboBox.addItemListener(itemListener);
}

From source file:org.tellervo.desktop.tridasv2.ui.ComponentViewer.java

private void setupTreeGUI() {
    //create a graph
    Graph<String, String> ig = Graphs
            .<String, String>synchronizedDirectedGraph(new DirectedSparseMultigraph<String, String>());

    ObservableGraph<String, String> og = new ObservableGraph<String, String>(ig);
    og.addGraphEventListener(new GraphEventListener<String, String>() {

        public void handleGraphEvent(GraphEvent<String, String> evt) {
            System.err.println("got " + evt);

        }/*from   ww  w.  j  av  a  2  s .  co  m*/
    });
    this.g = og;
    //create a graphdraw
    layout = new FRLayout<String, String>(g);
    //layout = new ISOMLayout<String, String>(g);
    //layout = new KKLayout<String, String>(g);
    //layout = new CircleLayout<String, String>(g);

    vv = new VisualizationViewer<String, String>(layout, null);

    //tree2Panel.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

    tree2Panel.setLayout(new BorderLayout());
    tree2Panel.setBackground(java.awt.Color.lightGray);
    tree2Panel.setFont(new Font("Serif", Font.PLAIN, 12));

    vv.getModel().getRelaxer().setSleepTime(500);
    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse<Number, Number>();

    vv.setGraphMouse(graphMouse);

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);
    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
    vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());

    Transformer<String, Paint> vertexColor = new Transformer<String, Paint>() {
        public Paint transform(String i) {

            if (i.equals(ComponentTreeCellRenderer.getFullTitle(sample, false))) {
                return Color.ORANGE;
            } else {
                return Color.PINK;
            }
        }
    };

    Transformer<String, Paint> edgeColor = new Transformer<String, Paint>() {
        public Paint transform(String i) {
            return Color.WHITE;
        }
    };

    Transformer<String, Shape> vertexShape = new Transformer<String, Shape>() {
        public Shape transform(String i) {

            if (i.equals(ComponentTreeCellRenderer.getFullTitle(sample, false))) {
                return new Rectangle(-150, -20, 300, 40);

            } else {
                return new Rectangle(-150, -10, 300, 20);
            }
        }
    };

    vv.getRenderContext().setVertexFillPaintTransformer(vertexColor);
    vv.getRenderContext().setEdgeDrawPaintTransformer(edgeColor);
    vv.getRenderContext().setVertexShapeTransformer(vertexShape);
    ;

    vv.setForeground(Color.BLACK);
    tree2Panel.add(vv, BorderLayout.CENTER);

    JComboBox modeBox = graphMouse.getModeComboBox();

    modeBox.setRenderer(new JUNGModeRenderer());

    modeBox.addItemListener(graphMouse.getModeListener());
    graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);

    final ScalingControl scaler = new CrossoverScalingControl();

    JButton plus = new JButton("+");
    plus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1.1f, vv.getCenter());
        }
    });
    JButton minus = new JButton("-");
    minus.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            scaler.scale(vv, 1 / 1.1f, vv.getCenter());
        }
    });

    JPanel scaleGrid = new JPanel(new GridLayout(1, 0));
    scaleGrid.setBorder(BorderFactory.createTitledBorder("Zoom"));

    JPanel controls = new JPanel();
    scaleGrid.add(plus);
    scaleGrid.add(minus);
    controls.add(scaleGrid);
    controls.add(modeBox);

    tree2Panel.add(controls, BorderLayout.NORTH);

}