Example usage for javax.swing.tree DefaultMutableTreeNode getUserObject

List of usage examples for javax.swing.tree DefaultMutableTreeNode getUserObject

Introduction

In this page you can find the example usage for javax.swing.tree DefaultMutableTreeNode getUserObject.

Prototype

public Object getUserObject() 

Source Link

Document

Returns this node's user object.

Usage

From source file:edu.harvard.i2b2.previousquery.ui.PreviousQueryPanel.java

public void treeExpanded(TreeExpansionEvent event) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) event.getPath().getLastPathComponent();
    QueryData data = (QueryData) node.getUserObject();

    if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryResultData")) {
        QueryResultData rdata = (QueryResultData) node.getUserObject();
        if (rdata.patientCount().equalsIgnoreCase("0")) {
            return;
            /*//from ww w  .  j  a v a2 s .c  o m
             * final JPanel parent = this;
             * java.awt.EventQueue.invokeLater(new Runnable() { public void
             * run() { JOptionPane.showMessageDialog(parent, "There's no
             * patient in this set.", "Message",
             * JOptionPane.INFORMATION_MESSAGE); } });
             */

        }
    }

    jTree1.scrollPathToVisible(new TreePath(node));

    System.out.println("Node expanded: " + data.name());

    if (data.visualAttribute().equals("FA")) {
        data.visualAttribute("FAO");
    } else if (data.visualAttribute().equals("CA")) {
        data.visualAttribute("CAO");
    }

    // check to see if child is a placeholder ('working...')
    // if so, make Web Service call to update children of node
    if (node.getChildCount() == 1) {
        final DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) node.getChildAt(0);
        if (((QueryData) node1.getUserObject()).visualAttribute().equals("LAO")
                && ((QueryData) node1.getUserObject()).name().equals("working ......")) {
            final DefaultMutableTreeNode anode = node;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    populateChildNodes(anode);
                }
            });
        }
    } else {
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode anode = (DefaultMutableTreeNode) node.getChildAt(0);
            QueryData adata = (QueryData) anode.getUserObject();
            if (adata.visualAttribute().equals("FAO")) {
                adata.visualAttribute("FA");
            } else if (adata.visualAttribute().equals("CAO")) {
                adata.visualAttribute("CA");
            }
        }
    }
}

From source file:edu.harvard.i2b2.query.ui.GroupPanel.java

public void treeExpanded(TreeExpansionEvent event) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) event.getPath().getLastPathComponent();
    QueryConceptTreeNodeData data = (QueryConceptTreeNodeData) node.getUserObject();
    jTree1.scrollPathToVisible(new TreePath(node));

    // System.out.println("Node expanded: "+data.dimcode());
    if (data.visualAttribute().equals("L")) {
        // return;
    }//from   w w w  .jav  a2s. c o m

    if (data.visualAttribute().equals("FA")) {
        data.visualAttribute("FAO");
    } else if (data.visualAttribute().equals("CA")) {
        data.visualAttribute("CAO");
    }

    // check to see if child is a placeholder ('working...')
    // if so, make Web Service call to update children of node
    if (node.getChildCount() == 1) {
        final DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) node.getChildAt(0);
        if (((QueryConceptTreeNodeData) node1.getUserObject()).name().equalsIgnoreCase("working ......")) {
            final DefaultMutableTreeNode anode = node;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    populateChildNodes(anode);
                }
            });
        }
    } else {
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode anode = (DefaultMutableTreeNode) node.getChildAt(0);
            QueryConceptTreeNodeData adata = (QueryConceptTreeNodeData) anode.getUserObject();
            if (adata.visualAttribute().equals("FAO")) {
                // adata.visualAttribute("FA");
            } else if (adata.visualAttribute().equals("CAO")) {
                // adata.visualAttribute("CA");
            }
        }
    }
}

From source file:net.jradius.client.gui.JRadiusSimulator.java

/**
 * This method initializes addButton   //from w ww . j a va  2  s. c om
 *    
 * @return javax.swing.JButton   
 */
private JButton getAddButton() {
    if (addButton == null) {
        addButton = new JButton();
        addButton.setText("Add");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                int rows[] = attributeTree.getSelectionRows();
                if (rows != null) {
                    for (int i = 0; i < rows.length; i++) {
                        TreePath path = attributeTree.getPathForRow(rows[i]);
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path
                                .getPathComponent(path.getPathCount() - 1);
                        String attr = (String) node.getUserObject();
                        try {
                            attributesTableModel.addAttribute(AttributeFactory.newAttribute(attr));
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }
                    }
                    attributesTableModel.fireTableDataChanged();
                }
            }
        });
    }
    return addButton;
}

From source file:Creator.WidgetPanel.java

private void _JTree_WidgetLinksValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event__JTree_WidgetLinksValueChanged

    DefaultMutableTreeNode node = (DefaultMutableTreeNode) _JTree_WidgetLinks.getLastSelectedPathComponent();

    if (node == null) //Nothing is selected.  
    {/*  w ww.j  a  v  a 2s.com*/
        return;
    }

    if (node.getParent() != null) {
        String s = node.getParent().toString() + "-" + node.getUserObject().toString();

        if (ws.containsKey(s)) {
            WidgetLink wl = ws.get(s);
            //System.out.println(wl); 

            // Select the Widget, IO name
            _ComboBox_Subgroup.setSelectedItem(wl.getSubGroup());

            String panelName = node.getParent().toString();

            if (panelName.startsWith("Rack")) {
                _ComboBox_DisplayPanel.setSelectedIndex(1);
            } /*else if (panelName.startsWith("Load")) {
              _ComboBox_DisplayPanel.setSelectedIndex(1 + cs.getNumRacks());
              } */else {
                _ComboBox_DisplayPanel.setSelectedItem(panelName);
            }

            int sel = _List_WidgetCodeList.getSelectedIndex();
            _List_WidgetCodeList.setSelectedIndex(sel >= 1 ? 0 : 1); // This will allow the next line to trigger the value changed field
            _List_WidgetCodeList.setSelectedValue(wl.getWidgetCodeName(), true);
            _List_WidgetVars.setSelectedValue(node.getUserObject().toString(), true);
            _FTF_WigetParam_xPosPer.setValue(wl.getPositionPercentage().getX());
            _FTF_WigetParam_yPosPer.setValue(wl.getPositionPercentage().getY());

        }

    }

}

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

