Example usage for java.awt.event ItemListener ItemListener

List of usage examples for java.awt.event ItemListener ItemListener

Introduction

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

Prototype

ItemListener

Source Link

Usage

From source file:org.nuclos.client.ui.collect.component.AbstractCollectableComponent.java

/**
 * @return//from  w ww.j a  v  a 2  s.co m
 * @precondition hasComparisonOperator()
 */
public JPopupMenu newComparisonOperatorPopupMenu() {
    if (!hasComparisonOperator()) {
        throw new IllegalStateException();
    }
    final JPopupMenu result = new JPopupMenu(
            getSpringLocaleDelegate().getMessage("AbstractCollectableComponent.16", "Vergleichsoperator"));

    // 1. comparison operators:
    final ButtonGroup btngrpComparisonOperators = new ButtonGroup();

    final ItemListener itemlistener = new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent ev) {
            if (ev.getStateChange() == ItemEvent.SELECTED) {
                final String sOperatorName = ((AbstractButton) ev.getItem()).getActionCommand();
                setComparisonOperator(ComparisonOperator.getInstance(sOperatorName));
                runLocked(new Runnable() {
                    @Override
                    public void run() {
                        updateSearchConditionInModel();
                    }
                });
            }
        }
    };

    ComparisonOperator[] supportedComparisonOperators = getSupportedComparisonOperators();
    if (supportedComparisonOperators == null)
        return null;

    for (ComparisonOperator compop : supportedComparisonOperators) {
        JMenuItem mi = new JRadioButtonMenuItem(
                getSpringLocaleDelegate().getMessage(compop.getResourceIdForLabel(), null));
        mi.setActionCommand(compop.name());
        mi.setToolTipText(getSpringLocaleDelegate().getMessage(compop.getResourceIdForDescription(), null));
        result.add(mi);
        btngrpComparisonOperators.add(mi);
        mi.addItemListener(itemlistener);
    }

    result.addPopupMenuListener(new PopupMenuListener() {
        @Override
        public void popupMenuWillBecomeVisible(PopupMenuEvent ev) {
            for (int i = 0, n = result.getComponentCount(); i < n; i++) {
                Component c = result.getComponent(i);
                if (c instanceof JMenuItem && StringUtils.emptyIfNull(((JMenuItem) c).getActionCommand())
                        .equals(getComparisonOperator().name()))
                    ((JMenuItem) c).setSelected(true);
            }
        }

        @Override
        public void popupMenuWillBecomeInvisible(PopupMenuEvent ev) {
        }

        @Override
        public void popupMenuCanceled(PopupMenuEvent ev) {
        }
    });

    // 2. right operand (value or other field):
    if (canDisplayComparisonWithOtherField()) {
        addRightOperandToPopupMenu(result, this);
    }

    return result;
}

From source file:it.isislab.dmason.tools.batch.BatchWizard.java

/**
 * Create the frame./*ww w.  j  a va 2  s.  co m*/
 */
