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: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 a v  a  2s. c  o 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:userinterface.properties.GUIGraphHandler.java

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

    JDialog dialog;/*from   w ww .  j  ava2  s.co  m*/
    JButton ok, cancel;
    JScrollPane scrollPane;
    ConstantPickerList constantList;
    JComboBox<String> xAxis, yAxis;

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

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

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

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

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

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

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

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

    //fill the axes components

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

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

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

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

    //fill the constants table

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

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

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

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

    }

    //do enables

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

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

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

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

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

    //add action listeners

    xAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            if (is2D) {
                return;
            }

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

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

                int index = yAxis.getSelectedIndex();

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

            }

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

                ConstantLine line = constantList.getConstantLine(i);

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

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    yAxis.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

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

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

                int index = xAxis.getSelectedIndex();

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

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

                ConstantLine line = constantList.getConstantLine(i);

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

                    line.doFuncEnables(false);
                } else {

                    line.doFuncEnables(true);
                }

            }
        }
    });

    ok.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            try {

                constantList.checkValid();

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

            if (is2D) {

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

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

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

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

                int seriesCount = 0;

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

                    ConstantLine line = constantList.getConstantLine(i);

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

                        seriesCount += line.getTotalNumOfValues();

                    }
                }

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

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

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

                }

                Values singleValuesGlobal = new Values();

                //add the single values to a global values list

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

                    ConstantLine line = constantList.getConstantLine(i);

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

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

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

                    SeriesKey key = pGraph.addSeries(seriesName);

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

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

                        double ans = -1;

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

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

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

                        }

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

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

                    }

                    if (isNewGraph) {
                        addGraph(pGraph);
                    }

                    dialog.dispose();
                    return;
                }

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

                    ConstantLine line = constantList.getConstantLine(i);

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

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

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

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

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

                            double ans = -1;

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

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

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

                            }

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

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

                                    continue;
                                }

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

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

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

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

                }

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

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

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

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

                //add the single values to a global values list

                Values singleValuesGlobal = new Values();

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

                    ConstantLine line = constantList.getConstantLine(i);

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

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

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

                SwingUtilities.invokeLater(new Runnable() {

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

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

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

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

            }

            dialog.dispose();
        }
    });

    cancel.addActionListener(new ActionListener() {

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

    //add everything to the dialog show the dialog

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

}

From source file:es.emergya.ui.plugins.admin.aux1.RecursoDialog.java

public RecursoDialog(final Recurso rec, final AdminResources adminResources) {
    super();/* www  .  ja  v a  2 s . c o  m*/
    setAlwaysOnTop(true);
    setSize(600, 400);

    setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosing(WindowEvent e) {
            super.windowClosing(e);
            if (cambios) {
                int res = JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION);
                if (res != JOptionPane.CANCEL_OPTION) {
                    e.getWindow().dispose();
                }
            } else {
                e.getWindow().dispose();
            }
        }
    });
    final Recurso r = (rec == null) ? null : RecursoConsultas.get(rec.getId());
    if (r != null) {
        setTitle(i18n.getString("Resources.summary.titleWindow") + " " + r.getIdentificador());
    } else {
        setTitle(i18n.getString("Resources.summary.titleWindow.new"));
    }
    setIconImage(getBasicWindow().getFrame().getIconImage());
    JPanel base = new JPanel();
    base.setBackground(Color.WHITE);
    base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS));

    // Icono del titulo
    JPanel title = new JPanel(new FlowLayout(FlowLayout.LEADING));
    title.setOpaque(false);
    JLabel labelTitulo = null;
    if (r != null) {
        labelTitulo = new JLabel(i18n.getString("Resources.summary"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    } else {
        labelTitulo = new JLabel(i18n.getString("Resources.cabecera.nuevo"),
                LogicConstants.getIcon("tittleficha_icon_recurso"), JLabel.LEFT);

    }
    labelTitulo.setFont(LogicConstants.deriveBoldFont(12f));
    title.add(labelTitulo);
    base.add(title);

    // Nombre
    JPanel mid = new JPanel(new SpringLayout());
    mid.setOpaque(false);
    mid.add(new JLabel(i18n.getString("Resources.name"), JLabel.RIGHT));
    final JTextField name = new JTextField(25);
    if (r != null) {
        name.setText(r.getNombre());
    }

    name.getDocument().addDocumentListener(changeListener);
    name.setEditable(r == null);
    mid.add(name);

    // patrullas
    final JLabel labelSquads = new JLabel(i18n.getString("Resources.squad"), JLabel.RIGHT);
    mid.add(labelSquads);
    List<Patrulla> pl = PatrullaConsultas.getAll();
    pl.add(0, null);
    final JComboBox squads = new JComboBox(pl.toArray());
    squads.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXXXXXXXXX");
    squads.addActionListener(changeSelectionListener);
    squads.setOpaque(false);
    labelSquads.setLabelFor(squads);
    if (r != null) {
        squads.setSelectedItem(r.getPatrullas());
    } else {
        squads.setSelectedItem(null);
    }
    squads.setEnabled((r != null && r.getHabilitado() != null) ? r.getHabilitado() : true);
    mid.add(squads);

    // // Identificador
    // mid.setOpaque(false);
    // mid.add(new JLabel(i18n.getString("Resources.identificador"),
    // JLabel.RIGHT));
    // final JTextField identificador = new JTextField("");
    // if (r != null) {
    // identificador.setText(r.getIdentificador());
    // }
    // identificador.getDocument().addDocumentListener(changeListener);
    // identificador.setEditable(r == null);
    // mid.add(identificador);
    // Espacio en blanco
    // mid.add(Box.createHorizontalGlue());
    // mid.add(Box.createHorizontalGlue());

    // Tipo
    final JLabel labelTipoRecursos = new JLabel(i18n.getString("Resources.type"), JLabel.RIGHT);
    mid.add(labelTipoRecursos);
    final JComboBox types = new JComboBox(RecursoConsultas.getTipos());
    labelTipoRecursos.setLabelFor(types);
    types.addActionListener(changeSelectionListener);
    if (r != null) {
        types.setSelectedItem(r.getTipo());
    } else {
        types.setSelectedItem(0);
    }
    // types.setEditable(true);
    types.setEnabled(true);
    mid.add(types);

    // Estado Eurocop
    mid.add(new JLabel(i18n.getString("Resources.status"), JLabel.RIGHT));
    final JTextField status = new JTextField();
    if (r != null && r.getEstadoEurocop() != null) {
        status.setText(r.getEstadoEurocop().getIdentificador());
    }
    status.setEditable(false);
    mid.add(status);

    // Subflota y patrulla
    mid.add(new JLabel(i18n.getString("Resources.subfleet"), JLabel.RIGHT));
    final JComboBox subfleets = new JComboBox(FlotaConsultas.getAllHabilitadas());
    subfleets.addActionListener(changeSelectionListener);
    if (r != null) {
        subfleets.setSelectedItem(r.getFlotas());
    } else {
        subfleets.setSelectedIndex(0);
    }
    subfleets.setEnabled(true);
    subfleets.setOpaque(false);
    mid.add(subfleets);

    // Referencia humana
    mid.add(new JLabel(i18n.getString("Resources.incidences"), JLabel.RIGHT));
    final JTextField rhumana = new JTextField();
    // if (r != null && r.getIncidencias() != null) {
    // rhumana.setText(r.getIncidencias().getReferenciaHumana());
    // }
    rhumana.setEditable(false);
    mid.add(rhumana);

    // dispositivo
    mid.add(new JLabel(i18n.getString("Resources.device"), JLabel.RIGHT));
    final PlainDocument plainDocument = new PlainDocument() {

        private static final long serialVersionUID = 4929271093724956016L;

        @Override
        public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
            if (this.getLength() + str.length() <= LogicConstants.LONGITUD_ISSI) {
                super.insertString(offs, str, a);
            }
        }
    };
    final JTextField issi = new JTextField(plainDocument, "", LogicConstants.LONGITUD_ISSI);
    plainDocument.addDocumentListener(changeListener);
    issi.setEditable(true);
    mid.add(issi);
    mid.add(new JLabel(i18n.getString("Resources.enabled"), JLabel.RIGHT));
    final JCheckBox enabled = new JCheckBox("", true);
    enabled.addActionListener(changeSelectionListener);
    enabled.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            if (enabled.isSelected()) {
                squads.setSelectedIndex(0);
            }
            squads.setEnabled(enabled.isSelected());
        }
    });
    enabled.setEnabled(true);
    enabled.setOpaque(false);
    if (r != null) {
        enabled.setSelected(r.getHabilitado());
    } else {
        enabled.setSelected(true);
    }
    if (r != null && r.getDispositivo() != null) {
        issi.setText(
                StringUtils.leftPad(String.valueOf(r.getDispositivo()), LogicConstants.LONGITUD_ISSI, '0'));
    }

    mid.add(enabled);

    // Fecha ultimo gps
    mid.add(new JLabel(i18n.getString("Resources.lastPosition"), JLabel.RIGHT));
    JTextField lastGPS = new JTextField();
    final Date lastGPSDateForRecurso = HistoricoGPSConsultas.lastGPSDateForRecurso(r);
    if (lastGPSDateForRecurso != null) {
        lastGPS.setText(SimpleDateFormat.getDateTimeInstance().format(lastGPSDateForRecurso));
    }
    lastGPS.setEditable(false);
    mid.add(lastGPS);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    // informacion adicional
    JPanel infoPanel = new JPanel(new SpringLayout());
    final JTextField info = new JTextField(25);
    info.getDocument().addDocumentListener(changeListener);
    infoPanel.add(new JLabel(i18n.getString("Resources.info")));
    infoPanel.add(info);
    infoPanel.setOpaque(false);
    info.setOpaque(false);
    SpringUtilities.makeCompactGrid(infoPanel, 1, 2, 6, 6, 6, 18);

    if (r != null) {
        info.setText(r.getInfoAdicional());
    } else {
        info.setText("");
    }
    info.setEditable(true);

    // Espacio en blanco
    mid.add(Box.createHorizontalGlue());
    mid.add(Box.createHorizontalGlue());

    SpringUtilities.makeCompactGrid(mid, 5, 4, 6, 6, 6, 18);
    base.add(mid);
    base.add(infoPanel);

    JPanel buttons = new JPanel();
    buttons.setOpaque(false);
    JButton accept = null;
    if (r == null) {
        accept = new JButton("Crear", LogicConstants.getIcon("button_crear"));
    } else {
        accept = new JButton("Guardar", LogicConstants.getIcon("button_save"));
    }
    accept.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (cambios || r == null || r.getId() == null) {
                    boolean shithappens = true;
                    if ((r == null || r.getId() == null)) { // Estamos
                        // creando
                        // uno nuevo
                        if (RecursoConsultas.alreadyExists(name.getText())) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                            shithappens = false;
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText())
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()))) {
                            shithappens = false;
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.dispositivoUnico"));
                        }
                    }
                    if (shithappens) {
                        if (name.getText().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.nombreNulo"));
                        } else if (issi.getText() != null && issi.getText().length() > 0 && StringUtils
                                .trimToEmpty(issi.getText()).length() != LogicConstants.LONGITUD_ISSI) {
                            JOptionPane.showMessageDialog(RecursoDialog.this, i18n.getString(Locale.ROOT,
                                    "admin.recursos.popup.error.faltanCifras", LogicConstants.LONGITUD_ISSI));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && LogicConstants.isNumeric(issi.getText()) && r != null && r.getId() != null
                                && RecursoConsultas.alreadyExists(new Integer(issi.getText()), r.getId())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.issiUnico"));
                        } else if (issi.getText() != null && issi.getText().length() > 0
                                && !LogicConstants.isNumeric(issi.getText())) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noNumerico"));
                            // } else if (identificador.getText().isEmpty())
                            // {
                            // JOptionPane
                            // .showMessageDialog(
                            // RecursoDialog.this,
                            // i18n.getString("admin.recursos.popup.error.identificadorNulo"));
                        } else if (subfleets.getSelectedIndex() == -1) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noSubflota"));
                        } else if (types.getSelectedItem() == null
                                || types.getSelectedItem().toString().trim().isEmpty()) {
                            JOptionPane.showMessageDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.error.noTipo"));
                        } else {
                            int i = JOptionPane.showConfirmDialog(RecursoDialog.this,
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.titulo"),
                                    i18n.getString("admin.recursos.popup.dialogo.guardar.guardar"),
                                    JOptionPane.YES_NO_CANCEL_OPTION);

                            if (i == JOptionPane.YES_OPTION) {

                                Recurso recurso = r;

                                if (r == null) {
                                    recurso = new Recurso();
                                }

                                recurso.setInfoAdicional(info.getText());
                                if (issi.getText() != null && issi.getText().length() > 0) {
                                    recurso.setDispositivo(new Integer(issi.getText()));
                                } else {
                                    recurso.setDispositivo(null);
                                }
                                recurso.setFlotas(FlotaConsultas.find(subfleets.getSelectedItem().toString()));
                                if (squads.getSelectedItem() != null && enabled.isSelected()) {
                                    recurso.setPatrullas(
                                            PatrullaConsultas.find(squads.getSelectedItem().toString()));
                                } else {
                                    recurso.setPatrullas(null);
                                }
                                recurso.setNombre(name.getText());
                                recurso.setHabilitado(enabled.isSelected());
                                // recurso.setIdentificador(identificador
                                // .getText());
                                recurso.setTipo(types.getSelectedItem().toString());
                                dispose();

                                RecursoAdmin.saveOrUpdate(recurso);
                                adminResources.refresh(null);

                                PluginEventHandler.fireChange(adminResources);
                            } else if (i == JOptionPane.NO_OPTION) {
                                dispose();
                            }
                        }
                    }
                } else {
                    log.debug("No hay cambios");
                    dispose();
                }

            } catch (Throwable t) {
                log.error("Error guardando un recurso", t);
            }
        }
    });
    buttons.add(accept);

    JButton cancelar = new JButton("Cancelar", LogicConstants.getIcon("button_cancel"));

    cancelar.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if (cambios) {
                if (JOptionPane.showConfirmDialog(RecursoDialog.this,
                        "Existen cambios sin guardar. Seguro que desea cerrar la ventana?",
                        "Cambios sin guardar", JOptionPane.OK_CANCEL_OPTION) != JOptionPane.CANCEL_OPTION) {
                    dispose();
                }
            } else {
                dispose();
            }
        }
    });

    buttons.add(cancelar);

    base.add(buttons);

    getContentPane().add(base);
    setLocationRelativeTo(null);
    cambios = false;
    if (r == null) {
        cambios = true;
    }

    pack();

    int x;
    int y;

    Container myParent = getBasicWindow().getPluginContainer().getDetachedTab(0);
    Point topLeft = myParent.getLocationOnScreen();
    Dimension parentSize = myParent.getSize();

    Dimension mySize = getSize();

    if (parentSize.width > mySize.width) {
        x = ((parentSize.width - mySize.width) / 2) + topLeft.x;
    } else {
        x = topLeft.x;
    }

    if (parentSize.height > mySize.height) {
        y = ((parentSize.height - mySize.height) / 2) + topLeft.y;
    } else {
        y = topLeft.y;
    }

    setLocation(x, y);
    cambios = false;
}