/**
 * Create the frame./*w  ww.j  av  a2 s .c om*/
 */
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:edu.harvard.i2b2.query.ui.GroupPanel.java

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("Constrain Item ...")) {
        // JOptionPane.showMessageDialog(this, "Constrain Item ...");
        // DefaultMutableTreeNode node = (DefaultMutableTreeNode)
        // jTree1.getSelectionPath().getLastPathComponent();
        // QueryConceptTreeNodeData ndata = (QueryConceptTreeNodeData)
        // node.getUserObject();
        // final QueryConstrainFrame cframe = new
        // QueryConstrainFrame(ndata);
        // cframe.setTitle("Constrain Item: "+ndata.name());
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                // cframe.setVisible(true);
            }/*from   w ww .j a v  a 2  s. co m*/
        });
    } else if (e.getActionCommand().equalsIgnoreCase("Delete Item")) {
        // JOptionPane.showMessageDialog(this, "Delete Item");
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        treeModel.removeNodeFromParent(node);
        data().getItems().remove(node.getUserObject());
    } else if (e.getActionCommand().equalsIgnoreCase("Set Value ...")) {
        final DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath()
                .getLastPathComponent();
        final QueryConceptTreeNodeData ndata = (QueryConceptTreeNodeData) node.getUserObject();
        final GroupPanel parent = this;

        int index = data().getItems().indexOf(node.getUserObject());
        currentData = data().getItems().get(index);

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                if (ndata.valuePropertyData().hasEnumValue()) {
                    EnumValueConstraintFrame vDialog = new EnumValueConstraintFrame(parent);
                    vDialog.setSize(410, 330);
                    //StringValueConstraintFrame vDialog = new StringValueConstraintFrame(
                    //parent);
                    //vDialog.setSize(380, 250);
                    vDialog.setLocation(300, 300);
                    vDialog.setTitle("Choose value of " + ndata.titleName());
                    vDialog.setVisible(true);
                } else if (ndata.valuePropertyData().hasStringValue()) {
                    StringValueConstraintFrame vDialog = new StringValueConstraintFrame(parent);
                    vDialog.setSize(380, 250);
                    vDialog.setLocation(300, 300);
                    vDialog.setTitle("Search within the " + ndata.titleName());
                    vDialog.setVisible(true);
                } else {
                    NumericValueConstraintFrame vDialog = new NumericValueConstraintFrame(parent);
                    vDialog.setSize(410, 215);
                    vDialog.setLocation(300, 300);
                    vDialog.setTitle("Choose value of " + ndata.titleName());
                    vDialog.setVisible(true);
                }
            }
        });
    } else if (e.getActionCommand().equalsIgnoreCase("Set Modifier Value ...")) {
        /*final DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1
              .getSelectionPath().getLastPathComponent();
        final QueryConceptTreeNodeData ndata = (QueryConceptTreeNodeData) node
              .getUserObject();
        final GroupPanel parent = this;
                
        int index = data().getItems().indexOf(node.getUserObject());
        currentData = data().getItems().get(index);
                
        java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
              //if (ndata.valuePropertyData().hasEnumValue()) {
          ModifierFrame vDialog = new ModifierFrame();
          vDialog.setSize(200, 410);
          vDialog.setLocation(300, 300);
          //vDialog
                //.setTitle("Choose value of "
                      //+ ndata.titleName());
          vDialog.setVisible(true);
                      
           }
        });*/
        final DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath()
                .getLastPathComponent();
        final ModifierData ndata = (ModifierData) node.getUserObject();
        final GroupPanel parent = this;

        int index = data().getItems().indexOf(node.getUserObject());
        currentData = data().getItems().get(index);

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                if (ndata.modifierValuePropertyData().hasEnumValue()) {
                    ModifierEnumValueConstraintFrame vDialog = new ModifierEnumValueConstraintFrame(parent);
                    vDialog.setSize(410, 330);
                    //ModifierStringValueConstraintFrame vDialog = new ModifierStringValueConstraintFrame(
                    //      parent);
                    //vDialog.setSize(380, 250);  ////410, 330);
                    vDialog.setLocation(300, 300);
                    vDialog.setTitle("Choose modifier value of " + ndata.titleName());
                    vDialog.setVisible(true);
                } else if (ndata.modifierValuePropertyData().hasStringValue()) {
                    ModifierStringValueConstraintFrame vDialog = new ModifierStringValueConstraintFrame(parent);
                    vDialog.setSize(380, 250);
                    vDialog.setLocation(300, 300);
                    vDialog.setTitle("Choose modifier value of " + ndata.titleName());
                    vDialog.setVisible(true);
                } else {
                    ModifierNumericValueConstraintFrame vDialog = new ModifierNumericValueConstraintFrame(
                            parent);
                    vDialog.setSize(410, 215);
                    vDialog.setLocation(300, 300);
                    vDialog.setTitle("Choose modifier value of " + ndata.titleName());
                    vDialog.setVisible(true);
                }
            }
        });
    }
}

From source file:edu.harvard.i2b2.previousquery.ui.PreviousQueryPanel.java