public BatchWizard() {
    setPreferredSize(new Dimension(800, 600));
    setTitle("Batch wizard");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 849, 620);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(new GridLayout(1, 0, 0, 0));

    JPanel panel = new JPanel();
    panel.setToolTipText("");
    contentPane.add(panel);

    panel_1 = new JPanel();
    panel_1.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Param Option",
            TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));

    JPanel panel_2 = new JPanel();
    panel_2.setBorder(
            new TitledBorder(null, "Params List", TitledBorder.LEADING, TitledBorder.TOP, null, null));

    JPanel panel_3 = new JPanel();

    JPanel panel_4 = new JPanel();
    GroupLayout gl_panel = new GroupLayout(panel);
    gl_panel.setHorizontalGroup(gl_panel.createParallelGroup(Alignment.LEADING).addGroup(gl_panel
            .createSequentialGroup().addContainerGap()
            .addComponent(
                    panel_1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
                    .addGroup(gl_panel.createSequentialGroup()
                            .addComponent(panel_4, GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE).addGap(20))
                    .addGroup(gl_panel.createSequentialGroup()
                            .addComponent(panel_2, GroupLayout.DEFAULT_SIZE, 545, Short.MAX_VALUE).addGap(4))))
            .addComponent(panel_3, GroupLayout.DEFAULT_SIZE, 823, Short.MAX_VALUE));
    gl_panel.setVerticalGroup(gl_panel.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel
            .createSequentialGroup()
            .addComponent(panel_3, GroupLayout.PREFERRED_SIZE, 47, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel.createParallelGroup(Alignment.TRAILING)
                    .addGroup(gl_panel.createSequentialGroup()
                            .addComponent(panel_2, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
                                    Short.MAX_VALUE)
                            .addGap(25)
                            .addComponent(panel_4, GroupLayout.PREFERRED_SIZE, 38, GroupLayout.PREFERRED_SIZE))
                    .addComponent(panel_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap()));

    final JButton btnSave = new JButton("Save");
    btnSave.setEnabled(false);
    btnSave.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {

            File saveFile = SaveFileChooser();
            createXML(saveFile.getAbsoluteFile().getPath());
        }
    });

    lblTotTests = new JLabel(totTestsMessage);
    GroupLayout gl_panel_4 = new GroupLayout(panel_4);
    gl_panel_4.setHorizontalGroup(gl_panel_4.createParallelGroup(Alignment.TRAILING)
            .addGroup(gl_panel_4.createSequentialGroup().addGap(21).addComponent(lblTotTests)
                    .addPreferredGap(ComponentPlacement.RELATED, 515, Short.MAX_VALUE).addComponent(btnSave)
                    .addGap(21)));
    gl_panel_4.setVerticalGroup(gl_panel_4.createParallelGroup(Alignment.LEADING)
            .addGroup(gl_panel_4.createSequentialGroup().addContainerGap()
                    .addGroup(gl_panel_4.createParallelGroup(Alignment.BASELINE).addComponent(btnSave)
                            .addComponent(lblTotTests))
                    .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    panel_4.setLayout(gl_panel_4);

    top = new DefaultMutableTreeNode("Parameters");

    JScrollPane scrollPaneTree = new JScrollPane();

    JLabel lblNumberOfWorkers = new JLabel("Number of Workers:");

    textFieldNumberOfWorkers = new JTextField();
    textFieldNumberOfWorkers.setText("1");
    textFieldNumberOfWorkers.setColumns(10);
    textFieldNumberOfWorkers.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            if (textFieldNumberOfWorkers.isVisible()) {
                boolean checkNumberOfWorkers = true;

                while (checkNumberOfWorkers) {

                    String dist = textFieldNumberOfWorkers.getText();
                    boolean validateDist = dist.matches("(\\d)+");
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldNumberOfWorkers.setText(newDist);
                    }

                    else {
                        checkNumberOfWorkers = false;
                    }
                }
            }
        }
    });

    checkBoxLoadBalancing = new JCheckBox("Load Balancing", false);
    checkBoxLoadBalancing.setEnabled(true);

    GroupLayout gl_panel_2 = new GroupLayout(panel_2);
    gl_panel_2.setHorizontalGroup(gl_panel_2.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_2
            .createSequentialGroup().addContainerGap()
            .addGroup(gl_panel_2.createParallelGroup(Alignment.LEADING)
                    .addComponent(scrollPaneTree, GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                    .addGroup(gl_panel_2.createSequentialGroup().addComponent(lblNumberOfWorkers)
                            .addPreferredGap(ComponentPlacement.UNRELATED)
                            .addComponent(textFieldNumberOfWorkers, GroupLayout.PREFERRED_SIZE, 46,
                                    GroupLayout.PREFERRED_SIZE))
                    .addComponent(checkBoxLoadBalancing, GroupLayout.PREFERRED_SIZE, 114,
                            GroupLayout.PREFERRED_SIZE))
            .addContainerGap()));
    gl_panel_2.setVerticalGroup(gl_panel_2.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_2
            .createSequentialGroup().addContainerGap()
            .addComponent(scrollPaneTree, GroupLayout.PREFERRED_SIZE, 271, GroupLayout.PREFERRED_SIZE)
            .addGap(33)
            .addGroup(gl_panel_2.createParallelGroup(Alignment.BASELINE).addComponent(lblNumberOfWorkers)
                    .addComponent(textFieldNumberOfWorkers, GroupLayout.PREFERRED_SIZE,
                            GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addComponent(checkBoxLoadBalancing, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)
            .addContainerGap(56, Short.MAX_VALUE)));

    final JTree treeParams = new JTree(top);
    scrollPaneTree.setViewportView(treeParams);
    treeParams.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent selected) {
            // DefaultMutableTreeNode parent =
            // selected.getPath().getParentPath()

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) treeParams.getLastSelectedPathComponent();
            if (node.getParent() != null) {
                if (node.getParent() == simParams || node.getParent().equals(generalParams)) {

                    selectedParam = (Param) node.getUserObject();
                    if (node.getParent() == simParams) {
                        selectedParamIndex = simParams.getIndex(node);
                        paramType = "simParam";
                    }

                    else {
                        selectedParamIndex = generalParams.getIndex(node);
                        paramType = "generalParam";
                    }
                    if (selectedParam instanceof ParamFixed) {
                        ParamFixed pf = (ParamFixed) selectedParam;
                        lblParamType.setText(pf.getName() + ": " + pf.getType());
                        if (suggestion.get(pf.getName()) != null) {
                            lblDomain.setText("Domain: " + suggestion.get(pf.getName()).getDomain());
                            lblSuggested.setText(
                                    "Suggested Value: " + suggestion.get(pf.getName()).getSuggestedValue());
                        }

                        textFieldRuns.setText("" + pf.getRuns());
                        textFieldValue.setText(pf.getValue());
                        rdbtnFixed.doClick();

                        lblMessage.setVisible(false);
                        setModifyControlEnable(true);

                    }

                    if (selectedParam instanceof ParamRange) {
                        ParamRange pf = (ParamRange) selectedParam;
                        lblParamType.setText(pf.getName() + ": " + pf.getType());
                        if (suggestion.get(pf.getName()) != null) {
                            lblDomain.setText("Domain: " + suggestion.get(pf.getName()).getDomain());
                            lblSuggested.setText(
                                    "Suggested Value: " + suggestion.get(pf.getName()).getSuggestedValue());
                        }
                        textFieldRuns.setText("" + pf.getRuns());
                        textFieldStartValue.setText(pf.getStart());
                        textFieldEndValue.setText(pf.getEnd());
                        textFieldIncrement.setText(pf.getIncrement());
                        rdbtnRange.doClick();

                        lblMessage.setVisible(false);
                        setModifyControlEnable(true);
                    }

                    if (selectedParam instanceof ParamList) {
                        ParamList pl = (ParamList) selectedParam;
                        if (suggestion.get(pl.getName()) != null) {
                            lblDomain.setText("Domain: " + suggestion.get(pl.getName()).getDomain());
                            lblSuggested.setText(
                                    "Suggested Value: " + suggestion.get(pl.getName()).getSuggestedValue());
                        }
                        lblParamType.setText(pl.getName() + ": " + pl.getType());
                        textFieldRuns.setText("" + pl.getRuns());
                        StringBuilder b = new StringBuilder();
                        boolean isFirst = true;
                        for (String element : pl.getValues()) {
                            if (isFirst) {
                                b.append(element);
                                isFirst = false;
                            } else
                                b.append("," + element);
                        }
                        textFieldList.setText(b.toString());
                        rdbtnByvalues.doClick();

                        setListControlvisibility(true);
                        lblMessage.setVisible(false);
                        setModifyControlEnable(true);
                    }
                    if (selectedParam instanceof ParamDistribution) {
                        DistributionType distType = DistributionType.none;
                        if (selectedParam instanceof ParamDistributionUniform) {
                            ParamDistributionUniform pu = (ParamDistributionUniform) selectedParam;
                            lblParamType.setText(pu.getName() + ": " + pu.getType());
                            if (suggestion.get(pu.getName()) != null) {
                                lblDomain.setText("Domain: " + suggestion.get(pu.getName()).getDomain());
                                lblSuggested.setText(
                                        "Suggested Value: " + suggestion.get(pu.getName()).getSuggestedValue());
                            }

                            textFieldRuns.setText("" + pu.getRuns());
                            textFieldA.setText(pu.getA());
                            textFieldB.setText(pu.getB());
                            textFieldNumberOfValues.setText("" + pu.getNumberOfValues());
                            distType = DistributionType.uniform;
                        }
                        if (selectedParam instanceof ParamDistributionExponential) {
                            ParamDistributionExponential pe = (ParamDistributionExponential) selectedParam;
                            lblParamType.setText(pe.getName() + ": " + pe.getType());
                            if (suggestion.get(pe.getName()) != null) {

                                lblDomain.setText("Domain: " + suggestion.get(pe.getName()).getDomain());
                                lblSuggested.setText(
                                        "Suggested Value: " + suggestion.get(pe.getName()).getSuggestedValue());
                            }

                            textFieldRuns.setText("" + pe.getRuns());
                            textFieldA.setText(pe.getLambda());
                            textFieldNumberOfValues.setText("" + pe.getNumberOfValues());
                            distType = DistributionType.exponential;
                        }
                        if (selectedParam instanceof ParamDistributionNormal) {
                            ParamDistributionNormal pn = (ParamDistributionNormal) selectedParam;
                            lblParamType.setText(pn.getName() + ": " + pn.getType());
                            if (suggestion.get(pn.getName()) != null) {
                                lblDomain.setText("Domain: " + suggestion.get(pn.getName()).getDomain());
                                lblSuggested.setText(
                                        "Suggested Value: " + suggestion.get(pn.getName()).getSuggestedValue());
                            }

                            textFieldRuns.setText("" + pn.getRuns());
                            textFieldA.setText(pn.getMean());
                            textFieldB.setText(pn.getStdDev());
                            textFieldNumberOfValues.setText("" + pn.getNumberOfValues());
                            distType = DistributionType.normal;

                        }

                        rdbtnByDistribution.doClick();
                        setDistributionControlVisibility(distType);
                        setDistributionComboBoxVisibility(true);
                        lblMessage.setVisible(false);
                        setModifyControlEnable(true);
                    }
                }
            }
        }
    });

    panel_2.setLayout(gl_panel_2);

    JLabel lblSelectSimulationJar = new JLabel("Select simulation jar:");

    textFieldSimJarPath = new JTextField();
    textFieldSimJarPath.setColumns(10);

    btnLoadParams = new JButton("Load Params");
    btnLoadParams.setEnabled(false);
    btnLoadParams.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            ArrayList<Param> params = loadParams();
            if (params != null) {
                top.removeAllChildren();
                createNodes(top, params);
                treeParams.expandPath(new TreePath(top.getPath()));
                treeParams.expandPath(new TreePath(simParams.getPath()));
                treeParams.expandPath(new TreePath(generalParams.getPath()));
            }

            lblTotTests.setText(totTestsMessage + " " + getTotTests());
            btnSave.setEnabled(true);
        }
    });

    JButton bntChooseSimulation = new JButton();
    bntChooseSimulation.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            simulationFile = showFileChooser();
            if (simulationFile != null) {
                textFieldSimJarPath.setText(simulationFile.getAbsolutePath());
                btnLoadParams.setEnabled(true);

                isThin = isThinSimulation(simulationFile);
                checkBoxLoadBalancing.setEnabled(!isThin);

            }
        }

    });
    bntChooseSimulation.setIcon(
            new ImageIcon(BatchWizard.class.getResource("/it.isislab.dmason/resource/image/openFolder.png")));
    GroupLayout gl_panel_3 = new GroupLayout(panel_3);
    gl_panel_3.setHorizontalGroup(gl_panel_3.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_3
            .createSequentialGroup().addContainerGap().addComponent(lblSelectSimulationJar)
            .addPreferredGap(ComponentPlacement.RELATED)
            .addComponent(textFieldSimJarPath, GroupLayout.PREFERRED_SIZE, 250, GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addComponent(bntChooseSimulation, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
            .addGap(26).addComponent(btnLoadParams).addContainerGap(172, Short.MAX_VALUE)));
    gl_panel_3.setVerticalGroup(gl_panel_3.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_3
            .createSequentialGroup().addContainerGap()
            .addGroup(gl_panel_3.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_3
                    .createParallelGroup(Alignment.BASELINE).addComponent(lblSelectSimulationJar)
                    .addComponent(textFieldSimJarPath, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(bntChooseSimulation, GroupLayout.PREFERRED_SIZE, 25,
                            GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnLoadParams))
            .addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
    panel_3.setLayout(gl_panel_3);

    lblParamType = new JLabel("Param : type");
    lblParamType.setFont(new Font("Tahoma", Font.BOLD, 11));

    JLabel lblRuns = new JLabel("Runs:");
    textFieldRuns = new JTextField();
    textFieldRuns.setColumns(10);
    textFieldRuns.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            if (textFieldRuns.isVisible()) {
                boolean checkRuns = true;

                while (checkRuns) {

                    String dist = textFieldRuns.getText();
                    boolean validateDist = dist.matches("(\\d)+");
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldRuns.setText(newDist);
                    }

                    else {
                        checkRuns = false;
                    }
                }
            }
        }
    });
    JLabel lblParameterSpace = new JLabel("Parameter Space");
    lblParameterSpace.setFont(new Font("Tahoma", Font.BOLD, 11));

    lblValue = new JLabel("Value:");

    textFieldValue = new JTextField();
    textFieldValue.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            String regex = "(\\d)+|((\\d)+\\.(\\d)+)";
            if (textFieldValue.isVisible()) {
                boolean checkValue = true;

                while (checkValue) {

                    String dist = textFieldValue.getText();
                    boolean validateDist = dist.matches(regex);
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldValue.setText(newDist);
                    }

                    else {
                        checkValue = false;
                    }
                }
            }
        }
    });
    textFieldValue.setColumns(10);
    /*textFieldValue.addKeyListener(new KeyListener() {
            
       @Override
       public void keyTyped(KeyEvent arg0) {}
            
       @Override
       public void keyReleased(KeyEvent arg0) {
    checkError();
            
            
       }
            
       @Override
       public void keyPressed(KeyEvent arg0) {}
    });
    */
    lblStartValue = new JLabel("Start value:");

    textFieldStartValue = new JTextField();
    textFieldStartValue.setText("1");
    textFieldStartValue.setColumns(10);
    textFieldStartValue.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            String regex = "(\\d)+|((\\d)+\\.(\\d)+)";
            if (textFieldStartValue.isVisible()) {
                boolean checkStartValue = true;

                while (checkStartValue) {

                    String dist = textFieldStartValue.getText();
                    boolean validateDist = dist.matches(regex);
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldStartValue.setText(newDist);
                    }

                    else {
                        checkStartValue = false;
                    }
                }
            }
        }
    });

    lblEndValue = new JLabel("End value:");

    textFieldEndValue = new JTextField();
    textFieldEndValue.setText("1");
    textFieldEndValue.setColumns(10);
    textFieldEndValue.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            String regex = "(\\d)+|((\\d)+\\.(\\d)+)";
            if (textFieldEndValue.isVisible()) {
                boolean checkEndValue = true;

                while (checkEndValue) {

                    String dist = textFieldEndValue.getText();
                    boolean validateDist = dist.matches(regex);
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldEndValue.setText(newDist);
                    }

                    else {
                        checkEndValue = false;
                    }
                }
            }
        }
    });

    lblIncrement = new JLabel("Increment:");

    textFieldIncrement = new JTextField();
    textFieldIncrement.setText("1");
    textFieldIncrement.setColumns(10);
    textFieldIncrement.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            String regex = "(\\d)+|((\\d)+\\.(\\d)+)";
            if (textFieldIncrement.isVisible()) {

                boolean checkIncrement = true;

                while (checkIncrement) {

                    String dist = textFieldIncrement.getText();
                    boolean validateDist = dist.matches(regex);
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldIncrement.setText(newDist);
                    }

                    else {
                        checkIncrement = false;
                    }
                }
            }
        }
    });

    rdbtnFixed = new JRadioButton("Fixed");
    rdbtnFixed.setSelected(true);
    rdbtnFixed.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {

            setListControlvisibility(false);
            setDistributionComboBoxVisibility(false);
            setRangeControlVisibility(false);
            setFixedControlVisibility(true);
            setDistributionControlVisibility(DistributionType.none);
        }

    });

    rdbtnRange = new JRadioButton("Range");
    rdbtnRange.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setRangeControlVisibility(true);
            setFixedControlVisibility(false);
            setListControlvisibility(false);
            setDistributionComboBoxVisibility(false);
            setDistributionControlVisibility(DistributionType.none);
        }
    });

    rdbtnByvalues = new JRadioButton("By Values");
    rdbtnByvalues.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setRangeControlVisibility(false);
            setFixedControlVisibility(false);
            setListControlvisibility(true);
            setDistributionComboBoxVisibility(false);
            setDistributionControlVisibility(DistributionType.none);
        }
    });
    rdbtnByDistribution = new JRadioButton("By Distribution");
    rdbtnByDistribution.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            setRangeControlVisibility(false);
            setFixedControlVisibility(false);
            setListControlvisibility(false);
            setDistributionComboBoxVisibility(true);
            setDistributionControlVisibility(DistributionType.none);
        }
    });
    // Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(rdbtnFixed);
    group.add(rdbtnRange);
    group.add(rdbtnByvalues);
    group.add(rdbtnByDistribution);

    setRangeControlVisibility(false);
    setFixedControlVisibility(false);

    lblMessage = new JLabel(message);

    btnModify = new JButton("Modify");
    btnModify.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {

            if (rdbtnFixed.isSelected()) {
                ParamFixed param = new ParamFixed(selectedParam.getName(), selectedParam.getType(),
                        Integer.parseInt(textFieldRuns.getText()), textFieldValue.getText());
                DefaultMutableTreeNode p = new DefaultMutableTreeNode(param);

                if (paramType.equals("simParam")) {
                    simParams.remove(selectedParamIndex);

                    simParams.insert(p, selectedParamIndex);
                } else {
                    generalParams.remove(selectedParamIndex);

                    generalParams.insert(p, selectedParamIndex);
                }

                treeParams.updateUI();

                /*
                 * ((ParamFixed)
                 * selectedParam).setValue(textFieldValue.getText());
                 * selectedParam
                 * .setRuns(Integer.parseInt(textFieldRuns.getText()));
                 * treeParams.repaint();
                 */
            }
            if (rdbtnRange.isSelected()) {
                ParamRange param = new ParamRange(selectedParam.getName(), selectedParam.getType(),
                        Integer.parseInt(textFieldRuns.getText()), textFieldStartValue.getText(),
                        textFieldEndValue.getText(), textFieldIncrement.getText());
                DefaultMutableTreeNode p = new DefaultMutableTreeNode(param);

                if (paramType.equals("simParam")) {
                    simParams.remove(selectedParamIndex);

                    simParams.insert(p, selectedParamIndex);
                } else {
                    generalParams.remove(selectedParamIndex);

                    generalParams.insert(p, selectedParamIndex);
                }
                treeParams.updateUI();
                // treeParams.repaint();

            }
            if (rdbtnByvalues.isSelected()) {
                StringTokenizer st = new StringTokenizer(textFieldList.getText(), ",");
                ArrayList<String> values = new ArrayList<String>();
                while (st.hasMoreTokens())
                    values.add(st.nextToken());

                ParamList param = new ParamList(selectedParam.getName(), selectedParam.getType(),
                        Integer.parseInt(textFieldRuns.getText()), values);
                DefaultMutableTreeNode p = new DefaultMutableTreeNode(param);

                if (paramType.equals("simParam")) {
                    simParams.remove(selectedParamIndex);

                    simParams.insert(p, selectedParamIndex);
                } else {
                    generalParams.remove(selectedParamIndex);

                    generalParams.insert(p, selectedParamIndex);
                }
                treeParams.updateUI();
                // treeParams.repaint();

            }
            if (rdbtnByDistribution.isSelected()) {
                DefaultMutableTreeNode p;
                switch (selectedDistribution) {
                case uniform:

                    p = new DefaultMutableTreeNode(
                            new ParamDistributionUniform(selectedParam.getName(), selectedParam.getType(),
                                    Integer.parseInt(textFieldRuns.getText()), textFieldA.getText(),
                                    textFieldB.getText(), Integer.parseInt(textFieldNumberOfValues.getText())));
                    break;
                case exponential:

                    p = new DefaultMutableTreeNode(new ParamDistributionExponential(selectedParam.getName(),
                            selectedParam.getType(), Integer.parseInt(textFieldRuns.getText()),
                            textFieldA.getText(), Integer.parseInt(textFieldNumberOfValues.getText())));
                    break;

                case normal:

                    p = new DefaultMutableTreeNode(
                            new ParamDistributionNormal(selectedParam.getName(), selectedParam.getType(),
                                    Integer.parseInt(textFieldRuns.getText()), textFieldA.getText(),
                                    textFieldA.getText(), Integer.parseInt(textFieldNumberOfValues.getText())));
                    break;
                default:
                    p = new DefaultMutableTreeNode();
                    break;
                }

                if (paramType.equals("simParam")) {
                    simParams.remove(selectedParamIndex);

                    simParams.insert(p, selectedParamIndex);
                } else {
                    generalParams.remove(selectedParamIndex);

                    generalParams.insert(p, selectedParamIndex);
                }
                treeParams.updateUI();
                // treeParams.repaint();

            }
            lblMessage.setVisible(true);
            setModifyControlEnable(false);
            setDistributionControlVisibility(DistributionType.none);
            setDistributionComboBoxVisibility(false);
            setListControlvisibility(false);

            int tot = getTotTests();
            if (tot >= testAlertThreshold)
                lblTotTests.setForeground(Color.RED);
            else
                lblTotTests.setForeground(Color.BLACK);

            lblTotTests.setText(totTestsMessage + " " + tot);

        }
    });

    btnCancel = new JButton("Cancel");
    btnCancel.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            lblMessage.setVisible(true);
            setModifyControlEnable(false);

        }
    });

    lblCommaSeparatedList = new JLabel("List:");
    lblCommaSeparatedList.setVisible(false);

    textFieldList = new JTextField();
    textFieldList.setVisible(false);
    textFieldList.setToolTipText("Comma separated");
    textFieldList.setColumns(10);
    textFieldList.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            /*if(textFieldList.isVisible())
            {
            boolean checkList=true;
                    
            while(checkList){
                    
               String dist=textFieldList.getText();
               boolean validateDist=dist.matches("(\\d)+|((\\d)+\\.(\\d)+)(,(\\d)+|((\\d)+\\.(\\d)+))*");
               if(!validateDist){   
                  String   newDist=  JOptionPane.showInputDialog(null,"Insert comma separate number list","Number Format Error", 0);
                  textFieldList.setText(newDist);
               }
                    
               else{
                  checkList=false;
               }
            }
            }*/
        }
    });

    lblDistribution = new JLabel("Distribution");
    lblDistribution.setVisible(false);

    lblA = new JLabel("a:");
    lblA.setVisible(false);

    textFieldA = new JTextField();
    textFieldA.setText("1");
    textFieldA.setVisible(false);
    textFieldA.setColumns(10);
    textFieldA.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            String regex = "(\\d)+|((\\d)+\\.(\\d)+)";

            if (textFieldA.isVisible()) {
                boolean checkA = true;

                while (checkA) {

                    String dist = textFieldA.getText();
                    boolean validateDist = dist.matches(regex);
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldA.setText(newDist);
                    }

                    else {
                        checkA = false;
                    }
                }
            }
        }
    });

    lblB = new JLabel("b:");
    lblB.setVisible(false);

    textFieldB = new JTextField();
    textFieldB.setText("1");
    textFieldB.setVisible(false);
    textFieldB.setColumns(10);
    textFieldB.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {

            String regex = "(\\d)+|((\\d)+\\.(\\d)+)";
            if (textFieldB.isVisible()) {
                boolean checkB = true;

                while (checkB) {

                    String dist = textFieldB.getText();
                    boolean validateDist = dist.matches(regex);
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldB.setText(newDist);
                    }

                    else {
                        checkB = false;
                    }
                }
            }
        }
    });
    jComboBoxDistribution = new JComboBox();
    jComboBoxDistribution.setVisible(false);
    jComboBoxDistribution.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent e) {
            // Prevent executing listener's actions two times
            if (e.getStateChange() != ItemEvent.SELECTED)
                return;
            selectedDistribution = ((DistributionType) jComboBoxDistribution.getSelectedItem());

            setDistributionControlVisibility(DistributionType.none);
            setDistributionControlVisibility(selectedDistribution);

        }
    });

    lblOfValues = new JLabel("# of values:");
    lblOfValues.setVisible(false);

    textFieldNumberOfValues = new JTextField();
    textFieldNumberOfValues.setText("1");
    textFieldNumberOfValues.setVisible(false);
    textFieldNumberOfValues.setColumns(10);
    textFieldNumberOfValues.addFocusListener(new FocusAdapter() {
        @Override
        public void focusLost(FocusEvent arg0) {
            if (textFieldNumberOfValues.isVisible()) {
                boolean checkNumberOfValues = true;

                while (checkNumberOfValues) {

                    String dist = textFieldNumberOfValues.getText();
                    boolean validateDist = dist.matches("(\\d)+");
                    if (!validateDist) {
                        String newDist = JOptionPane.showInputDialog(null, "Insert a number",
                                "Number Format Error", 0);
                        textFieldNumberOfValues.setText(newDist);
                    }

                    else {
                        checkNumberOfValues = false;
                    }
                }
            }
        }
    });

    lblSuggested = new JLabel("Suggested Value:");

    lblDomain = new JLabel("Domain:");

    GroupLayout gl_panel_1 = new GroupLayout(panel_1);
    gl_panel_1.setHorizontalGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel_1
            .createSequentialGroup().addContainerGap()
            .addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING).addGroup(gl_panel_1
                    .createSequentialGroup()
                    .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addComponent(lblParamType)
                            .addComponent(lblMessage).addComponent(lblSuggested))
                    .addContainerGap(77, Short.MAX_VALUE))
                    .addGroup(gl_panel_1.createSequentialGroup().addComponent(btnModify)
                            .addPreferredGap(ComponentPlacement.RELATED).addComponent(btnCancel)
                            .addContainerGap())
                    .addGroup(gl_panel_1.createSequentialGroup().addGroup(gl_panel_1
                            .createParallelGroup(Alignment.LEADING).addComponent(lblParameterSpace)
                            .addGroup(gl_panel_1.createSequentialGroup()
                                    .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                            .addComponent(rdbtnFixed).addComponent(rdbtnRange))
                                    .addGap(31)
                                    .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                            .addComponent(rdbtnByDistribution).addComponent(rdbtnByvalues)))
                            .addGroup(gl_panel_1.createSequentialGroup().addGroup(gl_panel_1
                                    .createParallelGroup(Alignment.TRAILING)
                                    .addGroup(gl_panel_1.createSequentialGroup().addComponent(lblValue)
                                            .addPreferredGap(ComponentPlacement.RELATED, 59, Short.MAX_VALUE)
                                            .addComponent(textFieldValue, GroupLayout.PREFERRED_SIZE,
                                                    GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                    .addGroup(Alignment.LEADING,
                                            gl_panel_1.createSequentialGroup().addComponent(lblStartValue)
                                                    .addPreferredGap(ComponentPlacement.RELATED, 46,
                                                            Short.MAX_VALUE)
                                                    .addComponent(textFieldStartValue,
                                                            GroupLayout.PREFERRED_SIZE,
                                                            GroupLayout.DEFAULT_SIZE,
                                                            GroupLayout.PREFERRED_SIZE))
                                    .addGroup(gl_panel_1.createSequentialGroup()
                                            .addComponent(lblCommaSeparatedList)
                                            .addPreferredGap(ComponentPlacement.RELATED, 69, Short.MAX_VALUE)
                                            .addComponent(textFieldList, GroupLayout.PREFERRED_SIZE,
                                                    GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                                    .addGroup(gl_panel_1.createSequentialGroup()
                                            .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                                    .addComponent(lblEndValue).addComponent(lblIncrement)
                                                    .addComponent(lblDistribution))
                                            .addGap(45)
                                            .addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
                                                    .addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
                                                            .addGroup(gl_panel_1
                                                                    .createParallelGroup(Alignment.LEADING,
                                                                            false)
                                                                    .addComponent(jComboBoxDistribution, 0,
                                                                            GroupLayout.DEFAULT_SIZE,
                                                                            Short.MAX_VALUE)
                                                                    .addComponent(textFieldA,
                                                                            GroupLayout.PREFERRED_SIZE,
                                                                            GroupLayout.DEFAULT_SIZE,
                                                                            GroupLayout.PREFERRED_SIZE)
                                                                    .addComponent(textFieldB,
                                                                            GroupLayout.PREFERRED_SIZE,
                                                                            GroupLayout.DEFAULT_SIZE,
                                                                            GroupLayout.PREFERRED_SIZE)
                                                                    .addComponent(textFieldNumberOfValues,
                                                                            GroupLayout.PREFERRED_SIZE,
                                                                            GroupLayout.DEFAULT_SIZE,
                                                                            GroupLayout.PREFERRED_SIZE))
                                                            .addComponent(textFieldIncrement, 89, 89, 89))
                                                    .addComponent(textFieldEndValue, GroupLayout.PREFERRED_SIZE,
                                                            GroupLayout.DEFAULT_SIZE,
                                                            GroupLayout.PREFERRED_SIZE))))
                                    .addPreferredGap(ComponentPlacement.RELATED, 8, GroupLayout.PREFERRED_SIZE))
                            .addGroup(gl_panel_1.createSequentialGroup().addComponent(lblA).addPreferredGap(
                                    ComponentPlacement.RELATED, 173, GroupLayout.PREFERRED_SIZE))
                            .addGroup(gl_panel_1.createSequentialGroup().addComponent(lblB).addPreferredGap(
                                    ComponentPlacement.RELATED, 173, GroupLayout.PREFERRED_SIZE))
                            .addComponent(lblOfValues)
                            .addGroup(gl_panel_1.createSequentialGroup().addComponent(lblRuns)
                                    .addPreferredGap(ComponentPlacement.RELATED)
                                    .addComponent(textFieldRuns, GroupLayout.PREFERRED_SIZE,
                                            GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(ComponentPlacement.RELATED, 65,
                                            GroupLayout.PREFERRED_SIZE)))
                            .addGap(35))
                    .addGroup(gl_panel_1.createSequentialGroup().addComponent(lblDomain).addContainerGap(186,
                            Short.MAX_VALUE)))));
    gl_panel_1.setVerticalGroup(gl_panel_1.createParallelGroup(Alignment.LEADING).addGroup(gl_panel_1
            .createSequentialGroup().addGap(4).addComponent(lblMessage).addGap(18).addComponent(lblParamType)
            .addPreferredGap(ComponentPlacement.RELATED).addComponent(lblSuggested)
            .addPreferredGap(ComponentPlacement.RELATED).addComponent(lblDomain).addGap(7)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(lblRuns).addComponent(
                    textFieldRuns, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.RELATED).addComponent(lblParameterSpace)
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(rdbtnFixed)
                    .addComponent(rdbtnByvalues))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(rdbtnRange)
                    .addComponent(rdbtnByDistribution))
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                    .addComponent(textFieldValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblValue))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                    .addComponent(textFieldList, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblCommaSeparatedList))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(lblStartValue)
                    .addComponent(textFieldStartValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(lblEndValue).addComponent(
                    textFieldEndValue, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                    .addComponent(textFieldIncrement, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIncrement))
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE)
                    .addComponent(jComboBoxDistribution, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                            GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblDistribution))
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(gl_panel_1
                    .createParallelGroup(Alignment.BASELINE).addComponent(lblA).addComponent(textFieldA,
                            GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.RELATED)
            .addGroup(gl_panel_1
                    .createParallelGroup(Alignment.BASELINE).addComponent(lblB).addComponent(textFieldB,
                            GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.UNRELATED)
            .addGroup(gl_panel_1.createParallelGroup(Alignment.BASELINE).addComponent(lblOfValues).addComponent(
                    textFieldNumberOfValues, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE,
                    GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(ComponentPlacement.RELATED, 18, Short.MAX_VALUE).addGroup(gl_panel_1
                    .createParallelGroup(Alignment.BASELINE).addComponent(btnModify).addComponent(btnCancel))));
    panel_1.setLayout(gl_panel_1);
    panel.setLayout(gl_panel);

    setModifyControlEnable(false);
    loadDistribution();
}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

@Override
protected void setupSearchToolBar() {
    // additional functionality in Search panel:
    //final JPanel pnlCustomToolBarAreaSearch = new JPanel();
    //pnlCustomToolBarAreaSearch.setLayout(new GridBagLayout());

    super.setupSearchToolBar();

    //final JToolBar toolbarSearchCustom = newCustomSearchToolBar();
    if (SecurityCache.getInstance().isActionAllowed(Actions.ACTION_READ_DELETED_RECORD)) {
        //toolbarSearchCustom.add(Box.createHorizontalStrut(5));

        //cmbbxSearchDeleted.addItem(SpringLocaleDelegate.getMessage("GenericObjectCollectController.59","Nur ungel\u00f6schte suchen"));
        //cmbbxSearchDeleted.addItem(SpringLocaleDelegate.getMessage("GenericObjectCollectController.58","Nur gel\u00f6schte suchen"));
        //cmbbxSearchDeleted.addItem(SpringLocaleDelegate.getMessage("GenericObjectCollectController.49","Gel\u00f6schte und ungel\u00f6schte suchen"));

        btnGrpSearchDeleted.add(miSearchDeleted[0]);
        btnGrpSearchDeleted.add(miSearchDeleted[1]);
        btnGrpSearchDeleted.add(miSearchDeleted[2]);
        btnGrpSearchDeleted.setSelected(miSearchDeleted[0].getModel(), true);

        //UIUtils.setMaximumSizeToPreferredSize(cmbbxSearchDeleted);
        //toolbarSearchCustom.add(cmbbxSearchDeleted);
        //this.getSearchPanel().addToolBarComponent(cmbbxSearchDeleted);
        this.getSearchPanel().addPopupExtraSeparator();
        this.getSearchPanel().addPopupExtraMenuItem(miSearchDeleted[0]);
        this.getSearchPanel().addPopupExtraMenuItem(miSearchDeleted[1]);
        this.getSearchPanel().addPopupExtraMenuItem(miSearchDeleted[2]);

        /*cmbbxSearchDeleted.addItemListener(new ItemListener() {
           @Override//  w w w.ja  v a  2 s  .  c  om
           public void itemStateChanged(ItemEvent ev) {
              if (ev.getStateChange() == ItemEvent.SELECTED)
          iSearchDeleted = cmbbxSearchDeleted.getSelectedIndex();
           }
        });*/
        ItemListener il = new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent ev) {
                if (ev.getStateChange() == ItemEvent.SELECTED) {
                    for (int i = 0; i < miSearchDeleted.length; i++) {
                        if (ev.getSource() == miSearchDeleted[i])
                            iSearchDeleted = i;
                    }
                }
            }
        };
        miSearchDeleted[0].addItemListener(il);
        miSearchDeleted[1].addItemListener(il);
        miSearchDeleted[2].addItemListener(il);
    }

    refreshFilterView();

    // glue:
    //final JToolBar toolbarGlue = UIUtils.createNonFloatableToolBar();

    // add toolbars to custom toolbar area:
    /*final GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.VERTICAL;
    gbc.weightx = 0.0;
    gbc.weighty = 1.0;
    pnlCustomToolBarAreaSearch.add(toolbarSearchCustom, gbc);
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    pnlCustomToolBarAreaSearch.add(toolbarGlue, gbc);
    gbc.fill = GridBagConstraints.VERTICAL;
    gbc.weightx = 0.0;
    gbc.weighty = 1.0;
    JToolBar toolSearchState = UIUtils.createNonFloatableToolBar();
    */
    JComboBox jComboBox = getSearchStateBox().getJComboBox();
    //UIUtils.setMaximumSizeToPreferredSize(jComboBox);
    jComboBox.setToolTipText(
            getSpringLocaleDelegate().getMessage("GenericObjectCollectController.8", "Aktueller Status"));
    //jComboBox.setOpaque(false);
    //CenteringPanel cpSearchState = new CenteringPanel(jComboBox);
    //cpSearchState.setOpaque(false);
    //toolSearchState.add(cpSearchState);
    //toolSearchState.add(Box.createHorizontalStrut(5));
    ColoredLabel lbSearchBox = new ColoredLabel(jComboBox,
            getSpringLocaleDelegate().getMessage("nuclos.entityfield.eo.state.label", "Status"));
    lbSearchBox.setName("blSearchState");
    this.getSearchPanel().addToolBarComponent(lbSearchBox, 6);

    //pnlCustomToolBarAreaSearch.add(toolSearchState, gbc);
    setSearchStatesAccordingToUsageCriteria(new UsageCriteria(iModuleId, null, null, getCustomUsage()));
    //getSearchPanel().setCustomToolBarArea(pnlCustomToolBarAreaSearch);
}