From source file:org.openmicroscopy.shoola.agents.util.SelectionWizard.java

/**
 * Creates the filtering controls.//from   w  w w . j  av  a2 s  .c  om
 *
 * @return See above.
 */
private JPanel createFilteringControl() {
    JPanel p = new JPanel();
    p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
    p.add(new JLabel("Filter by"));
    String txt = null;
    if (TagAnnotationData.class.equals(type)) {
        txt = "tag";
    } else if (TagAnnotationData.class.equals(type)) {
        txt = "attachment";
    }
    String[] values = new String[2];
    StringBuilder builder = new StringBuilder();
    builder.append("start of ");
    if (txt != null) {
        builder.append(txt);
        builder.append(" ");
    }
    builder.append("name");
    values[0] = builder.toString();

    builder = new StringBuilder();
    builder.append("anywhere in ");
    if (txt != null) {
        builder.append(txt);
        builder.append(" ");
    }
    builder.append("name");
    values[1] = builder.toString();
    JComboBox box = new JComboBox(values);
    int selected = 0;
    if (uiDelegate.isFilterAnywhere())
        selected = 1;
    box.setSelectedIndex(selected);
    box.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            JComboBox src = (JComboBox) e.getSource();
            uiDelegate.setFilterAnywhere(src.getSelectedIndex() == 1);
        }
    });
    JPanel rows = new JPanel();
    rows.setLayout(new BoxLayout(rows, BoxLayout.Y_AXIS));
    p.add(box);
    rows.add(p);
    if (!ExperimenterData.class.equals(type)) {
        //Filter by owner
        p = new JPanel();
        p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
        p.add(new JLabel("Filter by owner"));
        values = new String[3];
        values[SelectionWizardUI.ALL] = "All";
        values[SelectionWizardUI.CURRENT] = "Owned by me";
        values[SelectionWizardUI.OTHERS] = "Owned by others";
        box = new JComboBox(values);
        box.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JComboBox src = (JComboBox) e.getSource();
                uiDelegate.setOwnerIndex(src.getSelectedIndex());
            }
        });
        p.add(box);
        rows.add(p);
    }
    return UIUtilities.buildComponentPanel(rows);
}