private void populateChildNodes(DefaultMutableTreeNode node) {
    if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryMasterData")) {
        QueryMasterData data = (QueryMasterData) node.getUserObject();
        try {/*from   w ww . ja  va  2  s . co  m*/
            String xmlRequest = data.writeContentQueryXML();

            String xmlResponse = null;
            if (System.getProperty("webServiceMethod").equals("SOAP")) {
                xmlResponse = QueryListNamesClient.sendQueryRequestSOAP(xmlRequest);
            } else {
                xmlResponse = QueryListNamesClient.sendQueryRequestREST(xmlRequest);
            }
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }

            try {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();
                JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlResponse);
                ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();

                BodyType bt = messageType.getMessageBody();
                InstanceResponseType instanceResponseType = (InstanceResponseType) new JAXBUnWrapHelper()
                        .getObjectByClass(bt.getAny(), InstanceResponseType.class);

                for (QueryInstanceType queryInstanceType : instanceResponseType.getQueryInstance()) {
                    // change later for working with new xml schema
                    // RunQuery runQuery =

                    QueryInstanceData runData = new QueryInstanceData();

                    runData.visualAttribute("FA");
                    if (queryInstanceType.getQueryStatusType().getName().equalsIgnoreCase("completed")) {
                        XMLGregorianCalendar sCldr = queryInstanceType.getStartDate();
                        XMLGregorianCalendar eCldr = queryInstanceType.getEndDate();
                        long diff = eCldr.toGregorianCalendar().getTimeInMillis()
                                - sCldr.toGregorianCalendar().getTimeInMillis();
                        runData.tooltip("All results are available, run " + (diff / 1000) + " seconds");
                    }
                    runData.id(queryInstanceType.getQueryInstanceId());
                    // runData.patientRefId(new
                    // Integer(queryInstanceType.getRefId()).toString());
                    // runData.patientCount(new
                    // Long(queryInstanceType.getCount()).toString());
                    // XMLGregorianCalendar cldr =
                    // queryInstanceType.getStartDate();
                    /*
                     * runData.name("Results of "+
                     * "["+addZero(cldr.getMonth(
                     * ))+"-"+addZero(cldr.getDay())+"-"
                     * +addZero(cldr.getYear())+"
                     * "+addZero(cldr.getHour())+":"
                     * +addZero(cldr.getMinute())
                     * +":"+addZero(cldr.getSecond())+"]");
                     */
                    runData.name("Results of " + data.name().substring(0, data.name().indexOf("[")));
                    runData.queryName(data.name());
                    data.runs.add(runData);
                    if (!queryInstanceType.getQueryStatusType().getName().equalsIgnoreCase("completed")) {
                        runData.name(
                                runData.name() + " --- " + queryInstanceType.getQueryStatusType().getName());
                        runData.tooltip("The results of the query run");
                    }
                    addNode(runData, node);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            // jTree1.scrollPathToVisible(new TreePath(node.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryInstanceData")) {
        QueryInstanceData data = (QueryInstanceData) node.getUserObject();

        try {
            String xmlRequest = data.writeContentQueryXML();

            String xmlResponse = null;
            if (System.getProperty("webServiceMethod").equals("SOAP")) {
                xmlResponse = QueryListNamesClient.sendQueryRequestSOAP(xmlRequest);
            } else {
                xmlResponse = QueryListNamesClient.sendQueryRequestREST(xmlRequest);
            }
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }

            JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

            JAXBElement jaxbElement = jaxbUtil.unMashallFromString(xmlResponse);
            ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
            BodyType bt = messageType.getMessageBody();
            ResultResponseType resultResponseType = (ResultResponseType) new JAXBUnWrapHelper()
                    .getObjectByClass(bt.getAny(), ResultResponseType.class);

            for (QueryResultInstanceType queryResultInstanceType : resultResponseType
                    .getQueryResultInstance()) {
                String status = queryResultInstanceType.getQueryStatusType().getName();

                QueryResultData resultData = new QueryResultData();
                if (queryResultInstanceType.getQueryResultType().getName().equalsIgnoreCase("PATIENTSET")
                        && UserInfoBean.getInstance().isRoleInProject("DATA_LDS")) {
                    resultData.visualAttribute("FA");
                } else {
                    resultData.visualAttribute("LAO");
                }
                // resultData.queryId(data.queryId());
                resultData.patientRefId(queryResultInstanceType.getResultInstanceId());// data.patientRefId());
                resultData.patientCount(new Integer(queryResultInstanceType.getSetSize()).toString());// data.patientCount());
                String resultname = "";
                if ((resultname = queryResultInstanceType.getQueryResultType().getDescription()) == null) {
                    resultname = queryResultInstanceType.getQueryResultType().getName();
                }
                // if (status.equalsIgnoreCase("FINISHED")) {
                if (queryResultInstanceType.getQueryResultType().getName().equals("PATIENTSET")
                /*|| queryResultInstanceType.getQueryResultType().getName()
                .equals("PATIENT_COUNT_XML")*/) {
                    // if (UserInfoBean.getInstance().isRoleInProject(
                    // "DATA_OBFSC")) {
                    // resultData.name(resultname + " - "
                    // + resultData.patientCount() + " Patients");
                    // resultData.tooltip(resultData.patientCount()
                    // + " Patients");
                    // } else {
                    if (queryResultInstanceType.getDescription() != null) {
                        resultname = queryResultInstanceType.getDescription();
                        resultData.name(queryResultInstanceType.getDescription());
                    } else {
                        resultData.name(resultname + " - " + resultData.patientCount() + " Patients");
                    }
                    resultData.tooltip(resultData.patientCount() + " Patients");
                    // }
                } else {
                    if (queryResultInstanceType.getDescription() != null) {
                        resultname = queryResultInstanceType.getDescription();
                        resultData.name(queryResultInstanceType.getDescription());
                    } else {
                        resultData.name(resultname);// + " - " + status);
                        resultData.tooltip(status);
                    }

                }

                resultData.xmlContent(xmlResponse);
                resultData.queryName(data.queryName());
                resultData.type(queryResultInstanceType.getQueryResultType().getName());
                if (!status.equalsIgnoreCase("FINISHED")) {
                    resultData.name(resultData.name() + " --- " + status);
                }
                addNode(resultData, node);
            }
            // }
            // jTree1.scrollPathToVisible(new TreePath(node.getPath()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryResultData")) {
        QueryResultData data = (QueryResultData) node.getUserObject();
        if (data.patientCount().equalsIgnoreCase("0")) {
            return;
        }
        int maxNumPatientsToDisplay = Integer.valueOf(System.getProperty("PQMaxPatientsNumber"));
        if (Integer.valueOf(data.patientCount()) > maxNumPatientsToDisplay) {
            final JPanel parent = this;
            result = JOptionPane.showConfirmDialog(parent,
                    "The patient count is greater than maximum configured to be displayed.\n"
                            + "Populating the patient list may affect performance. \n"
                            + "Do you want to continue?",
                    "Please Note ...", JOptionPane.YES_NO_OPTION);
            if (result == JOptionPane.NO_OPTION) {
                DefaultMutableTreeNode tmpnode = (DefaultMutableTreeNode) node.getChildAt(0);
                QueryData tmpdata = (QueryData) tmpnode.getUserObject();
                if (tmpdata.name().equalsIgnoreCase("working ......")) {
                    tmpdata.name("Over maximum number of patient nodes");
                    treeModel.reload(tmpnode);
                }
                return;
            }
        }
        try {
            String xmlRequest = data.writeContentQueryXML();

            String xmlResponse = null;
            if (System.getProperty("webServiceMethod").equals("SOAP")) {
                xmlResponse = QueryListNamesClient.sendPDORequestSOAP(xmlRequest, showName());
            } else {
                xmlResponse = QueryListNamesClient.sendPdoRequestREST(xmlRequest);
            }
            if (xmlResponse.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                return;
            }

            // check response status here ......

            // System.out.println("Response: "+xmlResponse);
            PatientSet patientSet = new PDOResponseMessageFactory().getPatientSetFromResponseXML(xmlResponse);
            List<PatientType> patients = patientSet.getPatient();
            System.out.println("Patient set size: " + patients.size());

            for (int i = 0; i < patients.size(); i++) {
                PatientType patient = patients.get(i);

                PatientData pData = new PatientData();
                pData.patientID(patient.getPatientId().getValue());
                pData.setParamData(patient.getParam());
                pData.visualAttribute("LAO");
                pData.tooltip("Patient");
                pData.patientSetID(data.patientRefId());
                if (showName() && pData.lastName() != null && pData.firstName() != null) {
                    pData.name(pData.patientID() + " [" + pData.lastName().substring(0, 1).toUpperCase()
                            + pData.lastName().substring(1, pData.lastName().length()).toLowerCase() + ", "
                            + pData.firstName().substring(0, 1).toUpperCase()
                            + pData.firstName().substring(1, pData.firstName().length()).toLowerCase() + "]");// ["+pData.age()+"
                    // y/o
                    // "+pData.gender()+"
                    // "+pData.race()+"]");
                } else {
                    pData.name(pData.patientID() + " [" + pData.age() + " y/o " + pData.gender() + " "
                            + pData.race() + "]");
                }
                pData.queryName(data.queryName());
                addNode(pData, node);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // implement for other type of nodes later!!!
}

From source file:Creator.WidgetPanel.java

private void _List_WidgetCodeListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event__List_WidgetCodeListValueChanged

    // _ScrollPane_WidgetSettings
    if (!evt.getValueIsAdjusting()) {

        // Load the variables of the widget
        String widgetCodeStr;/* w  ww.  ja  v  a2  s  .  c o  m*/
        WidgetCode wc = null;
        WidgetLink wl = null;
        if (!_JTree_WidgetLinks.isSelectionEmpty()) {

            DefaultMutableTreeNode node = (DefaultMutableTreeNode) _JTree_WidgetLinks
                    .getLastSelectedPathComponent();

            if (node == null) //Nothing is selected.  
            {
                return;
            }

            if (node.getParent() != null) {
                String s = node.getParent().toString() + "-" + node.getUserObject().toString();

                if (ws.containsKey(s)) {
                    wl = ws.get(s);
                    wc = widgetList.get(wl.getWidgetCodeName());
                }
            }
        }

        if (wc == null) {
            // No selected item on the JTree
            widgetCodeStr = _List_WidgetCodeList.getSelectedValue().toString();
            wc = widgetList.get(widgetCodeStr);
        } else {

            // Make sure the item selected matches the code in the widget link
            // This makes selecting 
            if (!wc.getWidgetName().equals(_List_WidgetCodeList.getSelectedValue().toString())) {

                widgetCodeStr = _List_WidgetCodeList.getSelectedValue().toString();
                wc = widgetList.get(widgetCodeStr);
            }

        }

        GridBagLayout gbl = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();

        c.fill = GridBagConstraints.HORIZONTAL;
        c.gridx = 0;
        c.gridy = 0;
        c.weightx = 1;
        c.weighty = 0;
        c.gridwidth = 1;
        c.gridheight = 1;
        c.ipadx = 0;
        c.ipady = 5;

        if (widgetCodeSettings == null) {
            widgetCodeSettings = new HashMap<>();
        } else {
            widgetCodeSettings.clear();
        }

        _Panel_WidgetSettings.removeAll();
        _Panel_WidgetSettings.setLayout(gbl);

        for (String name : wc.getVariables()) {
            JLabel label = new JLabel(name);
            label.setFont(new Font("Arial", Font.BOLD, 13));
            label.setHorizontalAlignment(SwingConstants.CENTER);
            JTextField textfield = new JTextField("");
            textfield.setHorizontalAlignment(SwingConstants.CENTER);
            if (wl != null) {
                textfield.setText(wl.getVariables().get(name));
            }

            textfield.setFont(new Font("Arial", Font.BOLD, 15));

            widgetCodeSettings.put(label.getText(), textfield);
            _Panel_WidgetSettings.add(label, c);
            c.gridy += 1;
            _Panel_WidgetSettings.add(textfield, c);
            c.gridy += 1;
        }

        _ScrollPane_WidgetSettings.revalidate();
        _ScrollPane_WidgetSettings.repaint();

    }

}

From source file:gtu._work.etc._3DSMovieRenamer.java

private void initGUI() {
    try {/*  w  ww  . ja  va2 s  .  c  o  m*/
        final SwingActionUtil swingUtil = (SwingActionUtil) SwingActionUtil.newInstance(this);

        BorderLayout thisLayout = new BorderLayout();
        getContentPane().setLayout(thisLayout);
        this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        this.setTitle("3DS Rename");
        {
            jTabbedPane1 = new JTabbedPane();
            getContentPane().add(jTabbedPane1, BorderLayout.CENTER);
            {
                jPanel1 = new JPanel();
                BorderLayout jPanel1Layout = new BorderLayout();
                jPanel1.setLayout(jPanel1Layout);
                jTabbedPane1.addTab("vid list", null, jPanel1, null);
                {
                    openDir = new JButton();
                    jPanel1.add(openDir, BorderLayout.NORTH);
                    openDir.setText("open dir");
                    openDir.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            swingUtil.invokeAction("openDir.actionPerformed", evt);
                        }
                    });
                }
                {
                    ListModel vidListModel = new DefaultListModel();
                    vidList = new JList();
                    jPanel1.add(vidList, BorderLayout.CENTER);
                    vidList.setModel(vidListModel);
                    vidList.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent evt) {
                            swingUtil.invokeAction("vidList.mouseClicked", evt);
                        }
                    });
                    vidList.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent evt) {
                            swingUtil.invokeAction("vidList.keyPressed", evt);
                        }
                    });
                }
                {
                    jPanel3 = new JPanel();
                    jPanel1.add(jPanel3, BorderLayout.SOUTH);
                    jPanel3.setPreferredSize(new java.awt.Dimension(445, 34));
                    {
                        renameText = new JTextField();
                        jPanel3.add(renameText);
                        renameText.setPreferredSize(new java.awt.Dimension(187, 24));
                    }
                    {
                        renameBtn = new JButton();
                        jPanel3.add(renameBtn);
                        renameBtn.setText("rename");
                        renameBtn.setPreferredSize(new java.awt.Dimension(106, 24));
                        renameBtn.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                swingUtil.invokeAction("renameBtn.mouseClicked", evt);
                            }
                        });
                    }
                    {
                        forceChange = new JCheckBox();
                        jPanel3.add(forceChange);
                        forceChange.setText("force");
                        forceChange.setPreferredSize(new java.awt.Dimension(64, 21));
                    }
                }
            }
            {
                jPanel2 = new JPanel();
                BorderLayout jPanel2Layout = new BorderLayout();
                jPanel2.setLayout(jPanel2Layout);
                jTabbedPane1.addTab("copy", null, jPanel2, null);
                {
                    jScrollPane1 = new JScrollPane();
                    jPanel2.add(jScrollPane1, BorderLayout.CENTER);
                    {
                        ListModel copyToListModel = new DefaultListModel();
                        copyToList = new JList();
                        jScrollPane1.setViewportView(copyToList);
                        copyToList.setModel(copyToListModel);
                        copyToList.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                swingUtil.invokeAction("copyToList.mouseClicked", evt);
                            }
                        });
                    }
                }
            }
            {
                jPanel4 = new JPanel();
                BorderLayout jPanel4Layout = new BorderLayout();
                jPanel4.setLayout(jPanel4Layout);
                jTabbedPane1.addTab("BT Movie", null, jPanel4, null);
                {
                    jScrollPane2 = new JScrollPane();
                    jPanel4.add(jScrollPane2, BorderLayout.WEST);
                    jScrollPane2.setPreferredSize(new java.awt.Dimension(254, 355));
                    {
                        btDirTree = new JTree();
                        jScrollPane2.setViewportView(btDirTree);
                        btDirTree.addMouseListener(new MouseAdapter() {
                            public void mouseClicked(MouseEvent evt) {
                                swingUtil.invokeAction(evt);
                            }
                        });
                        btDirTree.addPropertyChangeListener(new PropertyChangeListener() {
                            public void propertyChange(PropertyChangeEvent evt) {
                                swingUtil.invokeAction(evt);
                            }
                        });
                        JTreeUtil.newInstance(btDirTree).fileSystem(DEFAULT_BT_DIR);
                    }
                }
                {
                    jPanel5 = new JPanel();
                    BorderLayout jPanel5Layout = new BorderLayout();
                    jPanel5.setLayout(jPanel5Layout);
                    jPanel4.add(jPanel5, BorderLayout.CENTER);
                    {
                        jScrollPane3 = new JScrollPane();
                        jPanel5.add(jScrollPane3, BorderLayout.CENTER);
                        jScrollPane3.setPreferredSize(new java.awt.Dimension(427, 355));
                        {
                            DefaultListModel btMovListModel = new DefaultListModel();
                            btMovList = new JList();
                            jScrollPane3.setViewportView(btMovList);
                            btMovList.setModel(btMovListModel);
                            btMovList.addMouseListener(new MouseAdapter() {
                                public void mouseClicked(MouseEvent evt) {
                                    swingUtil.invokeAction(evt);
                                }
                            });
                            btMovList.addKeyListener(new KeyAdapter() {
                                public void keyPressed(KeyEvent evt) {
                                    JListUtil.newInstance(btMovList).defaultJListKeyPressed(evt);
                                }
                            });
                        }
                    }
                }
            }
            {
                jPanel6 = new JPanel();
                FlowLayout jPanel6Layout = new FlowLayout();
                jTabbedPane1.addTab("common", null, jPanel6, null);
                jPanel6.setLayout(jPanel6Layout);
                {
                    execute3dsVidTransfer = new JButton();
                    jPanel6.add(execute3dsVidTransfer);
                    execute3dsVidTransfer.setText("execute 3ds video transfer");
                    execute3dsVidTransfer.setPreferredSize(new java.awt.Dimension(207, 42));
                    execute3dsVidTransfer.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            String bat = "C:/apps/_movie/3DSVideov1.00/3DS Video.exe";
                            try {
                                Runtime.getRuntime().exec(String.format("cmd /c call \"%s\"", bat));
                            } catch (IOException e) {
                                JCommonUtil.handleException(e);
                            }
                        }
                    });
                }
                {
                    openMovieAppDir = new JButton();
                    jPanel6.add(openMovieAppDir);
                    openMovieAppDir.setText("open movie app dir");
                    openMovieAppDir.setPreferredSize(new java.awt.Dimension(207, 42));
                    openMovieAppDir.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            try {
                                Desktop.getDesktop().open(new File("C:/apps/_movie"));
                            } catch (IOException e) {
                                JCommonUtil.handleException(e);
                            }
                        }
                    });
                }
            }
            {
                jPanel7 = new JPanel();
                BorderLayout jPanel7Layout = new BorderLayout();
                jTabbedPane1.addTab("fake rename", null, jPanel7, null);
                jPanel7.setLayout(jPanel7Layout);
                {
                    openFakeRenameDir = new JButton();
                    jPanel7.add(openFakeRenameDir, BorderLayout.NORTH);
                    openFakeRenameDir.setText("open dir");
                    openFakeRenameDir.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent evt) {
                            File file = JCommonUtil._jFileChooser_selectDirectoryOnly();
                            if (file != null) {
                                DefaultListModel model = new DefaultListModel();
                                for (File f : file.listFiles()) {
                                    model.addElement(f);
                                }
                                openFakeRenameDirList.setModel(model);
                            }
                        }
                    });
                }
                {
                    DefaultListModel openFakeRenameDirListModel = new DefaultListModel();
                    openFakeRenameDirList = new JList();
                    jPanel7.add(openFakeRenameDirList, BorderLayout.CENTER);
                    openFakeRenameDirList.setModel(openFakeRenameDirListModel);
                    openFakeRenameDirList.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent evt) {
                            File file = (File) JListUtil.getLeadSelectionObject(openFakeRenameDirList);
                            try {
                                Process process = Runtime.getRuntime()
                                        .exec(String.format("cmd /c call \"%s\"", file));
                                InputStream ins = process.getInputStream();
                                while (ins.read() != -1) {
                                    //TODO
                                }
                                ins.close();
                                System.out.println("done...");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    openFakeRenameDirList.addKeyListener(new KeyAdapter() {
                        public void keyPressed(KeyEvent evt) {
                            JListUtil.newInstance(openFakeRenameDirList).defaultJListKeyPressed(evt);
                        }
                    });
                }
                {
                    jPanel8 = new JPanel();
                    jPanel7.add(jPanel8, BorderLayout.SOUTH);
                    jPanel8.setPreferredSize(new java.awt.Dimension(681, 43));
                    {
                        openFakeRenameDir_newName = new JTextField();
                        jPanel8.add(openFakeRenameDir_newName);
                        openFakeRenameDir_newName.setPreferredSize(new java.awt.Dimension(287, 27));
                    }
                    {
                        fakeRenameExecute = new JButton();
                        jPanel8.add(fakeRenameExecute);
                        fakeRenameExecute.setText("execute");
                        fakeRenameExecute.setPreferredSize(new java.awt.Dimension(95, 27));
                        fakeRenameExecute.addActionListener(new ActionListener() {
                            public void actionPerformed(ActionEvent evt) {
                                DefaultListModel model = (DefaultListModel) openFakeRenameDirList.getModel();
                                //TODO
                            }
                        });
                    }
                }
            }

            swingUtil.addAction("copyToList.mouseClicked", new Action() {
                public void action(EventObject evt) throws Exception {
                    try {
                        if (((MouseEvent) evt).getButton() == 3) {
                            JMenuItem reloadMenu = new JMenuItem();
                            reloadMenu.setText("reload SD card directory");
                            reloadMenu.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent e) {
                                    DefaultListModel copyToListModel = new DefaultListModel();
                                    for (final File f : load3DSDir.listFiles(new FilenameFilter() {
                                        public boolean accept(File paramFile, String paramString) {
                                            if (paramFile.isDirectory()
                                                    && paramString.matches(CUSTOM_3DS_DIR_PATTERN)) {
                                                return true;
                                            }
                                            return false;
                                        }
                                    })) {
                                        copyToListModel.addElement(f);
                                    }
                                    copyToList.setModel(copyToListModel);
                                }
                            });
                            JMenuItem copyAllToMenu = new JMenuItem();
                            {
                                copyAllToMenu.setText(
                                        String.format("move %d vids to...", vidList.getModel().getSize()));
                                final File toDir = (File) JListUtil.getLeadSelectionObject(copyToList);
                                if (toDir == null || !toDir.exists() || !toDir.isDirectory()) {
                                    copyAllToMenu.setEnabled(false);
                                }
                                if (vidList.getModel().getSize() == 0) {
                                    copyAllToMenu.setText("copy no file...");
                                    copyAllToMenu.setEnabled(false);
                                }
                                copyAllToMenu.addActionListener(new ActionListener() {
                                    public void actionPerformed(ActionEvent e) {
                                        DefaultListModel model = JListUtil.newInstance(vidList).getModel();
                                        if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION != JOptionPaneUtil
                                                .newInstance().iconWaringMessage().confirmButtonYesNo()
                                                .showConfirmDialog("are you sure copy files : "
                                                        + model.getSize() + "\n to dir : " + toDir,
                                                        "COPY VIDS")) {
                                            return;
                                        }
                                        for (int ii = 0; ii < model.getSize(); ii++) {
                                            File src = (File) model.getElementAt(ii);
                                            src.renameTo(new File(toDir, src.getName()));
                                        }
                                        JOptionPaneUtil.newInstance().iconInformationMessage()
                                                .showMessageDialog("copy completed!", "SUCCESS");
                                        loadDirVids();
                                    }
                                });
                            }

                            JPopupMenuUtil.newInstance(copyToList).applyEvent((MouseEvent) evt)
                                    .addJMenuItem(reloadMenu, copyAllToMenu).show();
                        }
                    } catch (Exception ex) {
                        JCommonUtil.handleException(ex);
                    }
                }
            });
            swingUtil.addAction("openDir.actionPerformed", new Action() {
                public void action(EventObject evt) throws Exception {
                    File file = JFileChooserUtil.newInstance().selectDirectoryOnly().showOpenDialog()
                            .getApproveSelectedFile();
                    if (file == null) {
                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                .showMessageDialog("dir not corrent!, set desktop", getTitle());
                        loadDir = FileUtil.DESKTOP_DIR;
                    } else {
                        loadDir = file;
                    }
                    loadDirVids();
                }
            });
            swingUtil.addAction("vidList.mouseClicked", new Action() {
                //                    final String player = "C:/Program Files (x86)/GRETECH/GomPlayer/GOM.EXE";

                public void action(EventObject evt) throws Exception {
                    int pos = -1;
                    if ((pos = vidList.getLeadSelectionIndex()) == -1) {
                        return;
                    }
                    MouseEvent mevt = (MouseEvent) evt;

                    final File selectItem = (File) vidList.getModel().getElementAt(pos);

                    List<JMenuItem> menuList = new ArrayList<JMenuItem>();
                    JMenuItem simpleRenamer = new JMenuItem();
                    final String simpleRenamePrefix = RandomUtil.upperCase(3);
                    simpleRenamer.setText("Rename : " + simpleRenamePrefix);
                    simpleRenamer.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent paramActionEvent) {
                            String value = StringUtils.defaultString(JOptionPaneUtil.newInstance()
                                    .showInputDialog("3 char prefix?", "AVI PREFIX"), simpleRenamePrefix);
                            if (value != null && value.matches("[a-zA-Z]{3}")) {
                                selectItem.renameTo(getNewFile(selectItem.getParentFile(), value));
                                loadDirVids();
                            } else {
                                JOptionPaneUtil.newInstance().iconErrorMessage()
                                        .showMessageDialog("prefix is not correct!", "ERROR");
                            }
                        }
                    });
                    menuList.add(simpleRenamer);
                    if (load3DSDir == null) {
                        reload3DSDir();
                        if (load3DSDir == null) {
                            JMenuItem disable = new JMenuItem();
                            disable.setText("MOVE : SD card is not set!");
                            disable.setEnabled(false);
                            menuList.add(disable);
                        }
                    } else {
                        for (final File f : load3DSDir.listFiles(new FilenameFilter() {
                            public boolean accept(File paramFile, String paramString) {
                                if (paramFile.isDirectory() && paramString.matches(CUSTOM_3DS_DIR_PATTERN)) {
                                    return true;
                                }
                                return false;
                            }
                        })) {
                            JMenuItem copyTo = new JMenuItem();
                            copyTo.setText("MOVE : " + f.getName());
                            copyTo.addActionListener(new ActionListener() {
                                public void actionPerformed(ActionEvent paramActionEvent) {
                                    if (JOptionPaneUtil.ComfirmDialogResult.YES_OK_OPTION == JOptionPaneUtil
                                            .newInstance().iconQuestionMessage().confirmButtonYesNo()
                                            .showConfirmDialog(//
                                                    "are you sure move file\n" + //
                                    selectItem + "\n" + //
                                    "to\n" + //
                                    "dir : " + f + "  ??"//
                                    , "COPY FILE")) {

                                        File copyToNewDirFile = new File(f, selectItem.getName());
                                        if (copyToNewDirFile.exists()) {
                                            JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(
                                                    "target dir file already exist!, need rename!",
                                                    "FILE ALREADY EXIST");
                                            return;
                                        }
                                        selectItem.renameTo(copyToNewDirFile);
                                        loadDirVids();

                                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                                .showMessageDialog("move completed!", "MOVE FILE");
                                    }
                                }
                            });
                            menuList.add(copyTo);
                        }
                    }
                    JPopupMenuUtil.newInstance(vidList).applyEvent(mevt)
                            .addJMenuItem(menuList.toArray(new JMenuItem[menuList.size()])).show();

                    if (mevt.getClickCount() != 2) {
                        return;
                    }
                    String clkItemPath = selectItem.getAbsolutePath();
                    String command = "cmd /c call \"" + clkItemPath + "\"";
                    System.out.println(command);
                    Runtime.getRuntime().exec(command);
                }
            });
            swingUtil.addAction("vidList.keyPressed", new Action() {
                public void action(EventObject evt) throws Exception {
                    JListUtil.newInstance(vidList).defaultJListKeyPressed(evt);
                }
            });
            swingUtil.addAction("renameBtn.mouseClicked", new Action() {

                Pattern aviNamePattern = Pattern.compile("^([a-zA-Z]{3})_\\d{4}\\.[aA][vV][iI]$");

                public void action(EventObject evt) throws Exception {
                    String name = StringUtils.defaultIfEmpty(renameText.getText(), RandomUtil.upperCase(3));
                    System.out.println("name = " + name + ", force : " + forceChange.isSelected());
                    if (!name.matches("[a-zA-Z]{3}")) {
                        renameText.setText("");
                        JOptionPaneUtil.newInstance().iconErrorMessage()
                                .showMessageDialog("rename must eng 3 char!", "ERROR");
                        return;
                    }
                    DefaultListModel model = (DefaultListModel) vidList.getModel();
                    boolean matchOk = false;
                    if (model.size() != 0) {
                        File oldFile = null;
                        Matcher matcher = null;
                        for (int ii = 0; ii < model.getSize(); ii++) {
                            oldFile = (File) model.getElementAt(ii);

                            if (!oldFile.exists()) {
                                JOptionPaneUtil.newInstance().iconErrorMessage().showMessageDialog(
                                        "file not exeist : \n" + oldFile.getAbsolutePath(), getTitle());
                                return;
                            }
                            matcher = aviNamePattern.matcher(oldFile.getName());
                            matchOk = matcher.find();
                            System.out.println("matchOk = " + matchOk);
                            if (matchOk && !forceChange.isSelected()) {
                                oldFile.renameTo(getNewFile(oldFile.getParentFile(), matcher.group(1)));
                            } else {
                                oldFile.renameTo(getNewFile(oldFile.getParentFile(), name));
                            }
                        }
                        JOptionPaneUtil.newInstance().iconInformationMessage().showMessageDialog("success!",
                                getTitle());
                    }
                    loadDirVids();
                }
            });

            ToolTipManager.sharedInstance().setInitialDelay(0);
            swingUtil.addAction(btMovList, MouseEvent.class, new Action() {
                public void action(EventObject evt) throws Exception {
                    final File file = (File) JListUtil.getLeadSelectionObject(btMovList);
                    if (JMouseEventUtil.buttonLeftClick(1, evt)) {
                        btMovList.setToolTipText(
                                DateFormatUtils.format(file.lastModified(), "yyyy/MM/dd HH:mm:ss") + " length:"
                                        + (file.length() / 1024) + "k");
                    }

                    final Object[] objects = btMovList.getSelectedValues();
                    JPopupMenuUtil.newInstance(btMovList).applyEvent(evt)//
                            .addJMenuItem("move out", (objects != null && objects.length > 0),
                                    new ActionListener() {
                                        public void actionPerformed(ActionEvent paramActionEvent) {
                                            List<File> list = new ArrayList<File>();
                                            for (Object val : objects) {
                                                list.add((File) val);
                                            }
                                            if (!JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                                    "sure move file from\n" + list.toString().replace(',', '\n')
                                                            + "\nto\n" + DEFAULT_BT_DIR,
                                                    "MOVE")) {
                                                return;
                                            }
                                            StringBuilder sb = new StringBuilder();
                                            File moveTo = null;
                                            for (File file : list) {
                                                sb.append((file.renameTo(
                                                        moveTo = new File(DEFAULT_BT_DIR, file.getName()))
                                                        && moveTo.exists()) ? "" : file + "\n");
                                            }
                                            JCommonUtil._jOptionPane_showMessageDialog_info(
                                                    sb.length() == 0 ? "move success!" : "move failed!\n" + sb);
                                        }
                                    })
                            .addJMenuItem("delete this", file.exists(), new ActionListener() {
                                public void actionPerformed(ActionEvent paramActionEvent) {
                                    if (!JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                            "sure delete file \n" + file, "DELETE")) {
                                        return;
                                    }
                                    boolean result = file.delete();
                                    System.out.println("!!!!!" + result + "..." + file.exists());
                                    JCommonUtil._jOptionPane_showMessageDialog_info(
                                            result ? "delete success!" : "delete failed!");
                                }
                            }).show();

                    if (JMouseEventUtil.buttonLeftClick(2, evt)) {
                        Runtime.getRuntime().exec(String.format("cmd /c call \"%s\"", file));
                    }
                }
            });
            swingUtil.addAction(btDirTree, MouseEvent.class, new Action() {

                File getSingleFile() {
                    return ((JFile) JTreeUtil.newInstance(btDirTree).getSelectItem().getUserObject()).getFile();
                }

                public void action(EventObject evt) throws Exception {
                    int selectCount = btDirTree.getSelectionModel().getSelectionCount();
                    if (selectCount == 1) {
                        final File file = getSingleFile();
                        JPopupMenuUtil.newInstance(btDirTree).applyEvent(evt).addJMenuItem("delete this",
                                selectCount == 1 && file.exists(), new ActionListener() {
                                    public void actionPerformed(ActionEvent paramActionEvent) {
                                        if (file.isFile()) {
                                            if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                                    "sure delete FILE : \n" + file, "WARNING")) {
                                                file.delete();
                                                JCommonUtil._jOptionPane_showMessageDialog_info(
                                                        (file.exists() ? "delete failed!" : "delete success!"));
                                            }
                                        }
                                        if (file.isDirectory()) {
                                            StringBuilder sb = new StringBuilder();
                                            if (JCommonUtil._JOptionPane_showConfirmDialog_yesNoOption(
                                                    "sure delete DIR : \n" + file, "WARNING")) {
                                                List<Boolean> delL = new ArrayList<Boolean>();
                                                for (File f : file.listFiles()) {
                                                    if (fileExtensionPattern.matcher(f.getName()).find()
                                                            || f.length() > 1000000L) {
                                                        if (!JCommonUtil
                                                                ._JOptionPane_showConfirmDialog_yesNoOption(
                                                                        "delete this : \n" + f,
                                                                        "CHECK AGAIN")) {
                                                            continue;
                                                        }
                                                        delL.add(f.delete());
                                                    }
                                                    delL.add(f.delete());
                                                }
                                                for (File f : file.listFiles()) {
                                                    if (f.exists()) {
                                                        sb.append(f + "\n");
                                                    }
                                                }
                                                System.out.println("delL.contains(false)==================>"
                                                        + delL.contains(false));
                                            }
                                            if (!file.delete()) {
                                                sb.append(file + "\n");
                                            }
                                            JCommonUtil._jOptionPane_showMessageDialog_info(
                                                    sb.length() > 0 ? "delete failed!\nlist:\n" + sb
                                                            : "delete success!");
                                            if (sb.length() == 0) {
                                                DefaultMutableTreeNode node = JTreeUtil.newInstance(btDirTree)
                                                        .getSelectItem();
                                                System.out.println(
                                                        JTreeUtil.newInstance(btDirTree).removeNode(node));
                                            }
                                        }
                                    }
                                }).addJMenuItem("open dir", new ActionListener() {
                                    public void actionPerformed(ActionEvent paramActionEvent) {
                                        File openTarget = file;
                                        if (file.isFile()) {
                                            openTarget = file.getParentFile();
                                        }
                                        try {
                                            Desktop.getDesktop().open(openTarget);
                                        } catch (IOException e) {
                                            JCommonUtil.handleException(e);
                                        }
                                    }
                                }).show();
                    }
                }
            });
            swingUtil.addAction(btDirTree, PropertyChangeEvent.class, new Action() {
                public void action(EventObject evt) throws Exception {
                    List<File> list = new ArrayList<File>();
                    for (DefaultMutableTreeNode node : JTreeUtil.newInstance(btDirTree).getSelectItems()) {
                        JFile jfile = (JFile) node.getUserObject();
                        if (jfile.getFile().isDirectory()) {
                            for (File f : jfile.getFile().listFiles(new FilenameFilter() {
                                public boolean accept(File paramFile, String paramString) {
                                    return fileExtensionPattern.matcher(paramString).find();
                                }
                            })) {
                                System.out.println(f.getName() + "...." + f.length());
                                list.add(f);
                            }
                        }
                    }
                    Collections.sort(list, new Comparator<File>() {
                        public int compare(File paramT1, File paramT2) {
                            return paramT1.lastModified() > paramT2.lastModified() ? -1 : 1;
                        }
                    });
                    btMovList.setModel(JListUtil.createModel(list.iterator()));
                }
            });
        }
        this.setSize(702, 422);

        loadDirVids();
        reload3DSDir();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:edu.harvard.i2b2.previousquery.ui.PreviousQueryPanel.java