From source file:org.broad.igv.hic.MainWindow.java

private JMenuBar createMenuBar(final JPanel hiCPanel) {

    JMenuBar menuBar = new JMenuBar();

    //======== fileMenu ========
    JMenu fileMenu = new JMenu("File");

    //---- loadMenuItem ----
    JMenuItem loadMenuItem = new JMenuItem();
    loadMenuItem.setText("Load...");
    loadMenuItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadMenuItemActionPerformed(e);
        }/*from  w  ww. j av  a 2  s. c  o  m*/
    });
    fileMenu.add(loadMenuItem);

    //---- loadFromURL ----
    JMenuItem loadFromURL = new JMenuItem();
    JMenuItem getEigenvector = new JMenuItem();
    final JCheckBoxMenuItem viewDNAseI;

    loadFromURL.setText("Load from URL ...");
    loadFromURL.setName("loadFromURL");
    loadFromURL.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            loadFromURLActionPerformed(e);
        }
    });
    fileMenu.add(loadFromURL);
    fileMenu.addSeparator();

    // Pre-defined datasets.  TODO -- generate from a file
    addPredefinedLoadItems(fileMenu);

    JMenuItem saveToImage = new JMenuItem();
    saveToImage.setText("Save to image");
    saveToImage.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            BufferedImage image = (BufferedImage) createImage(1000, 1000);
            Graphics g = image.createGraphics();
            hiCPanel.paint(g);

            JFileChooser fc = new JFileChooser();
            fc.setSelectedFile(new File("image.png"));
            int actionDialog = fc.showSaveDialog(null);
            if (actionDialog == JFileChooser.APPROVE_OPTION) {
                File file = fc.getSelectedFile();
                if (file.exists()) {
                    actionDialog = JOptionPane.showConfirmDialog(null, "Replace existing file?");
                    if (actionDialog == JOptionPane.NO_OPTION || actionDialog == JOptionPane.CANCEL_OPTION)
                        return;
                }
                try {
                    // default if they give no format or invalid format
                    String fmt = "jpg";
                    int ind = file.getName().indexOf(".");
                    if (ind != -1) {
                        String ext = file.getName().substring(ind + 1);
                        String[] strs = ImageIO.getWriterFormatNames();
                        for (String aStr : strs)
                            if (ext.equals(aStr))
                                fmt = ext;
                    }
                    ImageIO.write(image.getSubimage(0, 0, 600, 600), fmt, file);
                } catch (IOException ie) {
                    System.err.println("Unable to write " + file + ": " + ie);
                }
            }
        }
    });
    fileMenu.add(saveToImage);
    getEigenvector = new JMenuItem("Get principal eigenvector");
    getEigenvector.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            getEigenvectorActionPerformed(e);
        }
    });
    fileMenu.add(getEigenvector);
    //---- exit ----
    JMenuItem exit = new JMenuItem();
    exit.setText("Exit");
    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            exitActionPerformed(e);
        }
    });
    fileMenu.add(exit);

    menuBar.add(fileMenu);

    //======== Tracks menu ========

    JMenu tracksMenu = new JMenu("Tracks");

    viewEigenvector = new JCheckBoxMenuItem("View Eigenvector...");
    viewEigenvector.addItemListener(new ItemListener() {
        public void itemStateChanged(ItemEvent e) {
            if (viewEigenvector.isSelected()) {
                if (eigenvectorTrack == null) {
                    eigenvectorTrack = new EigenvectorTrack("eigen", "Eigenvectors");
                }
                updateEigenvectorTrack();
            } else {
                trackPanel.setEigenvectorTrack(null);
                if (HiCTrackManager.getLoadedTracks().isEmpty()) {
                    trackPanel.setVisible(false);
                }
            }
        }
    });
    viewEigenvector.setEnabled(false);
    tracksMenu.add(viewEigenvector);

    JMenuItem loadItem = new JMenuItem("Load...");
    loadItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadHostedTrack(MainWindow.this);
        }

    });
    tracksMenu.add(loadItem);

    JMenuItem loadFromFileItem = new JMenuItem("Load from file...");
    loadFromFileItem.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            HiCTrackManager.loadTrackFromFile(MainWindow.this);
        }

    });
    tracksMenu.add(loadFromFileItem);

    menuBar.add(tracksMenu);

    //======== Extras menu ========
    JMenu extrasMenu = new JMenu("Extras");

    JMenuItem dumpPearsons = new JMenuItem("Dump pearsons matrix ...");
    dumpPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            BasicMatrix pearsons = hic.zd.getPearsons();
            try {
                String chr1 = hic.getChromosomes()[hic.zd.getChr1()].getName();
                String chr2 = hic.getChromosomes()[hic.zd.getChr2()].getName();
                int binSize = hic.zd.getBinSize();
                File initFile = new File("pearsons_" + chr1 + "_" + "_" + chr2 + "_" + binSize + ".bin");
                File f = FileDialogUtils.chooseFile("Save pearsons", null, initFile, FileDialogUtils.SAVE);
                if (f != null) {
                    ScratchPad.dumpPearsonsBinary(pearsons, chr1, chr2, hic.zd.getBinSize(), f);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });

    JMenuItem dumpEigenvector = new JMenuItem("Dump eigenvector ...");
    dumpEigenvector.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                ScratchPad.dumpEigenvector(hic);
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(dumpEigenvector);

    JMenuItem readPearsons = new JMenuItem("Read pearsons...");
    readPearsons.addActionListener(new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent actionEvent) {
            try {
                File f = FileDialogUtils.chooseFile("Pearsons file (Yunfan format)");
                if (f != null) {
                    BasicMatrix bm = ScratchPad.readPearsons(f.getAbsolutePath());

                    hic.zd.setPearsons(bm);
                }
            } catch (IOException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
        }

    });
    extrasMenu.add(readPearsons);

    extrasMenu.add(dumpPearsons);
    menuBar.add(extrasMenu);

    return menuBar;
}