From source file:org.openuat.apps.IPSecConnectorAdmin.java

/**
 * dialog to set up the dongle configuration.
 *//*from www . ja va  2  s  . c om*/
private static Configuration configureDialog(String[] ports, String[] sides, String[] types) {
    JTextField username = new JTextField();
    JComboBox cport = new JComboBox(ports);
    JComboBox csides = new JComboBox(sides);
    JComboBox ctypes = new JComboBox(types);
    int option = JOptionPane.showOptionDialog(null,
            new Object[] { "User Name:", username, "Choose your port", cport,
                    "On which side of your Device is the Dongle plugged into:", csides, " What type of Device:",
                    ctypes, },
            " Relate Dongle Configuration", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null,
            null);
    if ((option == JOptionPane.CLOSED_OPTION) || (option == JOptionPane.CANCEL_OPTION)) {
        System.exit(0);
    }
    Configuration config = new Configuration(cport.getSelectedItem() + "");
    config.setType(ctypes.getSelectedIndex());
    config.setSide(csides.getSelectedIndex());
    config.setUserName(username.getText());
    config.setDeviceType(Configuration.DEVICE_TYPE_DONGLE);
    //      logger.finer(config);
    return config;
}

From source file:org.pentaho.ui.xul.swing.tags.SwingTree.java