public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("Rename ...")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryMasterData")) {

            QueryMasterData ndata = (QueryMasterData) node.getUserObject();
            Object inputValue = JOptionPane.showInputDialog(this, "Rename this query to: ",
                    "Rename Query Dialog", JOptionPane.PLAIN_MESSAGE, null, null,
                    ndata.name().substring(0, ndata.name().indexOf("[") - 1));

            if (inputValue != null) {
                String newQueryName = (String) inputValue;
                String requestXml = ndata.writeRenameQueryXML(newQueryName);

                setCursor(new Cursor(Cursor.WAIT_CURSOR));

                String response = null;
                if (System.getProperty("webServiceMethod").equals("SOAP")) {
                    // TO DO
                    // response =
                    // QueryListNamesClient.sendQueryRequestSOAP(requestXml);
                } else {
                    response = QueryListNamesClient.sendQueryRequestREST(requestXml);
                }// w w  w . j ava2  s .c  o m

                if (response.equalsIgnoreCase("CellDown")) {
                    final JPanel parent = this;
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            JOptionPane.showMessageDialog(parent,
                                    "Trouble with connection to the remote server, "
                                            + "this is often a network error, please try again",
                                    "Network Error", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    return;
                }

                if (response != null) {
                    JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                    try {
                        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                        ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                        StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                        String status = statusType.getType();

                        if (status.equalsIgnoreCase("DONE")) {
                            // XMLGregorianCalendar cldr =
                            // //queryMasterType.getCreateDate();
                            Calendar cldr = Calendar.getInstance(Locale.getDefault());
                            ndata.name(newQueryName + " [" + addZero(cldr.get(Calendar.MONTH) + 1) + "-"
                                    + addZero(cldr.get(Calendar.DAY_OF_MONTH)) + "-"
                                    + addZero(cldr.get(Calendar.YEAR)) + " ]" + " [" + ndata.userId() + "]");
                            // ndata.name(newQueryName + " [" +
                            // ndata.userId()
                            // + "]");
                            node.setUserObject(ndata);
                            // DefaultMutableTreeNode parent =
                            // (DefaultMutableTreeNode) node.getParent();

                            jTree1.repaint();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        } else if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryResultData")) {

            QueryResultData rdata = (QueryResultData) node.getUserObject();
            // if(!rdata.type().equalsIgnoreCase("PatientSet")) {
            // return;
            // }

            Object inputValue1 = JOptionPane.showInputDialog(this, "Rename this to: ", "Renaming Dialog",
                    JOptionPane.PLAIN_MESSAGE, null, null, rdata.name());
            // .substring(0, rdata.name().lastIndexOf("[") - 1));

            if (inputValue1 != null) {
                String newQueryName = (String) inputValue1;
                String requestXml = rdata.writeRenameQueryXML(newQueryName);

                setCursor(new Cursor(Cursor.WAIT_CURSOR));

                String response = null;
                if (System.getProperty("webServiceMethod").equals("SOAP")) {
                    // TO DO
                    // response =
                    // QueryListNamesClient.sendQueryRequestSOAP(requestXml);
                } else {
                    response = QueryListNamesClient.sendQueryRequestREST(requestXml);
                }

                if (response.equalsIgnoreCase("CellDown")) {
                    final JPanel parent = this;
                    java.awt.EventQueue.invokeLater(new Runnable() {
                        public void run() {
                            JOptionPane.showMessageDialog(parent,
                                    "Trouble with connection to the remote server, "
                                            + "this is often a network error, please try again",
                                    "Network Error", JOptionPane.INFORMATION_MESSAGE);

                        }
                    });
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                    return;
                }

                if (response != null) {
                    JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                    try {
                        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                        ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                        StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                        String status = statusType.getType();

                        if (status.equalsIgnoreCase("DONE")) {
                            rdata.name(newQueryName);// + " [" +
                            // rdata.userId()
                            // + "]");
                            node.setUserObject(rdata);
                            // DefaultMutableTreeNode parent =
                            // (DefaultMutableTreeNode) node.getParent();

                            jTree1.repaint();
                        } else {
                            final String tmp = response;
                            final JPanel parent = this;
                            java.awt.EventQueue.invokeLater(new Runnable() {
                                public void run() {
                                    JOptionPane.showMessageDialog(parent,
                                            "Error message delivered from the remote server, "
                                                    + "you may wish to retry your last action",
                                            "Server Error", JOptionPane.INFORMATION_MESSAGE);
                                    log.error(tmp);
                                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                                }

                            });

                            return;
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    } else if (e.getActionCommand().equalsIgnoreCase("Cancel")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryMasterData")) {
            DefaultMutableTreeNode node1 = (DefaultMutableTreeNode) node.getFirstChild();
            if (node1.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryMasterData")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent, "Please expand this node then try to cancel it.",
                                "Message", JOptionPane.INFORMATION_MESSAGE);

                    }
                });
                return;
            }
            QueryInstanceData rdata = (QueryInstanceData) node1.getUserObject();

            String requestXml = rdata.writeCancelQueryXML();

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = null;
            if (System.getProperty("webServiceMethod").equals("SOAP")) {
                // TO DO
                // response =
                // QueryListNamesClient.sendQueryRequestSOAP(requestXml);
            } else {
                response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            }

            if (response.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);

                    }
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();
                    final JPanel parent = this;
                    if (status.equalsIgnoreCase("DONE")) {
                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                JOptionPane.showMessageDialog(parent, "The query is finished.", "Message",
                                        JOptionPane.INFORMATION_MESSAGE);
                                // log.error(tmp);
                                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                            }

                        });
                        rdata.name(rdata.name().substring(0, rdata.name().indexOf("-")));// + " [" +
                        // rdata
                        // .userId()
                        // + "]");
                        node.setUserObject(rdata);
                        // DefaultMutableTreeNode parent =
                        // (DefaultMutableTreeNode) node.getParent();

                        jTree1.repaint();
                    } else {
                        final String tmp = response;
                        // final JPanel parent = this;
                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                JOptionPane.showMessageDialog(parent,
                                        "Error message delivered from the remote server, "
                                                + "you may wish to retry your last action",
                                        "Server Error", JOptionPane.INFORMATION_MESSAGE);
                                log.error(tmp);
                                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                            }

                        });

                        return;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                // }
            }
        } else if (node.getUserObject().getClass().getSimpleName().equalsIgnoreCase("QueryInstanceData")) {

            QueryInstanceData rdata = (QueryInstanceData) node.getUserObject();

            String requestXml = rdata.writeCancelQueryXML();

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = null;
            if (System.getProperty("webServiceMethod").equals("SOAP")) {
                // TO DO
                // response =
                // QueryListNamesClient.sendQueryRequestSOAP(requestXml);
            } else {
                response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            }

            if (response.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);

                    }
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();
                    final JPanel parent = this;
                    if (status.equalsIgnoreCase("DONE")) {
                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                JOptionPane.showMessageDialog(parent, "The query is finished.", "Message",
                                        JOptionPane.INFORMATION_MESSAGE);
                                // log.error(tmp);
                                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                            }

                        });
                        rdata.name(rdata.name().substring(0, rdata.name().indexOf("-")));// + " [" +
                        // rdata
                        // .userId()
                        // + "]");
                        node.setUserObject(rdata);
                        // DefaultMutableTreeNode parent =
                        // (DefaultMutableTreeNode) node.getParent();

                        jTree1.repaint();
                    } else {
                        final String tmp = response;
                        // final JPanel parent = this;
                        java.awt.EventQueue.invokeLater(new Runnable() {
                            public void run() {
                                JOptionPane.showMessageDialog(parent,
                                        "Error message delivered from the remote server, "
                                                + "you may wish to retry your last action",
                                        "Server Error", JOptionPane.INFORMATION_MESSAGE);
                                log.error(tmp);
                                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                            }

                        });

                        return;
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                // }
            }
        } else {
            final JPanel parent = this;
            java.awt.EventQueue.invokeLater(new Runnable() {

                public void run() {
                    JOptionPane.showMessageDialog(parent, "Cancel action is not supported on this level",
                            "Message", JOptionPane.INFORMATION_MESSAGE);
                    setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                }

            });
        }
        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
    } else if (e.getActionCommand().equalsIgnoreCase("Delete")) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getSelectionPath().getLastPathComponent();
        QueryMasterData ndata = (QueryMasterData) node.getUserObject();
        Object selectedValue = JOptionPane.showConfirmDialog(this, "Delete Query \"" + ndata.name() + "\"?",
                "Delete Query Dialog", JOptionPane.YES_NO_OPTION);
        if (selectedValue.equals(JOptionPane.YES_OPTION)) {
            System.out.println("delete " + ndata.name());
            String requestXml = ndata.writeDeleteQueryXML();
            // System.out.println(requestXml);

            setCursor(new Cursor(Cursor.WAIT_CURSOR));

            String response = null;
            if (System.getProperty("webServiceMethod").equals("SOAP")) {
                // TO DO
                // response =
                // QueryListNamesClient.sendQueryRequestSOAP(requestXml);
            } else {
                response = QueryListNamesClient.sendQueryRequestREST(requestXml);
            }

            if (response.equalsIgnoreCase("CellDown")) {
                final JPanel parent = this;
                java.awt.EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        JOptionPane.showMessageDialog(parent,
                                "Trouble with connection to the remote server, "
                                        + "this is often a network error, please try again",
                                "Network Error", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
                setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
                return;
            }

            if (response != null) {
                JAXBUtil jaxbUtil = PreviousQueryJAXBUtil.getJAXBUtil();

                try {
                    JAXBElement jaxbElement = jaxbUtil.unMashallFromString(response);
                    ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
                    StatusType statusType = messageType.getResponseHeader().getResultStatus().getStatus();
                    String status = statusType.getType();

                    if (status.equalsIgnoreCase("DONE")) {
                        treeModel.removeNodeFromParent(node);

                        // jTree1.repaint();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        }
    } else if (e.getActionCommand().equalsIgnoreCase("Refresh All")) {
        String status = "";
        if (isManager) {
            status = loadPreviousQueries("all users");
        } else {
            status = loadPreviousQueries(UserInfoBean.getInstance().getUserName());
        }
        if (status.equalsIgnoreCase("")) {
            reset(200, false, false);
        } else if (status.equalsIgnoreCase("CellDown")) {
            final JPanel parent = this;
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    JOptionPane.showMessageDialog(parent,
                            "Trouble with connection to the remote server, "
                                    + "this is often a network error, please try again",
                            "Network Error", JOptionPane.INFORMATION_MESSAGE);
                }
            });
        }
    }
}