From source file:com.declarativa.interprolog.gui.Ini2.java

private void graphComponents() throws IOException {

    Forest<String, Integer> forest = new DelegateForest<>();
    ObservableGraph g = new ObservableGraph(new BalloonLayoutDemo().createTree(forest));

    Layout layout = new BalloonLayout(forest);
    //Layout layout = new TreeLayout(forest, 70, 70);

    final BaseJungScene scene = new SceneImpl(g, layout);

    jLayeredPane1.setLayout(new BorderLayout());
    //jf.setLayout(new BorderLayout());

    jLayeredPane1.add(new JScrollPane(scene.createView()), BorderLayout.CENTER);
    //jf.add(new JScrollPane(scene.createView()), BorderLayout.CENTER);

    JToolBar bar = new JToolBar();
    bar.setMargin(new Insets(5, 5, 5, 5));
    bar.setLayout(new FlowLayout(5));
    DefaultComboBoxModel<Layout> mdl = new DefaultComboBoxModel<>();
    mdl.addElement(new KKLayout(g));
    mdl.addElement(layout);//  w  w w . ja  v a 2s  . c  o  m
    mdl.addElement(new BalloonLayout(forest));
    mdl.addElement(new RadialTreeLayout(forest));
    mdl.addElement(new CircleLayout(g));
    mdl.addElement(new FRLayout(g));
    mdl.addElement(new FRLayout2(g));
    mdl.addElement(new ISOMLayout(g));
    mdl.addElement(new SpringLayout(g));
    mdl.addElement(new SpringLayout2(g));
    mdl.addElement(new DAGLayout(g));
    mdl.addElement(new XLayout(g));
    mdl.setSelectedItem(layout);
    final JCheckBox checkbox = new JCheckBox("Animate iterative layouts");

    scene.setLayoutAnimationFramesPerSecond(48);

    final JComboBox<Layout> layouts = new JComboBox(mdl);
    layouts.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList<?> jlist, Object o, int i, boolean bln,
                boolean bln1) {
            o = o.getClass().getSimpleName();
            return super.getListCellRendererComponent(jlist, o, i, bln, bln1); //To change body of generated methods, choose Tools | Templates.
        }
    });
    bar.add(new JLabel(" Layout Type"));
    bar.add(layouts);
    layouts.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            Layout layout = (Layout) layouts.getSelectedItem();
            // These two layouts implement IterativeContext, but they do
            // not evolve toward anything, they just randomly rearrange
            // themselves.  So disable animation for these.
            if (layout instanceof ISOMLayout || layout instanceof DAGLayout) {
                checkbox.setSelected(false);
            }
            scene.setGraphLayout(layout, true);
        }
    });

    bar.add(new JLabel(" Connection Shape"));
    DefaultComboBoxModel<Transformer<Context<Graph<String, Number>, Number>, Shape>> shapes = new DefaultComboBoxModel<>();
    shapes.addElement(new EdgeShape.QuadCurve<String, Number>());
    shapes.addElement(new EdgeShape.BentLine<String, Number>());
    shapes.addElement(new EdgeShape.CubicCurve<String, Number>());
    shapes.addElement(new EdgeShape.Line<String, Number>());
    shapes.addElement(new EdgeShape.Box<String, Number>());
    shapes.addElement(new EdgeShape.Orthogonal<String, Number>());
    shapes.addElement(new EdgeShape.Wedge<String, Number>(10));

    final JComboBox<Transformer<Context<Graph<String, Number>, Number>, Shape>> shapesBox = new JComboBox<>(
            shapes);
    shapesBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            Transformer<Context<Graph<String, Number>, Number>, Shape> xform = (Transformer<Context<Graph<String, Number>, Number>, Shape>) shapesBox
                    .getSelectedItem();
            scene.setConnectionEdgeShape(xform);
        }
    });
    shapesBox.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList<?> jlist, Object o, int i, boolean bln,
                boolean bln1) {
            o = o.getClass().getSimpleName();
            return super.getListCellRendererComponent(jlist, o, i, bln, bln1); //To change body of generated methods, choose Tools | Templates.
        }
    });
    shapesBox.setSelectedItem(new EdgeShape.QuadCurve<>());
    bar.add(shapesBox);

    //jf.add(bar, BorderLayout.NORTH);

    bar.add(new MinSizePanel(scene.createSatelliteView()));
    bar.setFloatable(false);
    bar.setRollover(true);

    final JLabel selectionLabel = new JLabel("<html>&nbsp;</html>");
    System.out.println("LOOKUP IS " + scene.getLookup());
    Lookup.Result<String> selectedNodes = scene.getLookup().lookupResult(String.class);
    LookupListener listener = new LookupListener() {
        @Override
        public void resultChanged(LookupEvent le) {
            System.out.println("RES CHANGED");
            Lookup.Result<String> res = (Lookup.Result<String>) le.getSource();
            StringBuilder sb = new StringBuilder("<html>");
            List<String> l = new ArrayList<>(res.allInstances());
            Collections.sort(l);
            for (String s : l) {
                if (sb.length() != 0) {
                    sb.append(", ");
                }
                sb.append(s);
            }
            sb.append("</html>");
            selectionLabel.setText(sb.toString());
            System.out.println("LOOKUP EVENT " + sb);
        }
    };
    selectedNodes.addLookupListener(listener);
    selectedNodes.allInstances();

    bar.add(selectionLabel);

    checkbox.setSelected(true);
    checkbox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            scene.setAnimateIterativeLayouts(checkbox.isSelected());
        }
    });
    bar.add(checkbox);
    jLayeredPane3.setLayout(new BorderLayout());

    jLayeredPane3.add(bar);
    //        jf.setSize(jf.getGraphicsConfiguration().getBounds().width - 120, 700);
    //        jf.setSize(new Dimension(1280, 720));
    //        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent we) {
            scene.relayout(true);
            scene.validate();
        }
    });

}