private TableCellEditor getCellEditor(final SwingTreeCol col) {
    return new DefaultCellEditor(new JComboBox()) {

        JComponent control;//w w w.j  av a  2  s  . co m

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
                final int row, final int column) {
            Component comp;
            ColumnType colType = col.getColumnType();
            if (colType == ColumnType.DYNAMIC) {
                colType = ColumnType.valueOf(extractDynamicColType(elements.toArray()[row], column));
            }

            final XulTreeCell cell = getRootChildren().getItem(row).getRow().getCell(column);
            switch (colType) {
            case CHECKBOX:
                final JCheckBox checkbox = new JCheckBox();
                final JTable tbl = table;
                checkbox.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent event) {
                        SwingTree.this.table.setValueAt(checkbox.isSelected(), row, column);
                        tbl.getCellEditor().stopCellEditing();
                    }
                });

                control = checkbox;
                if (value instanceof String) {
                    checkbox.setSelected(((String) value).equalsIgnoreCase("true")); //$NON-NLS-1$
                } else if (value instanceof Boolean) {
                    checkbox.setSelected((Boolean) value);
                } else if (value == null) {
                    checkbox.setSelected(false);
                }
                if (isSelected) {
                    checkbox.setBackground(Color.LIGHT_GRAY);
                }
                comp = checkbox;
                checkbox.setEnabled(!cell.isDisabled());
                break;
            case EDITABLECOMBOBOX:
            case COMBOBOX:
                Vector val = (value != null && value instanceof Vector) ? (Vector) value : new Vector();
                final JComboBox comboBox = new JComboBox(val);

                if (isSelected) {
                    comboBox.setBackground(Color.LIGHT_GRAY);
                }

                if (colType == ColumnType.EDITABLECOMBOBOX) {

                    comboBox.setEditable(true);
                    final JTextComponent textComp = (JTextComponent) comboBox.getEditor().getEditorComponent();

                    textComp.addKeyListener(new KeyListener() {
                        private String oldValue = ""; //$NON-NLS-1$

                        public void keyPressed(KeyEvent e) {
                            oldValue = textComp.getText();
                        }

                        public void keyReleased(KeyEvent e) {
                            if (oldValue != null && !oldValue.equals(textComp.getText())) {
                                SwingTree.this.table.setValueAt(textComp.getText(), row, column);

                                oldValue = textComp.getText();
                            } else if (oldValue == null) {
                                // AWT error where sometimes the keyReleased is fired before keyPressed.
                                oldValue = textComp.getText();
                            } else {
                                logger.debug("Special key pressed, ignoring"); //$NON-NLS-1$
                            }
                        }

                        public void keyTyped(KeyEvent e) {
                        }
                    });

                    comboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                            // if(textComp.hasFocus() == false && comboBox.hasFocus()){
                            SwingTree.logger.debug("Setting ComboBox value from editor: " //$NON-NLS-1$
                                    + comboBox.getSelectedItem() + ", " + row + ", " + column); //$NON-NLS-1$ //$NON-NLS-2$

                            SwingTree.this.table.setValueAt(comboBox.getSelectedIndex(), row, column);
                            // }
                        }
                    });
                } else {
                    comboBox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {

                            SwingTree.logger.debug("Setting ComboBox value from editor: " //$NON-NLS-1$
                                    + comboBox.getSelectedItem() + ", " + row + ", " + column); //$NON-NLS-1$ //$NON-NLS-2$

                            SwingTree.this.table.setValueAt(comboBox.getSelectedIndex(), row, column);
                        }
                    });
                }

                control = comboBox;
                comboBox.setEnabled(!cell.isDisabled());
                comp = comboBox;
                break;
            case LABEL:
                JLabel lbl = new JLabel(cell.getLabel());
                comp = lbl;
                control = lbl;
                break;
            case CUSTOM:
                return new CustomCellEditorWrapper(cell, customEditors.get(col.getType()));
            default:
                final JTextField label = new JTextField((String) value);

                label.getDocument().addDocumentListener(new DocumentListener() {

                    public void changedUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                    public void insertUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                    public void removeUpdate(DocumentEvent arg0) {
                        SwingTree.this.table.setValueAt(label.getText(), row, column);
                    }

                });
                if (isSelected) {
                    label.setOpaque(true);
                    // label.setBackground(Color.LIGHT_GRAY);
                }

                control = label;
                comp = label;
                label.setEnabled(!cell.isDisabled());
                label.setDisabledTextColor(Color.DARK_GRAY);
                break;
            }

            return comp;
        }

        @Override
        public Object getCellEditorValue() {
            if (control instanceof JCheckBox) {
                return ((JCheckBox) control).isSelected();
            } else if (control instanceof JComboBox) {
                JComboBox box = (JComboBox) control;
                if (box.isEditable()) {
                    return ((JTextComponent) box.getEditor().getEditorComponent()).getText();
                } else {
                    return box.getSelectedIndex();
                }
            } else if (control instanceof JTextField) {
                return ((JTextField) control).getText();
            } else {
                return ((JLabel) control).getText();
            }
        }

    };

}

From source file:pl.otros.logview.gui.actions.StartSocketListener.java

private LogImporterAndPort chooseLogImporter() {
    Collection<LogImporter> elements = AllPluginables.getInstance().getLogImportersContainer().getElements();
    LogImporter[] importers = elements.toArray(new LogImporter[0]);
    String[] names = new String[elements.size()];
    for (int i = 0; i < names.length; i++) {
        names[i] = importers[i].getName();
    }/*w  w w  .j  av a 2  s .c  o m*/

    JComboBox box = new JComboBox(names);
    SpinnerNumberModel numberModel = new SpinnerNumberModel(50505, 1025, 65000, 1);
    JSpinner jSpinner = new JSpinner(numberModel);
    MigLayout migLayout = new MigLayout();
    JPanel panel = new JPanel(migLayout);
    panel.add(new JLabel("Select log importer"));
    panel.add(box, "wrap");
    panel.add(new JLabel("Select port"));
    panel.add(jSpinner, "span");

    if (logReaders.size() > 0) {
        panel.add(new JLabel("Opened sockets"), "wrap, growx");
        JTable jTable = new JTable(logReaders.size(), 2);
        jTable.getTableHeader().getColumnModel().getColumn(0).setHeaderValue("Log importer");
        jTable.getTableHeader().getColumnModel().getColumn(1).setHeaderValue("Port");
        int row = 0;
        for (SocketLogReader socketLogReader : logReaders) {
            jTable.setValueAt(socketLogReader.getLogImporter().getName(), row, 0);
            jTable.setValueAt(Integer.toString(socketLogReader.getPort()), row, 1);
            row++;
        }
        JScrollPane jScrollPane = new JScrollPane(jTable);
        panel.add(jScrollPane, "wrap, span");
    }
    int showConfirmDialog = JOptionPane.showConfirmDialog(null, panel, "Choose log importer and port",
            JOptionPane.OK_CANCEL_OPTION);
    if (showConfirmDialog != JOptionPane.OK_OPTION) {
        return null;
    }

    return new LogImporterAndPort(importers[box.getSelectedIndex()], numberModel.getNumber().intValue());
}

From source file:pl.otros.logview.gui.LogViewMainFrame.java

private void initToolbar() {
    toolBar = new JToolBar();
    final JComboBox searchMode = new JComboBox(
            new String[] { "String contains search: ", "Regex search: ", "Query search: " });
    final SearchAction searchActionForward = new SearchAction(otrosApplication, SearchDirection.FORWARD);
    final SearchAction searchActionBackward = new SearchAction(otrosApplication, SearchDirection.REVERSE);
    searchFieldCbxModel = new DefaultComboBoxModel();
    searchField = new JXComboBox(searchFieldCbxModel);
    searchField.setEditable(true);/*  w  w w.j a  va  2s.co m*/
    AutoCompleteDecorator.decorate(searchField);
    searchField.setMinimumSize(new Dimension(150, 10));
    searchField.setPreferredSize(new Dimension(250, 10));
    searchField.setToolTipText(
            "<HTML>Enter text to search.<BR/>" + "Enter - search next,<BR/>Alt+Enter search previous,<BR/>"
                    + "Ctrl+Enter - mark all found</HTML>");
    final DelayedSwingInvoke delayedSearchResultUpdate = new DelayedSwingInvoke() {
        @Override
        protected void performActionHook() {
            JTextComponent editorComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
            int stringEnd = editorComponent.getSelectionStart();
            if (stringEnd < 0) {
                stringEnd = editorComponent.getText().length();
            }
            try {
                String selectedText = editorComponent.getText(0, stringEnd);
                if (StringUtils.isBlank(selectedText)) {
                    return;
                }
                OtrosJTextWithRulerScrollPane<JTextPane> logDetailWithRulerScrollPane = otrosApplication
                        .getSelectedLogViewPanel().getLogDetailWithRulerScrollPane();
                MessageUpdateUtils.highlightSearchResult(logDetailWithRulerScrollPane,
                        otrosApplication.getAllPluginables().getMessageColorizers());
                RulerBarHelper.scrollToFirstMarker(logDetailWithRulerScrollPane);
            } catch (BadLocationException e) {
                LOGGER.log(Level.SEVERE, "Can't update search highlight", e);
            }
        }
    };
    JTextComponent searchFieldTextComponent = (JTextComponent) searchField.getEditor().getEditorComponent();
    searchFieldTextComponent.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
        @Override
        protected void documentChanged(DocumentEvent e) {
            delayedSearchResultUpdate.performAction();
        }
    });
    final MarkAllFoundAction markAllFoundAction = new MarkAllFoundAction(otrosApplication);
    final SearchModeValidatorDocumentListener searchValidatorDocumentListener = new SearchModeValidatorDocumentListener(
            (JTextField) searchField.getEditor().getEditorComponent(), observer, SearchMode.STRING_CONTAINS);
    SearchMode searchModeFromConfig = configuration.get(SearchMode.class, "gui.searchMode",
            SearchMode.STRING_CONTAINS);
    final String lastSearchString;
    int selectedSearchMode = 0;
    if (searchModeFromConfig.equals(SearchMode.STRING_CONTAINS)) {
        selectedSearchMode = 0;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_STRING, "");
    } else if (searchModeFromConfig.equals(SearchMode.REGEX)) {
        selectedSearchMode = 1;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_REGEX, "");
    } else if (searchModeFromConfig.equals(SearchMode.QUERY)) {
        selectedSearchMode = 2;
        lastSearchString = configuration.getString(ConfKeys.SEARCH_LAST_QUERY, "");
    } else {
        LOGGER.warning("Unknown search mode " + searchModeFromConfig);
        lastSearchString = "";
    }
    Component editorComponent = searchField.getEditor().getEditorComponent();
    if (editorComponent instanceof JTextField) {
        final JTextField sfTf = (JTextField) editorComponent;
        sfTf.getDocument().addDocumentListener(searchValidatorDocumentListener);
        sfTf.getDocument().addDocumentListener(new DocumentInsertUpdateHandler() {
            @Override
            protected void documentChanged(DocumentEvent e) {
                try {
                    int length = e.getDocument().getLength();
                    if (length > 0) {
                        searchResultColorizer.setSearchString(e.getDocument().getText(0, length));
                    }
                } catch (BadLocationException e1) {
                    LOGGER.log(Level.SEVERE, "Error: ", e1);
                }
            }
        });
        sfTf.addKeyListener(new SearchFieldKeyListener(searchActionForward, sfTf));
        sfTf.setText(lastSearchString);
    }
    searchMode.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SearchMode mode = null;
            boolean validationEnabled = false;
            String confKey = null;
            String lastSearch = ((JTextField) searchField.getEditor().getEditorComponent()).getText();
            if (searchMode.getSelectedIndex() == 0) {
                mode = SearchMode.STRING_CONTAINS;
                searchValidatorDocumentListener.setSearchMode(mode);
                validationEnabled = false;
                searchMode.setToolTipText("Checking if log message contains string (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_STRING;
            } else if (searchMode.getSelectedIndex() == 1) {
                mode = SearchMode.REGEX;
                validationEnabled = true;
                searchMode
                        .setToolTipText("Checking if log message matches regular expression (case is ignored)");
                confKey = ConfKeys.SEARCH_LAST_REGEX;
            } else if (searchMode.getSelectedIndex() == 2) {
                mode = SearchMode.QUERY;
                validationEnabled = true;
                String querySearchTooltip = "<HTML>" + //
                "Advance search using SQL-like quries (i.e. level>=warning && msg~=failed && thread==t1)<BR/>" + //
                "Valid operator for query search is ==, ~=, !=, LIKE, EXISTS, <, <=, >, >=, &&, ||, ! <BR/>" + //
                "See wiki for more info<BR/>" + //
                "</HTML>";
                searchMode.setToolTipText(querySearchTooltip);
                confKey = ConfKeys.SEARCH_LAST_QUERY;
            }
            searchValidatorDocumentListener.setSearchMode(mode);
            searchValidatorDocumentListener.setEnable(validationEnabled);
            searchActionForward.setSearchMode(mode);
            searchActionBackward.setSearchMode(mode);
            markAllFoundAction.setSearchMode(mode);
            configuration.setProperty("gui.searchMode", mode);
            searchResultColorizer.setSearchMode(mode);
            List<Object> list = configuration.getList(confKey);
            searchFieldCbxModel.removeAllElements();
            for (Object o : list) {
                searchFieldCbxModel.addElement(o);
            }
            searchField.setSelectedItem(lastSearch);
        }
    });
    searchMode.setSelectedIndex(selectedSearchMode);
    final JCheckBox markFound = new JCheckBox("Mark search result");
    markFound.setMnemonic(KeyEvent.VK_M);
    searchField.addKeyListener(markAllFoundAction);
    configuration.addConfigurationListener(markAllFoundAction);
    JButton markAllFoundButton = new JButton(markAllFoundAction);
    final JComboBox markColor = new JComboBox(MarkerColors.values());
    markFound.setSelected(configuration.getBoolean("gui.markFound", true));
    markFound.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            boolean selected = markFound.isSelected();
            searchActionForward.setMarkFound(selected);
            searchActionBackward.setMarkFound(selected);
            configuration.setProperty("gui.markFound", markFound.isSelected());
        }
    });
    markColor.setRenderer(new MarkerColorsComboBoxRenderer());
    //      markColor.addActionListener(new ActionListener() {
    //
    //         @Override
    //         public void actionPerformed(ActionEvent e) {
    //            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
    //            searchActionForward.setMarkerColors(markerColors);
    //            searchActionBackward.setMarkerColors(markerColors);
    //            markAllFoundAction.setMarkerColors(markerColors);
    //            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
    //            otrosApplication.setSelectedMarkColors(markerColors);
    //         }
    //      });
    markColor.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            MarkerColors markerColors = (MarkerColors) markColor.getSelectedItem();
            searchActionForward.setMarkerColors(markerColors);
            searchActionBackward.setMarkerColors(markerColors);
            markAllFoundAction.setMarkerColors(markerColors);
            configuration.setProperty("gui.markColor", markColor.getSelectedItem());
            otrosApplication.setSelectedMarkColors(markerColors);
        }
    });
    markColor.getModel()
            .setSelectedItem(configuration.get(MarkerColors.class, "gui.markColor", MarkerColors.Aqua));
    buttonSearch = new JButton(searchActionForward);
    buttonSearch.setMnemonic(KeyEvent.VK_N);
    JButton buttonSearchPrev = new JButton(searchActionBackward);
    buttonSearchPrev.setMnemonic(KeyEvent.VK_P);
    enableDisableComponetsForTabs.addComponet(buttonSearch);
    enableDisableComponetsForTabs.addComponet(buttonSearchPrev);
    enableDisableComponetsForTabs.addComponet(searchField);
    enableDisableComponetsForTabs.addComponet(markFound);
    enableDisableComponetsForTabs.addComponet(markAllFoundButton);
    enableDisableComponetsForTabs.addComponet(searchMode);
    enableDisableComponetsForTabs.addComponet(markColor);
    toolBar.add(searchMode);
    toolBar.add(searchField);
    toolBar.add(buttonSearch);
    toolBar.add(buttonSearchPrev);
    toolBar.add(markFound);
    toolBar.add(markAllFoundButton);
    toolBar.add(markColor);
    JButton nextMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.FORWARD));
    nextMarked.setToolTipText(nextMarked.getText());
    nextMarked.setText("");
    nextMarked.setMnemonic(KeyEvent.VK_E);
    enableDisableComponetsForTabs.addComponet(nextMarked);
    toolBar.add(nextMarked);
    JButton prevMarked = new JButton(new JumpToMarkedAction(otrosApplication, Direction.BACKWARD));
    prevMarked.setToolTipText(prevMarked.getText());
    prevMarked.setText("");
    prevMarked.setMnemonic(KeyEvent.VK_R);
    enableDisableComponetsForTabs.addComponet(prevMarked);
    toolBar.add(prevMarked);
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, 1, Level.SEVERE)));
    enableDisableComponetsForTabs.addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.INFO)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.WARNING)));
    enableDisableComponetsForTabs
            .addComponet(toolBar.add(new SearchByLevel(otrosApplication, -1, Level.SEVERE)));
}