From source file:net.pms.newgui.NavigationShareTab.java

private PanelBuilder initSharedFoldersGuiComponents(CellConstraints cc) {
    // Apply the orientation for the locale
    ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale());
    String colSpec = FormLayoutUtil.getColSpec(SHARED_FOLDER_COL_SPEC, orientation);

    FormLayout layoutFolders = new FormLayout(colSpec, SHARED_FOLDER_ROW_SPEC);
    PanelBuilder builderFolder = new PanelBuilder(layoutFolders);
    builderFolder.opaque(true);//from w  w w .  ja v a2 s .  c o m

    JComponent cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"),
            FormLayoutUtil.flip(cc.xyw(1, 1, 7), colSpec, orientation));
    cmp = (JComponent) cmp.getComponent(0);
    cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));

    folderTableModel = new SharedFoldersTableModel();
    sharedFolders = new JTable(folderTableModel);

    JPopupMenu popupMenu = new JPopupMenu();
    JMenuItem menuItemMarkPlayed = new JMenuItem(Messages.getString("FoldTab.75"));
    JMenuItem menuItemMarkUnplayed = new JMenuItem(Messages.getString("FoldTab.76"));

    menuItemMarkPlayed.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String path = (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0);
            TableFilesStatus.setDirectoryFullyPlayed(path, true);
        }
    });

    menuItemMarkUnplayed.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String path = (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0);
            TableFilesStatus.setDirectoryFullyPlayed(path, false);
        }
    });

    popupMenu.add(menuItemMarkPlayed);
    popupMenu.add(menuItemMarkUnplayed);

    sharedFolders.setComponentPopupMenu(popupMenu);

    /* An attempt to set the correct row height adjusted for font scaling.
     * It sets all rows based on the font size of cell (0, 0). The + 4 is
     * to allow 2 pixels above and below the text. */
    DefaultTableCellRenderer cellRenderer = (DefaultTableCellRenderer) sharedFolders.getCellRenderer(0, 0);
    FontMetrics metrics = cellRenderer.getFontMetrics(cellRenderer.getFont());
    sharedFolders.setRowHeight(metrics.getLeading() + metrics.getMaxAscent() + metrics.getMaxDescent() + 4);
    sharedFolders.setIntercellSpacing(new Dimension(8, 2));

    final JPanel tmpsharedPanel = sharedPanel;

    addButton.setToolTipText(Messages.getString("FoldTab.9"));
    addButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            JFileChooser chooser;
            try {
                chooser = new JFileChooser();
            } catch (Exception ee) {
                chooser = new JFileChooser(new RestrictedFileSystemView());
            }
            chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
            int returnVal = chooser.showOpenDialog((Component) e.getSource());
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                int firstSelectedRow = sharedFolders.getSelectedRow();
                if (firstSelectedRow >= 0) {
                    ((SharedFoldersTableModel) sharedFolders.getModel()).insertRow(firstSelectedRow,
                            new Object[] { chooser.getSelectedFile().getAbsolutePath(), true });
                } else {
                    ((SharedFoldersTableModel) sharedFolders.getModel())
                            .addRow(new Object[] { chooser.getSelectedFile().getAbsolutePath(), true });
                }
            }
        }
    });
    builderFolder.add(addButton, FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation));

    removeButton.setToolTipText(Messages.getString("FoldTab.36"));
    removeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            int[] rows = sharedFolders.getSelectedRows();
            if (rows.length > 0) {
                if (rows.length > 1) {
                    if (JOptionPane.showConfirmDialog(tmpsharedPanel,
                            String.format(Messages.getString("SharedFolders.ConfirmRemove"), rows.length),
                            Messages.getString("Dialog.Confirm"), JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) {
                        return;
                    }
                }
                for (int i = rows.length - 1; i >= 0; i--) {
                    PMS.get().getDatabase().removeMediaEntriesInFolder(
                            (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0));
                    ((SharedFoldersTableModel) sharedFolders.getModel()).removeRow(rows[i]);
                }
            }
        }
    });
    builderFolder.add(removeButton, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation));

    arrowDownButton.setToolTipText(Messages.getString("SharedFolders.ArrowDown"));
    arrowDownButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < sharedFolders.getRowCount() - 1; i++) {
                if (sharedFolders.isRowSelected(i)) {
                    Object value1 = sharedFolders.getValueAt(i, 0);
                    boolean value2 = (boolean) sharedFolders.getValueAt(i, 1);

                    sharedFolders.setValueAt(sharedFolders.getValueAt(i + 1, 0), i, 0);
                    sharedFolders.setValueAt(value1, i + 1, 0);
                    sharedFolders.setValueAt(sharedFolders.getValueAt(i + 1, 1), i, 1);
                    sharedFolders.setValueAt(value2, i + 1, 1);
                    sharedFolders.changeSelection(i + 1, 1, false, false);

                    break;
                }
            }
        }
    });
    builderFolder.add(arrowDownButton, FormLayoutUtil.flip(cc.xy(4, 3), colSpec, orientation));

    arrowUpButton.setToolTipText(Messages.getString("SharedFolders.ArrowUp"));
    arrowUpButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            for (int i = 1; i < sharedFolders.getRowCount(); i++) {
                if (sharedFolders.isRowSelected(i)) {
                    Object value1 = sharedFolders.getValueAt(i, 0);
                    boolean value2 = (boolean) sharedFolders.getValueAt(i, 1);

                    sharedFolders.setValueAt(sharedFolders.getValueAt(i - 1, 0), i, 0);
                    sharedFolders.setValueAt(value1, i - 1, 0);
                    sharedFolders.setValueAt(sharedFolders.getValueAt(i - 1, 1), i, 1);
                    sharedFolders.setValueAt(value2, i - 1, 1);
                    sharedFolders.changeSelection(i - 1, 1, false, false);

                    break;

                }
            }
        }
    });
    builderFolder.add(arrowUpButton, FormLayoutUtil.flip(cc.xy(5, 3), colSpec, orientation));

    scanButton.setToolTipText(Messages.getString("FoldTab.2"));
    scanBusyIcon.start();
    scanBusyDisabledIcon.start();
    scanButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            if (configuration.getUseCache()) {
                DLNAMediaDatabase database = PMS.get().getDatabase();

                if (database != null) {
                    if (database.isScanLibraryRunning()) {
                        int option = JOptionPane.showConfirmDialog(looksFrame, Messages.getString("FoldTab.10"),
                                Messages.getString("Dialog.Question"), JOptionPane.YES_NO_OPTION);
                        if (option == JOptionPane.YES_OPTION) {
                            database.stopScanLibrary();
                            looksFrame.setStatusLine(Messages.getString("FoldTab.41"));
                            scanButton.setEnabled(false);
                            scanButton.setToolTipText(Messages.getString("FoldTab.41"));
                        }
                    } else {
                        database.scanLibrary();
                        scanButton.setIcon(scanBusyIcon);
                        scanButton.setRolloverIcon(scanBusyRolloverIcon);
                        scanButton.setPressedIcon(scanBusyPressedIcon);
                        scanButton.setDisabledIcon(scanBusyDisabledIcon);
                        scanButton.setToolTipText(Messages.getString("FoldTab.40"));
                    }
                }
            }
        }
    });

    /*
     * Hide the scan button in basic mode since it's better to let it be done in
     * realtime.
     */
    if (!configuration.isHideAdvancedOptions()) {
        builderFolder.add(scanButton, FormLayoutUtil.flip(cc.xy(6, 3), colSpec, orientation));
    }

    scanButton.setEnabled(configuration.getUseCache());

    isScanSharedFoldersOnStartup = new JCheckBox(Messages.getString("NetworkTab.StartupScan"),
            configuration.isScanSharedFoldersOnStartup());
    isScanSharedFoldersOnStartup.setToolTipText(Messages.getString("NetworkTab.StartupScanTooltip"));
    isScanSharedFoldersOnStartup.setContentAreaFilled(false);
    isScanSharedFoldersOnStartup.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            configuration.setScanSharedFoldersOnStartup((e.getStateChange() == ItemEvent.SELECTED));
        }
    });

    builderFolder.add(isScanSharedFoldersOnStartup, FormLayoutUtil.flip(cc.xy(7, 3), colSpec, orientation));

    updateSharedFolders();

    JScrollPane pane = new JScrollPane(sharedFolders);
    Dimension d = sharedFolders.getPreferredSize();
    pane.setPreferredSize(new Dimension(d.width, sharedFolders.getRowHeight() * 2));
    builderFolder.add(pane, FormLayoutUtil.flip(cc.xyw(1, 5, 7, CellConstraints.DEFAULT, CellConstraints.FILL),
            colSpec, orientation));

    return builderFolder;
}

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  ww.  java2  s. com*/
            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:op.care.supervisor.PnlHandover.java