From source file:ro.nextreports.designer.querybuilder.RuntimeParametersPanel.java

private void initUI() {
    setLayout(new GridBagLayout());

    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    components = new ArrayList<JComponent>();
    checks = new ArrayList<JCheckBox>();

    int size = paramList.size();
    boolean shouldExpand = false;
    boolean needScroll = false;
    for (int i = 0; i < size; i++) {
        final int pos = i;
        final QueryParameter param = paramList.get(i);
        if (param.isHidden()) {
            components.add(null);/*ww w .  j a v a  2 s.  co m*/
            checks.add(null);
            initHiddenParameterValues(param);
            continue;
        }
        String source = param.getSource();
        String defaultSource = param.getDefaultSource();

        if ((defaultSource != null) && !defaultSource.trim().equals("")) {
            try {
                param.setDefaultSourceValues(Globals.getDBViewer().getDefaultSourceValues(con, param));
            } catch (NextSqlException e) {
                Show.error(e);
            }
        }

        final JComponent component;
        int anchor = GridBagConstraints.WEST;
        double y = 0.0;
        int expand = GridBagConstraints.HORIZONTAL;
        if ((source != null) && !source.equals("")) {
            List<IdName> values = new ArrayList<IdName>();
            try {
                if (param.isManualSource()) {
                    if (!param.isDependent()) {
                        values = Globals.getDBViewer().getValues(con, source, true, param.getOrderBy());
                    }
                } else {
                    int index = source.indexOf(".");
                    int index2 = source.lastIndexOf(".");
                    String tableName = source.substring(0, index);
                    String columnName;
                    String shownColumnName = null;
                    if (index == index2) {
                        columnName = source.substring(index + 1);
                    } else {
                        columnName = source.substring(index + 1, index2);
                        shownColumnName = source.substring(index2 + 1);
                    }
                    values = Globals.getDBViewer().getColumnValues(con, param.getSchema(), tableName,
                            columnName, shownColumnName, param.getOrderBy());
                }
            } catch (NextSqlException e) {
                error = true;
                Show.error(e);
            } catch (InvalidSqlException e) {
                String m = I18NSupport.getString("source.dialog.valid");
                Show.info(m + " : \"select <exp1> , <exp2> from ...\"");
            }
            if (param.getSelection().equals(ParameterEditPanel.SINGLE_SELECTION)) {
                component = new JComboBox();
                final JComboBox combo = (JComboBox) component;
                combo.setRenderer(new IdNameRenderer());
                combo.addItem("-- " + I18NSupport.getString("parameter.value.select") + " --");
                for (int j = 0, len = values.size(); j < len; j++) {
                    combo.addItem(values.get(j));
                }

                combo.addItemListener(new ItemListener() {
                    public void itemStateChanged(ItemEvent e) {
                        if (e.getStateChange() == ItemEvent.SELECTED) {
                            IdName in = null;
                            if (combo.getSelectedIndex() > 0) {
                                in = (IdName) combo.getSelectedItem();
                            }
                            parameterSelection(pos, in);
                        }
                    }
                });
                AutoCompleteDecorator.decorate(combo);
                needScroll = false;
            } else {
                anchor = GridBagConstraints.NORTHWEST;
                y = 1.0;
                expand = GridBagConstraints.BOTH;

                DefaultListModel model = new DefaultListModel();
                for (int j = 0, len = values.size(); j < len; j++) {
                    model.addElement(values.get(j));
                }
                List srcList = Arrays.asList(model.toArray());
                component = new ListSelectionPanel(srcList, new ArrayList(), "", "", true, false) {
                    protected void onAdd() {
                        selection();
                    }

                    protected void onRemove() {
                        selection();
                    }

                    // needed for saved parameters on rerun
                    protected void onSetRight() {
                        selection();
                    }

                    private void selection() {
                        if (ParameterManager.getInstance().getChildDependentParameters(param).size() > 0) {
                            Object[] values = getDestinationElements().toArray();
                            if (values.length == 0) {
                                values = new Object[] { ParameterUtil.NULL };
                            }
                            parameterSelection(pos, values);
                        }
                    }
                };
                ((ListSelectionPanel) component).setListSize(scrListDim);
                ((ListSelectionPanel) component).setRenderer(new IdNameRenderer(),
                        new IdNameComparator(param.getOrderBy()));

                shouldExpand = true;
            }

        } else {
            if (param.getSelection().equals(QueryParameter.MULTIPLE_SELECTION)) {
                anchor = GridBagConstraints.NORTHWEST;
                y = 1.0;
                expand = GridBagConstraints.BOTH;
                ;
                component = new ListAddPanel(param) {
                    protected void onAdd() {
                        selection();
                    }

                    protected void onRemove() {
                        selection();
                    }

                    private void selection() {
                        if (ParameterManager.getInstance().getChildDependentParameters(param).size() > 0) {
                            Object[] values = getElements().toArray();
                            parameterSelection(pos, values);
                        }
                    }
                };
            } else {
                needScroll = false;
                if (param.getValueClassName().equals("java.util.Date")) {
                    component = new JXDatePicker();
                    ((JXDatePicker) component).addPropertyChangeListener(new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent e) {
                            if ("date".equals(e.getPropertyName())) {
                                parameterSelection(pos, ((JXDatePicker) component).getDate());
                            }
                        }
                    });
                    // hack to fix bug with big popup button
                    JButton popupButton = (JButton) component.getComponent(1);
                    //popupButton.setMargin(new Insets(2, 2, 2, 2));
                    popupButton.setMinimumSize(new Dimension(20, (int) getPreferredSize().getHeight()));
                    popupButton.setPreferredSize(new Dimension(20, (int) getPreferredSize().getHeight()));
                    popupButton.setBorder(BorderFactory.createLineBorder(Color.GRAY));
                } else if (param.getValueClassName().equals("java.sql.Timestamp")
                        || param.getValueClassName().equals("java.sql.Time")) {
                    component = new JDateTimePicker() {
                        protected void onChange() {
                            parameterSelection(pos, getDate());
                        }
                    };
                    // hack to fix bug with big popup button
                    JButton popupButton = (JButton) (((JDateTimePicker) component).getDatePicker())
                            .getComponent(1);
                    //popupButton.setMargin(new Insets(2, 2, 2, 2));
                    popupButton.setMinimumSize(new Dimension(20, (int) getPreferredSize().getHeight()));
                    popupButton.setPreferredSize(new Dimension(20, (int) getPreferredSize().getHeight()));
                    popupButton.setBorder(BorderFactory.createLineBorder(Color.GRAY));
                } else if (param.getValueClassName().equals("java.lang.Boolean")) {
                    component = new JCheckBox();
                    ((JCheckBox) component).addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent actionEvent) {
                            AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
                            boolean selected = abstractButton.getModel().isSelected();
                            parameterSelection(pos, selected);
                        }
                    });
                } else {
                    component = new JTextField(25);
                    ((JTextField) component).getDocument().addDocumentListener(new DocumentListener() {

                        @Override
                        public void changedUpdate(DocumentEvent e) {
                            updateFromTextField(e);
                        }

                        @Override
                        public void insertUpdate(DocumentEvent e) {
                            updateFromTextField(e);
                        }

                        @Override
                        public void removeUpdate(DocumentEvent e) {
                            updateFromTextField(e);
                        }

                        private void updateFromTextField(DocumentEvent e) {
                            java.awt.EventQueue.invokeLater(new Runnable() {

                                @Override
                                public void run() {
                                    Object value = null;
                                    try {
                                        if ("".equals(((JTextField) component).getText().trim())) {
                                            value = null;
                                        } else {
                                            value = ParameterUtil.getParameterValueFromString(
                                                    param.getValueClassName(),
                                                    ((JTextField) component).getText());
                                        }
                                        parameterSelection(pos, value);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        LOG.error(e.getMessage(), e);
                                    }
                                }
                            });
                        }
                    });
                }
            }
        }
        components.add(component);
        final JCheckBox cb = new JCheckBox(I18NSupport.getString("run.parameter.ignore"));
        checks.add(cb);

        final JLabel label = new JLabel(getRuntimeParameterName(param));
        panel.add(label, new GridBagConstraints(0, i, 1, 1, 0.0, 0.0, anchor, GridBagConstraints.NONE,
                new Insets(5, 5, 5, 5), 0, 0));
        final JComponent addComponent;
        if (needScroll) {
            JScrollPane scr = new JScrollPane(component, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
            scr.setPreferredSize(listDim);
            addComponent = scr;
        } else {
            addComponent = component;
        }
        panel.add(addComponent, new GridBagConstraints(1, i, 1, 1, 1.0, y, GridBagConstraints.WEST, expand,
                new Insets(5, 0, 5, 5), 0, 0));
        int checkAnchor = GridBagConstraints.WEST;
        if ((addComponent instanceof JScrollPane) || (addComponent instanceof ListSelectionPanel)) {
            checkAnchor = GridBagConstraints.NORTHWEST;
        }

        if (Globals.getParametersIgnore()) {
            panel.add(cb, new GridBagConstraints(2, i, 1, 1, 0.0, 0.0, checkAnchor, GridBagConstraints.NONE,
                    new Insets(5, 0, 5, 5), 0, 0));
        }

        cb.addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                if (cb.isSelected()) {
                    if (addComponent instanceof JScrollPane) {
                        component.setEnabled(false);
                    }
                    label.setEnabled(false);
                    addComponent.setEnabled(false);
                    param.setIgnore(true);
                } else {
                    if (addComponent instanceof JScrollPane) {
                        component.setEnabled(true);
                    }
                    label.setEnabled(true);
                    addComponent.setEnabled(true);
                    param.setIgnore(false);
                }
            }
        });
    }

    // populate hidden dependent parameters (this will be done if a parameter depends only on a single hidden parameter)
    // if a parameter depends on a hidden parameter and other parameters, it cannot be populated here
    for (int i = 0; i < size; i++) {
        final QueryParameter param = paramList.get(i);
        if (param.isHidden()) {
            populateDependentParameters(param, false);
        }
    }

    if (!shouldExpand) {
        panel.add(new JLabel(), new GridBagConstraints(0, size, 3, 1, 1.0, 1.0, GridBagConstraints.WEST,
                GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
    }

    JScrollPane scrPanel = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    scrPanel.setPreferredSize(scrDim);
    scrPanel.setMinimumSize(scrDim);

    add(scrPanel, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.WEST, GridBagConstraints.BOTH,
            new Insets(0, 0, 0, 0), 0, 0));
    setParameterValues(parametersValues);
    setParameterIgnore(parametersIgnore);
}