private List<Component> addFilters() {
    List<Component> list = new ArrayList<Component>();

    Pair<DateTime, DateTime> minmax = NReportTools.getMinMax();
    if (minmax != null) {
        final DefaultComboBoxModel yearModel = new DefaultComboBoxModel();
        for (int year = new LocalDate().getYear(); year >= minmax.getFirst().getYear(); year--) {
            yearModel.addElement(year);//w w  w  .  jav a  2s  . c  o m
        }

        JPanel innerPanel = new JPanel();
        innerPanel.setOpaque(false);
        innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.PAGE_AXIS));
        txtSearch = new JXSearchField(SYSTools.xx("misc.msg.searchphrase"));
        txtSearch.setInstantSearchDelay(100000);
        txtSearch.setFont(SYSConst.ARIAL14);
        txtSearch.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (SYSTools.catchNull(txtSearch.getText()).trim().length() > 3) {
                    SYSFilesTools.print(NReportTools.getReportsAndHandoversAsHTML(
                            NReportTools.getNReports4Handover((Homes) cmbHomes.getSelectedItem(),
                                    txtSearch.getText().trim(),
                                    Integer.parseInt(yearModel.getSelectedItem().toString())),
                            txtSearch.getText().trim(),
                            Integer.parseInt(yearModel.getSelectedItem().toString())), false);
                }
            }
        });
        innerPanel.add(txtSearch);
        JButton btnSearchGeneralReports = GUITools
                .createHyperlinkButton("nursingrecords.handover.searchHandovers", null, null);
        btnSearchGeneralReports.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                List listHandovers = HandoversTools.getBy(
                        Integer.parseInt(yearModel.getSelectedItem().toString()),
                        (Homes) cmbHomes.getSelectedItem());
                SYSFilesTools.print(NReportTools.getReportsAndHandoversAsHTML(listHandovers, "",
                        Integer.parseInt(yearModel.getSelectedItem().toString())), false);
            }
        });
        innerPanel.add(btnSearchGeneralReports);
        yearCombo = new JXComboBox(yearModel);
        yearCombo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                txtSearch.postActionEvent();
            }
        });

        JPanel myPanel = new JPanel();
        myPanel.setOpaque(false);
        myPanel.setLayout(new BoxLayout(myPanel, BoxLayout.LINE_AXIS));
        myPanel.add(innerPanel);
        myPanel.add(yearCombo);
        list.add(myPanel);
    }

    cmbHomes = new JComboBox();
    cmbHomes.setFont(SYSConst.ARIAL14);
    HomesTools.setComboBox(cmbHomes);
    cmbHomes.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent itemEvent) {
            if (itemEvent.getStateChange() != ItemEvent.SELECTED)
                return;
            reloadDisplay();
        }
    });
    list.add(cmbHomes);

    tbResidentFirst = GUITools.getNiceToggleButton("nursingrecords.handover.residentFirst");
    SYSPropsTools.restoreState("nursingrecords.handover.tbResidentFirst", tbResidentFirst);
    tbResidentFirst.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            SYSPropsTools.storeState("nursingrecords.handover.tbResidentFirst", tbResidentFirst);
            reload();
        }
    });
    tbResidentFirst.setHorizontalAlignment(SwingConstants.LEFT);
    list.add(tbResidentFirst);

    return list;
}

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

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

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

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

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

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

            NetPlan netPlan = callback.getDesign();

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

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

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

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

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

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

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

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

    });
    options.add(setServiceTypes);

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

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

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

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

                    layerSelector.setSelectedIndex(0);

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

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

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

            options.add(createUpperLayerLinkFromDemandItem);

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

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

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

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

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

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

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

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

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

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

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

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

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

            options.add(coupleDemandToLink);
        }

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

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

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

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

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

                        layerSelector.setSelectedIndex(0);

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

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

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

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

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

        }
    }

    return options;
}