From source file:ro.nextreports.designer.querybuilder.RuntimeParametersPanel.java

public Object getParameterValue(QueryParameter qp) throws RuntimeParameterException {

    String paramName = qp.getName();
    String runtimeParamName = qp.getRuntimeName();
    if ((runtimeParamName == null) || runtimeParamName.trim().equals("")) {
        runtimeParamName = paramName;/*w  ww  . j av a2s . c  o  m*/
    }
    JComponent component = getComponent(qp);
    String type = qp.getValueClassName();

    Object value = null;

    if (!qp.isIgnore()) {
        if (component instanceof JTextField) {
            value = ((JTextField) component).getText();
            if (value.equals("")) {
                if (qp.isMandatory()) {
                    throw new RuntimeParameterException(
                            I18NSupport.getString("runtime.parameters.notentered", runtimeParamName));
                } else {
                    value = null;
                }
            }
        } else if (component instanceof JComboBox) {
            JComboBox combo = (JComboBox) component;
            if (combo.getSelectedIndex() == 0) {
                if (qp.isMandatory()) {
                    throw new RuntimeParameterException(
                            I18NSupport.getString("runtime.parameters.notselected", runtimeParamName));
                } else {
                    value = null;
                }
            } else {
                value = combo.getSelectedItem();
            }
        } else if (component instanceof ListSelectionPanel) {
            value = ((ListSelectionPanel) component).getDestinationElements().toArray();
            if (((Object[]) value).length == 0) {
                if (qp.isMandatory()) {
                    throw new RuntimeParameterException(
                            I18NSupport.getString("runtime.parameters.notselected", runtimeParamName));
                } else {
                    value = new Object[] { ParameterUtil.NULL };
                }
            }
        } else if (component instanceof ListAddPanel) {
            value = ((ListAddPanel) component).getElements().toArray();
            if (((Object[]) value).length == 0) {
                if (qp.isMandatory()) {
                    throw new RuntimeParameterException(
                            I18NSupport.getString("runtime.parameters.notselected", runtimeParamName));
                } else {
                    value = new Object[] { ParameterUtil.NULL };
                }
            }
        } else if (component instanceof JDateTimePicker) {
            value = ((JDateTimePicker) component).getDate();
            if (value == null) {
                if (qp.isMandatory()) {
                    throw new RuntimeParameterException(
                            I18NSupport.getString("runtime.parameters.notentered", runtimeParamName));
                }
            }
        } else if (component instanceof JXDatePicker) {
            value = ((JXDatePicker) component).getDate();
            if (value == null) {
                if (qp.isMandatory()) {
                    throw new RuntimeParameterException(
                            I18NSupport.getString("runtime.parameters.notentered", runtimeParamName));
                }
            }
        } else if (component instanceof JCheckBox) {
            value = ((JCheckBox) component).isSelected();
        }

        if (value != null) {
            if (value.getClass().getName().equals("java.lang.String")) {
                try {
                    value = ParameterUtil.getParameterValueFromString(qp.getValueClassName(), (String) value);
                } catch (Exception e) {
                    LOG.error(e.getMessage(), e);
                    // the exception is thrown outside the for statement so that
                    // all parameter values are saved
                    throw new RuntimeParameterException("Invalid parameter value " + value + " for parameter "
                            + runtimeParamName + " of type " + type + " .");
                }
            }
        }
    }
    return value;
}