From source file:com.declarativa.interprolog.gui.Ini3.java

private void graphComponents() throws IOException {

    Forest<String, Integer> forest = new DelegateForest<>();
    ObservableGraph g = new ObservableGraph(new BalloonLayoutDemo().createTree(forest));

    Layout layout = new BalloonLayout(forest);
    //Layout layout = new TreeLayout(forest, 70, 70);

    final BaseJungScene scene = new SceneImpl(g, layout);

    jLayeredPane1.setLayout(new BorderLayout());
    //jf.setLayout(new BorderLayout());

    jLayeredPane1.add(new JScrollPane(scene.createView()), BorderLayout.CENTER);
    //jf.add(new JScrollPane(scene.createView()), BorderLayout.CENTER);

    JToolBar bar = new JToolBar();
    bar.setMargin(new Insets(5, 5, 5, 5));
    bar.setLayout(new FlowLayout(5));
    DefaultComboBoxModel<Layout> mdl = new DefaultComboBoxModel<>();
    mdl.addElement(new KKLayout(g));
    mdl.addElement(layout);/* w w w .  ja  va  2  s .co  m*/
    mdl.addElement(new BalloonLayout(forest));
    mdl.addElement(new RadialTreeLayout(forest));
    mdl.addElement(new CircleLayout(g));
    mdl.addElement(new FRLayout(g));
    mdl.addElement(new FRLayout2(g));
    mdl.addElement(new ISOMLayout(g));
    mdl.addElement(new SpringLayout(g));
    mdl.addElement(new SpringLayout2(g));
    mdl.addElement(new DAGLayout(g));
    mdl.addElement(new XLayout(g));
    mdl.setSelectedItem(layout);
    final JCheckBox checkbox = new JCheckBox("Animate iterative layouts");

    scene.setLayoutAnimationFramesPerSecond(48);

    final JComboBox<Layout> layouts = new JComboBox(mdl);
    layouts.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList<?> jlist, Object o, int i, boolean bln,
                boolean bln1) {
            o = o.getClass().getSimpleName();
            return super.getListCellRendererComponent(jlist, o, i, bln, bln1); //To change body of generated methods, choose Tools | Templates.
        }
    });
    bar.add(new JLabel(" Layout Type"));
    bar.add(layouts);
    layouts.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            Layout layout = (Layout) layouts.getSelectedItem();
            // These two layouts implement IterativeContext, but they do
            // not evolve toward anything, they just randomly rearrange
            // themselves.  So disable animation for these.
            if (layout instanceof ISOMLayout || layout instanceof DAGLayout) {
                checkbox.setSelected(false);
            }
            scene.setGraphLayout(layout, true);
        }
    });

    bar.add(new JLabel(" Connection Shape"));
    DefaultComboBoxModel<Transformer<Context<Graph<String, Number>, Number>, Shape>> shapes = new DefaultComboBoxModel<>();
    shapes.addElement(new EdgeShape.QuadCurve<String, Number>());
    shapes.addElement(new EdgeShape.BentLine<String, Number>());
    shapes.addElement(new EdgeShape.CubicCurve<String, Number>());
    shapes.addElement(new EdgeShape.Line<String, Number>());
    shapes.addElement(new EdgeShape.Box<String, Number>());
    shapes.addElement(new EdgeShape.Orthogonal<String, Number>());
    shapes.addElement(new EdgeShape.Wedge<String, Number>(10));

    final JComboBox<Transformer<Context<Graph<String, Number>, Number>, Shape>> shapesBox = new JComboBox<>(
            shapes);
    shapesBox.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent ae) {
            Transformer<Context<Graph<String, Number>, Number>, Shape> xform = (Transformer<Context<Graph<String, Number>, Number>, Shape>) shapesBox
                    .getSelectedItem();
            scene.setConnectionEdgeShape(xform);
        }
    });
    shapesBox.setRenderer(new DefaultListCellRenderer() {
        @Override
        public Component getListCellRendererComponent(JList<?> jlist, Object o, int i, boolean bln,
                boolean bln1) {
            o = o.getClass().getSimpleName();
            return super.getListCellRendererComponent(jlist, o, i, bln, bln1); //To change body of generated methods, choose Tools | Templates.
        }
    });
    shapesBox.setSelectedItem(new EdgeShape.QuadCurve<>());
    bar.add(shapesBox);

    //jf.add(bar, BorderLayout.NORTH);
    bar.add(new MinSizePanel(scene.createSatelliteView()));
    bar.setFloatable(false);
    bar.setRollover(true);

    final JLabel selectionLabel = new JLabel("<html>&nbsp;</html>");
    System.out.println("LOOKUP IS " + scene.getLookup());
    Lookup.Result<String> selectedNodes = scene.getLookup().lookupResult(String.class);
    LookupListener listener = new LookupListener() {
        @Override
        public void resultChanged(LookupEvent le) {
            System.out.println("RES CHANGED");
            Lookup.Result<String> res = (Lookup.Result<String>) le.getSource();
            StringBuilder sb = new StringBuilder("<html>");
            List<String> l = new ArrayList<>(res.allInstances());
            Collections.sort(l);
            for (String s : l) {
                if (sb.length() != 0) {
                    sb.append(", ");
                }
                sb.append(s);
            }
            sb.append("</html>");
            selectionLabel.setText(sb.toString());
            System.out.println("LOOKUP EVENT " + sb);
        }
    };
    selectedNodes.addLookupListener(listener);
    selectedNodes.allInstances();

    bar.add(selectionLabel);

    checkbox.setSelected(true);
    checkbox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            scene.setAnimateIterativeLayouts(checkbox.isSelected());
        }
    });
    bar.add(checkbox);
    jLayeredPane3.setLayout(new BorderLayout());

    jLayeredPane3.add(bar);
    //        jf.setSize(jf.getGraphicsConfiguration().getBounds().width - 120, 700);
    //        jf.setSize(new Dimension(1280, 720));
    //        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    this.addWindowListener(new WindowAdapter() {
        @Override
        public void windowOpened(WindowEvent we) {
            scene.relayout(true);
            scene.validate();
        }
    });

}