Example usage for javax.swing.tree DefaultMutableTreeNode DefaultMutableTreeNode

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

Introduction

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

Prototype

public DefaultMutableTreeNode(Object userObject) 

Source Link

Document

Creates a tree node with no parent, no children, but which allows children, and initializes it with the specified user object.

Usage

From source file:Creator.WidgetPanel.java

public void loadTree() {

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Widget Links");
    treeModel = new DefaultTreeModel(root, true);

    Map<String, DefaultMutableTreeNode> treeMap = new TreeMap<>();

    for (Entry<String, WidgetLink> entry : ws.getWidgetLinkEntrySet()) {

        String[] entryString = entry.getKey().split("-");

        if (!treeMap.containsKey(entryString[0])) {
            DefaultMutableTreeNode folder = new DefaultMutableTreeNode(entryString[0], true);
            treeMap.put(entryString[0], folder);
        }//from   w ww .ja  va 2  s  . c o  m

        DefaultMutableTreeNode child = new DefaultMutableTreeNode(entryString[1], true);

        // Add the fields of the widget link
        for (String s : entry.getValue().getTreeStrings()) {
            MutableTreeNode childStats = new DefaultMutableTreeNode(s, false);
            child.add(childStats);
        }

        //MutableTreeNode child = new DefaultMutableTreeNode(entry.getValue().getTreeStrings(entryString[1]), false);
        treeMap.get(entryString[0]).add(child);
    }

    for (Entry<String, DefaultMutableTreeNode> entry : treeMap.entrySet()) {
        root.add(entry.getValue());
    }

    _JTree_WidgetLinks.setModel(treeModel);

}

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

/**
 * This method is called from within the constructor to initialize the form.
 *//*from   w w  w  .  j a  va2  s  .c  o m*/
private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jClearButton = new javax.swing.JButton();
    jConstrainButton = new javax.swing.JButton();
    jExcludeButton = new javax.swing.JButton();
    jOccurrenceButton = new javax.swing.JButton();
    jNameLabel = new javax.swing.JLabel();
    jHintLabel = new javax.swing.JLabel();
    jTimingComboBox = new javax.swing.JComboBox();
    // jAnyvisitToggleButton = new javax.swing.JToggleButton();
    // jSamevisitToggleButton = new javax.swing.JToggleButton();

    setLayout(null);

    QueryConceptTreeNodeData tmpData = new QueryConceptTreeNodeData();
    tmpData.name("working ......");
    tmpData.tooltip("A root node");
    tmpData.visualAttribute("FAO");
    top = new DefaultMutableTreeNode(tmpData);
    // top = new DefaultMutableTreeNode("Root Node");
    treeModel = new DefaultTreeModel(top);
    // treeModel.addTreeModelListener(new MyTreeModelListener());

    jTree1 = new JTree(treeModel);

    jTree1.setDragEnabled(true);
    jTree1.setEditable(true);
    // jTree1.getSelectionModel().setSelectionMode
    // (TreeSelectionModel.SINGLE_TREE_SELECTION);
    // jTree1.setShowsRootHandles(true);
    // JScrollPane treeView = new JScrollPane(jTree1);
    jTree1.setRootVisible(false);
    jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    jTree1.setCellRenderer(new MyRenderer());
    ToolTipManager.sharedInstance().registerComponent(jTree1);

    setBorder(javax.swing.BorderFactory.createEtchedBorder());
    add(jScrollPane1);
    // jScrollPane1.setBounds(0, 40, 180, 200);

    jClearButton.setFont(new java.awt.Font("Tahoma", 1, 10));
    jClearButton.setText("X");
    jClearButton.setToolTipText("Clear all items from panel");
    jClearButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    jClearButton.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
    jClearButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
    if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
        jClearButton.setMargin(new java.awt.Insets(-10, -15, -10, -20));
    }
    jClearButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jClearButtonActionPerformed(evt);
        }
    });

    add(jClearButton);
    jClearButton.setBounds(160, 0, 18, 20);

    jConstrainButton.setText("Dates");
    jConstrainButton.setToolTipText("Constrain group by dates");
    jConstrainButton.setHorizontalTextPosition(javax.swing.SwingConstants.LEFT);
    jConstrainButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
    // jConstrainButton.setMargin(new java.awt.Insets(-10, -15, -10,-20));
    if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
        jConstrainButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        // jConstrainButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
        jConstrainButton.setMargin(new java.awt.Insets(-10, -15, -10, -20));
    }

    jConstrainButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jConstrainButtonActionPerformed(evt);
        }
    });

    add(jConstrainButton);
    jConstrainButton.setBounds(0, 20, 40, 21);

    jOccurrenceButton.setText("Occurs > 0x");
    jOccurrenceButton.setToolTipText("Set occurrence times");
    jOccurrenceButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jOccurrenceButton.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jOccurrenceButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
    if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
        jOccurrenceButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jOccurrenceButton.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jOccurrenceButton.setMargin(new java.awt.Insets(-10, -10, -10, -10));
    }
    jOccurrenceButton.setIconTextGap(0);
    jOccurrenceButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jOccurrenceButtonActionPerformed(evt);
        }
    });
    jOccurrenceButton.setBounds(40, 20, 90, 21);
    add(jOccurrenceButton);

    // jExcludeButton.setMnemonic('E');
    jExcludeButton.setText("Exclude");
    jExcludeButton.setToolTipText("Exclude all items in group");
    jExcludeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jExcludeButton.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jExcludeButton.setMargin(new java.awt.Insets(2, 2, 2, 2));
    if (System.getProperty("os.name").toLowerCase().indexOf("mac") > -1) {
        jExcludeButton.setMargin(new java.awt.Insets(-10, -15, -10, -20));
        jExcludeButton.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
    }
    jExcludeButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jExcludeButtonActionPerformed(evt);
        }
    });
    add(jExcludeButton);
    jExcludeButton.setBounds(130, 20, 48, 21);

    jNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jNameLabel.setText("Group 1");
    jNameLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
    jNameLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    add(jNameLabel);
    jNameLabel.setBounds(0, 0, 160, 20);
    jNameLabel.setTransferHandler(new GroupLabelTextHandler());
    jNameLabel.addMouseListener(new DragMouseAdapter());
    jNameLabel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
        public void mouseMoved(java.awt.event.MouseEvent evt) {
            jNameLabelMouseMoved(evt);
            // System.out.println("mouse x: "+evt.getX()+" y: "+evt.
            // getY());
            // System.out.println("name label x: "+jNameLabel.getX()+
            // " width: "+
            // jNameLabel.getWidth()+" y: "
            // +jNameLabel.getY()+" height "+jNameLabel.getHeight());
        }

    });
    jNameLabel.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseExited(java.awt.event.MouseEvent evt) {
            jNameLabelMouseExited(evt);
        }

    });

    /*
     * jAnyvisitToggleButton.setText("Any Visit");
     * add(jAnyvisitToggleButton); jAnyvisitToggleButton.setBounds(0, 40,
     * 89, 20);
     * 
     * jSamevisitToggleButton.setText("Same Visit");
     * add(jSamevisitToggleButton); jSamevisitToggleButton.setBounds(90, 40,
     * 88, 20);
     * 
     * ButtonGroup group = new ButtonGroup();
     * group.add(jAnyvisitToggleButton); group.add(jSamevisitToggleButton);
     * jAnyvisitToggleButton.setSelected(true);
     */

    jTree1.addTreeExpansionListener(this);
    jTree1.setTransferHandler(new TextHandler());
    add(jScrollPane1);
    jScrollPane1.setViewportView(jTree1);
    // jTree1.setToolTipText(
    // "Double click on a folder to view the items inside");
    // jScrollPane1.getViewport().setToolTipText(
    // "Double click on a folder to view the items inside");
    jScrollPane1.setBounds(0, 60, 180, 120);
    // jScrollPane1.setBounds(0, 60, 190, 270);
    // jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new
    // java.awt.Color(0, 0, 0)));
    // jTree1.addMouseMotionListener(new java.awt.event.MouseMotionAdapter()
    // {
    // public void mouseMoved(java.awt.event.MouseEvent evt) {
    // jScrollPane1MouseMoved(evt);
    // }

    // @Override
    // public void mouseDragged(MouseEvent e) {
    // jScrollPane1MouseMoved(e);
    // }

    // });
    // jTree1.addMouseListener(new java.awt.event.MouseAdapter() {
    // public void mouseExited(java.awt.event.MouseEvent evt) {
    // jScrollPane1MouseExited(evt);
    // }

    // @Override
    // public void mouseEntered(MouseEvent e) {

    // jScrollPane1MouseEntered(e);
    // }

    // });

    jHintLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    jHintLabel.setText(
            "<html><center>Drag terms from Navigate, <br>" + "<left>Find and Workplace into this group");
    // jHintLabel.getFont();
    jHintLabel.setFont(new Font("SansSerif", Font.PLAIN, 9));
    // jHintLabel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    jHintLabel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    jHintLabel.setVerticalAlignment(javax.swing.SwingConstants.CENTER);
    // jHintLabel.setBackground(Color.WHITE);
    // jHintLabel.setForeground(Color.WHITE);
    add(jHintLabel);
    jHintLabel.setBounds(0, 120, 180, 30);

    jTimingComboBox.setModel(new javax.swing.DefaultComboBoxModel(
            new String[] { "Treat Independently", "Occurs in Same Encounter", "Items instance will be same" }));
    jTimingComboBox.setAlignmentX(5.0F);
    ListCellRenderer renderer = new DefaultListCellRenderer();
    ((JLabel) renderer).setHorizontalAlignment(SwingConstants.CENTER);
    jTimingComboBox.setRenderer(renderer);
    // jTimingComboBox.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
    add(jTimingComboBox);
    jTimingComboBox.setBounds(1, 40, 177, 20);
    jTimingComboBox.setEnabled(false);
}

From source file:com.SE.myPlayer.MusicPlayerGUI.java

private void treeReferesh() {
        DefaultTreeModel myModel = (DefaultTreeModel) folder_Playlist_Tree.getModel();
        DefaultMutableTreeNode root = (DefaultMutableTreeNode) myModel.getRoot();
        root.removeAllChildren();//  ww w.  ja va  2s.  c  o  m

        DefaultMutableTreeNode library = new DefaultMutableTreeNode("library");
        DefaultMutableTreeNode playlist = new DefaultMutableTreeNode("playlist");

        myModel.insertNodeInto(library, root, root.getChildCount());
        myModel.insertNodeInto(playlist, root, root.getChildCount());

        try {
            con = db.getCon();
            stmt = con.createStatement();
            String node;

            ResultSet rs = stmt.executeQuery("select pn_name from playlist_name");

            while (rs.next()) {
                node = rs.getString(1);
                DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(node);
                myModel.insertNodeInto(newNode, playlist, playlist.getChildCount());
            }

            if (con != null) {
                stmt.close();
                con.close();
            }
        } catch (SQLException e) {
            System.out.println("Error in Stmt " + e);
        }

        myModel.reload();
        folder_Playlist_Tree.setModel(myModel);
    }

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Setup all the components/*  w  ww  .j a v  a  2 s. co m*/
 */
private void setupControls() {
    LOGGER.debug("setupControls");

    reasoningLevel = new JComboBox();
    for (ReasonerSelection reasoner : ReasonerSelection.values()) {
        reasoningLevel.addItem(reasoner);
    }
    reasoningLevel.setSelectedIndex(reasoningLevel.getItemCount() - 1);
    reasoningLevel.setToolTipText(((ReasonerSelection) reasoningLevel.getSelectedItem()).description());
    reasoningLevel.addActionListener(new ReasonerConfigurationChange());

    language = new JComboBox();
    language.addItem("Auto");
    for (String lang : FORMATS) {
        language.addItem(lang);
    }
    language.setSelectedIndex(0);

    assertedTripleCount = new JLabel(NOT_APPLICABLE_DISPLAY);
    assertedTripleCount.setHorizontalAlignment(JLabel.CENTER);
    inferredTripleCount = new JLabel(NOT_APPLICABLE_DISPLAY);
    inferredTripleCount.setHorizontalAlignment(JLabel.CENTER);

    runInferencing = new JButton("Create Model");
    runInferencing.setToolTipText(
            "Creates an ontology model using the provieed assertions " + "and the selected reasoning level");
    runInferencing.addActionListener(new ReasonerListener());

    runSparql = new JButton("Run Query");
    runSparql.addActionListener(new SparqlListener());

    sparqlServerInfo = new JLabel("Shutdown");
    sparqlServerInfo.setHorizontalAlignment(SwingConstants.CENTER);
    sparqlServerInfo.setBorder(BorderFactory.createTitledBorder("SPARQL Server Status"));

    proxyInfo = new JLabel("Disabled");
    proxyInfo.setHorizontalAlignment(SwingConstants.CENTER);
    proxyInfo.setBorder(BorderFactory.createTitledBorder("Proxy Status"));

    assertionsInput = new JTextArea(10, 50);
    assertionsInput.addKeyListener(new UserInputListener());
    assertionsInput.addCaretListener(new TextAreaCaratListener());

    inferredTriples = new JTextArea(10, 50);
    inferredTriples.setEditable(false);

    // SPARQL Input
    sparqlInput = new JTextArea(10, 50);
    sparqlInput.addKeyListener(new UserInputListener());
    sparqlInput.addCaretListener(new TextAreaCaratListener());

    // User id and password for accessing secured SPARQL endpoints
    sparqlServiceUserId = new JTextField(10);
    sparqlServicePassword = new JPasswordField(10);

    // SPARQL service URLs
    sparqlServiceUrl = new JComboBox();
    sparqlServiceUrl.setEditable(true);
    sparqlServiceUrl.addActionListener(new SparqlModelChoiceListener());
    sparqlServiceUrl.getEditor().getEditorComponent().addKeyListener(new UserInputListener());

    // Default graph if required
    defaultGraphUri = new JTextField();
    defaultGraphUri.setColumns(20);

    // Move through query history
    previousQuery = new JButton("Previous");
    previousQuery.addActionListener(new SparqlHistoryPreviousListener());
    nextQuery = new JButton("Next");
    nextQuery.addActionListener(new SparqlHistoryNextListener());

    // A basic default query
    sparqlInput.setText("select ?s ?p ?o where { ?s ?p ?o } limit 100");

    // Results table
    // sparqlResultsTable = new JTable(new SparqlTableModel());
    sparqlResultsTable = new JTable();

    // TODO Allow configuration to switch auto-resizing on/off (e.g. horizontal
    // scrolling)
    sparqlResultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    sparqlResultsTable.setAutoCreateRowSorter(true);

    // Determine whether alternate tree icons exist
    if (ImageLibrary.instance().getImageIcon(ImageLibrary.ICON_TREE_CLASS) != null) {
        replaceTreeImages = true;
    }

    LOGGER.debug("Tree renderer, specialized icons available? " + replaceTreeImages);

    // Create the tree UI with a default model
    ontModelTree = new JTree(new DefaultTreeModel(new DefaultMutableTreeNode("No Tree Generated")));

    ontModelTree.addMouseListener(new OntologyModelTreeMouseListener());

    if (replaceTreeImages) {
        ToolTipManager.sharedInstance().registerComponent(ontModelTree);
        ontModelTree.setCellRenderer(new OntologyTreeCellRenderer());
    }

    // Status label
    status = new JLabel("Initializing");
}

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

@SuppressWarnings("unchecked")
private List<ParameterInfo> createAndDisplayAParameterPanel(
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> batchParameters, final String title,
        final SubmodelInfo parent, final boolean submodelSelectionWithoutNotify,
        final IModelHandler currentModelHandler) {
    final List<ParameterMetaData> metadata = new LinkedList<ParameterMetaData>(),
            unknownFields = new ArrayList<ParameterMetaData>();
    for (final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> record : batchParameters) {
        final String parameterName = record.getName(), fieldName = StringUtils.uncapitalize(parameterName);
        Class<?> modelComponentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        while (true) {
            try {
                final Field field = modelComponentType.getDeclaredField(fieldName);
                final ParameterMetaData datum = new ParameterMetaData();
                for (final Annotation element : field.getAnnotations()) {
                    if (element.annotationType().getName() != Layout.class.getName()) // Proxies
                        continue;
                    final Class<? extends Annotation> type = element.annotationType();
                    datum.verboseDescription = (String) type.getMethod("VerboseDescription").invoke(element);
                    datum.banner = (String) type.getMethod("Title").invoke(element);
                    datum.fieldName = (String) " " + type.getMethod("FieldName").invoke(element);
                    datum.imageFileName = (String) type.getMethod("Image").invoke(element);
                    datum.layoutOrder = (Double) type.getMethod("Order").invoke(element);
                }//from  w w w . j a  va2  s .  c  om
                datum.parameter = record;
                if (datum.fieldName.trim().isEmpty())
                    datum.fieldName = parameterName.replaceAll("([A-Z])", " $1");
                metadata.add(datum);
                break;
            } catch (final SecurityException e) {
            } catch (final NoSuchFieldException e) {
            } catch (final IllegalArgumentException e) {
            } catch (final IllegalAccessException e) {
            } catch (final InvocationTargetException e) {
            } catch (final NoSuchMethodException e) {
            }
            modelComponentType = modelComponentType.getSuperclass();
            if (modelComponentType == null) {
                ParameterMetaData.createAndRegisterUnknown(fieldName, record, unknownFields);
                break;
            }
        }
    }
    Collections.sort(metadata);
    for (int i = unknownFields.size() - 1; i >= 0; --i)
        metadata.add(0, unknownFields.get(i));

    // initialize single run form
    final DefaultFormBuilder formBuilder = FormsUtils.build("p ~ p:g", "");
    appendMinimumWidthHintToPresentation(formBuilder, 550);

    if (parent == null) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                numberOfTurnsField.grabFocus();
            }
        });

        appendBannerToPresentation(formBuilder, "General Parameters");
        appendTextToPresentation(formBuilder, "Global parameters affecting the entire simulation");

        formBuilder.append(NUMBER_OF_TURNS_LABEL_TEXT, numberOfTurnsField);
        formBuilder.append(NUMBER_OF_TIMESTEPS_TO_IGNORE_LABEL_TEXT, numberTimestepsIgnored);

        appendCheckBoxFieldToPresentation(formBuilder, UPDATE_CHARTS_LABEL_TEXT, onLineChartsCheckBox);
        appendCheckBoxFieldToPresentation(formBuilder, DISPLAY_ADVANCED_CHARTS_LABEL_TEXT,
                advancedChartsCheckBox);
    }

    appendBannerToPresentation(formBuilder, title);

    final DefaultMutableTreeNode parentNode = (parent == null) ? parameterValueComponentTree
            : findParameterInfoNode(parent, false);

    final List<ParameterInfo> info = new ArrayList<ParameterInfo>();

    // Search for a @ConfigurationComponent annotation
    {
        String headerText = "", imagePath = "";
        final Class<?> parentType = parent == null ? currentModelHandler.getModelClass()
                : parent.getActualType();
        for (final Annotation element : parentType.getAnnotations()) { // Proxies
            if (element.annotationType().getName() != ConfigurationComponent.class.getName())
                continue;
            boolean doBreak = false;
            try {
                try {
                    headerText = (String) element.annotationType().getMethod("Description").invoke(element);
                    if (headerText.startsWith("#")) {
                        headerText = (String) parent.getActualType().getMethod(headerText.substring(1))
                                .invoke(parent.getInstance());
                    }
                    doBreak = true;
                } catch (IllegalArgumentException e) {
                } catch (SecurityException e) {
                } catch (IllegalAccessException e) {
                } catch (InvocationTargetException e) {
                } catch (NoSuchMethodException e) {
                }
            } catch (final Exception e) {
            }
            try {
                imagePath = (String) element.annotationType().getMethod("ImagePath").invoke(element);
                doBreak = true;
            } catch (IllegalArgumentException e) {
            } catch (SecurityException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            } catch (NoSuchMethodException e) {
            }
            if (doBreak)
                break;
        }
        if (!headerText.isEmpty())
            appendHeaderTextToPresentation(formBuilder, headerText);
        if (!imagePath.isEmpty())
            appendImageToPresentation(formBuilder, imagePath);
    }

    if (metadata.isEmpty()) {
        // No fields to display.
        appendTextToPresentation(formBuilder, "No configuration is required for this module.");
    } else {
        for (final ParameterMetaData record : metadata) {
            final ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> batchParameterInfo = record.parameter;

            if (!record.banner.isEmpty())
                appendBannerToPresentation(formBuilder, record.banner);
            if (!record.imageFileName.isEmpty())
                appendImageToPresentation(formBuilder, record.imageFileName);
            appendTextToPresentation(formBuilder, record.verboseDescription);

            final ParameterInfo parameterInfo = InfoConverter.parameterInfo2ParameterInfo(batchParameterInfo);
            if (parent != null && parameterInfo instanceof ISubmodelGUIInfo) {
                //               sgi.setParentValue(parent.getActualType());
            }

            final JComponent field;
            final DefaultMutableTreeNode oldNode = findParameterInfoNode(parameterInfo, true);
            Pair<ParameterInfo, JComponent> userData = null;
            JComponent oldField = null;
            if (oldNode != null) {
                userData = (Pair<ParameterInfo, JComponent>) oldNode.getUserObject();
                oldField = userData.getSecond();
            }

            if (parameterInfo.isBoolean()) {
                field = new JCheckBox();
                boolean value = oldField != null ? ((JCheckBox) oldField).isSelected()
                        : ((Boolean) batchParameterInfo.getDefaultValue()).booleanValue();
                ((JCheckBox) field).setSelected(value);
            } else if (parameterInfo.isEnum() || parameterInfo instanceof MasonChooserParameterInfo) {
                Object[] elements = null;
                if (parameterInfo.isEnum()) {
                    final Class<Enum<?>> type = (Class<Enum<?>>) parameterInfo.getJavaType();
                    elements = type.getEnumConstants();
                } else {
                    final MasonChooserParameterInfo chooserInfo = (MasonChooserParameterInfo) parameterInfo;
                    elements = chooserInfo.getValidStrings();
                }
                final JComboBox list = new JComboBox(elements);

                if (parameterInfo.isEnum()) {
                    final Object value = oldField != null ? ((JComboBox) oldField).getSelectedItem()
                            : parameterInfo.getValue();
                    list.setSelectedItem(value);
                } else {
                    final int value = oldField != null ? ((JComboBox) oldField).getSelectedIndex()
                            : (Integer) parameterInfo.getValue();
                    list.setSelectedIndex(value);
                }

                field = list;
            } else if (parameterInfo instanceof SubmodelInfo) {
                final SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                final Object[] elements = new Object[] { "Loading class information..." };
                final JComboBox list = new JComboBox(elements);
                //            field = list;

                final Object value = oldField != null
                        ? ((JComboBox) ((JPanel) oldField).getComponent(0)).getSelectedItem()
                        : new ClassElement(submodelInfo.getActualType(), null);

                new ClassCollector(this, list, submodelInfo, value, submodelSelectionWithoutNotify).execute();

                final JButton rightButton = new JButton();
                rightButton.setOpaque(false);
                rightButton.setRolloverEnabled(true);
                rightButton.setIcon(SHOW_SUBMODEL_ICON);
                rightButton.setRolloverIcon(SHOW_SUBMODEL_ICON_RO);
                rightButton.setDisabledIcon(SHOW_SUBMODEL_ICON_DIS);
                rightButton.setBorder(null);
                rightButton.setToolTipText("Display submodel parameters");
                rightButton.setActionCommand(ACTIONCOMMAND_SHOW_SUBMODEL);
                rightButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent arg0) {
                        if (parameterInfo instanceof SubmodelInfo) {
                            SubmodelInfo submodelInfo = (SubmodelInfo) parameterInfo;
                            int level = 0;

                            showHideSubparameters(list, submodelInfo);

                            List<String> components = new ArrayList<String>();
                            components.add(submodelInfo.getName());
                            while (submodelInfo.getParent() != null) {
                                submodelInfo = submodelInfo.getParent();
                                components.add(submodelInfo.getName());
                                level++;
                            }
                            Collections.reverse(components);
                            final String[] breadcrumbText = components.toArray(new String[components.size()]);
                            for (int i = 0; i < breadcrumbText.length; ++i)
                                breadcrumbText[i] = breadcrumbText[i].replaceAll("([A-Z])", " $1");
                            breadcrumb.setPath(
                                    currentModelHandler.getModelClassSimpleName().replaceAll("([A-Z])", " $1"),
                                    breadcrumbText);
                            Style.apply(breadcrumb, dashboard.getCssStyle());

                            // reset all buttons that are nested deeper than this to default color
                            for (int i = submodelButtons.size() - 1; i >= level; i--) {
                                JButton button = submodelButtons.get(i);
                                button.setIcon(SHOW_SUBMODEL_ICON);
                                submodelButtons.remove(i);
                            }

                            rightButton.setIcon(SHOW_SUBMODEL_ICON_RO);
                            submodelButtons.add(rightButton);
                        }
                    }
                });

                field = new JPanel(new BorderLayout());
                field.add(list, BorderLayout.CENTER);
                field.add(rightButton, BorderLayout.EAST);
            } else if (File.class.isAssignableFrom(parameterInfo.getJavaType())) {
                field = new JPanel(new BorderLayout());

                String oldName = "";
                String oldPath = "";
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldName = oldTextField.getText();
                    oldPath = oldTextField.getToolTipText();
                } else if (parameterInfo.getValue() != null) {
                    final File file = (File) parameterInfo.getValue();
                    oldName = file.getName();
                    oldPath = file.getAbsolutePath();
                }

                final JTextField textField = new JTextField(oldName);
                textField.setToolTipText(oldPath);
                textField.setInputVerifier(new InputVerifier() {

                    @Override
                    public boolean verify(final JComponent input) {
                        final JTextField inputField = (JTextField) input;
                        if (inputField.getText() == null || inputField.getText().isEmpty()) {
                            final File file = new File("");
                            inputField.setToolTipText(file.getAbsolutePath());
                            hideError();
                            return true;
                        }

                        final File oldFile = new File(inputField.getToolTipText());
                        if (oldFile.exists() && oldFile.getName().equals(inputField.getText().trim())) {
                            hideError();
                            return true;
                        }

                        inputField.setToolTipText("");
                        final File file = new File(inputField.getText().trim());
                        if (file.exists()) {
                            inputField.setToolTipText(file.getAbsolutePath());
                            inputField.setText(file.getName());
                            hideError();
                            return true;
                        } else {
                            final PopupFactory popupFactory = PopupFactory.getSharedInstance();
                            final Point locationOnScreen = inputField.getLocationOnScreen();
                            final JLabel message = new JLabel("Please specify an existing file!");
                            message.setBorder(new LineBorder(Color.RED, 2, true));
                            if (errorPopup != null)
                                errorPopup.hide();
                            errorPopup = popupFactory.getPopup(inputField, message, locationOnScreen.x - 10,
                                    locationOnScreen.y - 30);
                            errorPopup.show();
                            return false;
                        }
                    }
                });

                final JButton browseButton = new JButton(BROWSE_BUTTON_TEXT);
                browseButton.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        final JFileChooser fileDialog = new JFileChooser(
                                !"".equals(textField.getToolTipText()) ? textField.getToolTipText()
                                        : currentDirectory);
                        if (!"".equals(textField.getToolTipText()))
                            fileDialog.setSelectedFile(new File(textField.getToolTipText()));
                        int dialogResult = fileDialog.showOpenDialog(dashboard);
                        if (dialogResult == JFileChooser.APPROVE_OPTION) {
                            final File selectedFile = fileDialog.getSelectedFile();
                            if (selectedFile != null) {
                                currentDirectory = selectedFile.getAbsoluteFile().getParent();
                                textField.setText(selectedFile.getName());
                                textField.setToolTipText(selectedFile.getAbsolutePath());
                            }
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(browseButton, BorderLayout.EAST);
            } else if (parameterInfo instanceof MasonIntervalParameterInfo) {
                final MasonIntervalParameterInfo intervalInfo = (MasonIntervalParameterInfo) parameterInfo;

                field = new JPanel(new BorderLayout());

                String oldValueStr = String.valueOf(parameterInfo.getValue());
                if (oldField != null) {
                    final JTextField oldTextField = (JTextField) oldField.getComponent(0);
                    oldValueStr = oldTextField.getText();
                }

                final JTextField textField = new JTextField(oldValueStr);

                PercentJSlider tempSlider = null;
                if (intervalInfo.isDoubleInterval())
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().doubleValue(),
                            intervalInfo.getIntervalMax().doubleValue(), Double.parseDouble(oldValueStr));
                else
                    tempSlider = new PercentJSlider(intervalInfo.getIntervalMin().longValue(),
                            intervalInfo.getIntervalMax().longValue(), Long.parseLong(oldValueStr));

                final PercentJSlider slider = tempSlider;
                slider.setMajorTickSpacing(100);
                slider.setMinorTickSpacing(10);
                slider.setPaintTicks(true);
                slider.setPaintLabels(true);
                slider.addChangeListener(new ChangeListener() {
                    public void stateChanged(final ChangeEvent _) {
                        if (slider.hasFocus()) {
                            final String value = intervalInfo.isDoubleInterval()
                                    ? String.valueOf(slider.getDoubleValue())
                                    : String.valueOf(slider.getLongValue());
                            textField.setText(value);
                            slider.setToolTipText(value);
                        }
                    }
                });

                textField.setInputVerifier(new InputVerifier() {
                    public boolean verify(JComponent input) {
                        final JTextField inputField = (JTextField) input;

                        try {
                            hideError();
                            final String valueStr = inputField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else
                                    showError(
                                            "Please specify a value between " + intervalInfo.getIntervalMin()
                                                    + " and " + intervalInfo.getIntervalMax() + ".",
                                            inputField);
                                return false;
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr)) {
                                    slider.setValue(value);
                                    return true;
                                } else {
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", inputField);
                                    return false;
                                }
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, inputField);
                            return false;
                        }

                    }
                });

                textField.getDocument().addDocumentListener(new DocumentListener() {
                    //               private Popup errorPopup;

                    public void removeUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void insertUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    public void changedUpdate(final DocumentEvent _) {
                        textFieldChanged();
                    }

                    private void textFieldChanged() {
                        if (!textField.hasFocus()) {
                            hideError();
                            return;
                        }

                        try {
                            hideError();
                            final String valueStr = textField.getText().trim();
                            if (intervalInfo.isDoubleInterval()) {
                                final double value = Double.parseDouble(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify a value between " + intervalInfo.getIntervalMin()
                                            + " and " + intervalInfo.getIntervalMax() + ".", textField);
                            } else {
                                final long value = Long.parseLong(valueStr);
                                if (intervalInfo.isValidValue(valueStr))
                                    slider.setValue(value);
                                else
                                    showError("Please specify an integer value between "
                                            + intervalInfo.getIntervalMin() + " and "
                                            + intervalInfo.getIntervalMax() + ".", textField);
                            }
                        } catch (final NumberFormatException _) {
                            final String message = "The specified value is not a"
                                    + (intervalInfo.isDoubleInterval() ? "" : "n integer") + " number.";
                            showError(message, textField);
                        }
                    }
                });

                field.add(textField, BorderLayout.CENTER);
                field.add(slider, BorderLayout.SOUTH);
            } else {
                final Object value = oldField != null ? ((JTextField) oldField).getText()
                        : parameterInfo.getValue();
                field = new JTextField(value.toString());
                ((JTextField) field).addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(final ActionEvent e) {
                        wizard.clickDefaultButton();
                    }
                });
            }

            final JLabel parameterLabel = new JLabel(record.fieldName);

            final String description = parameterInfo.getDescription();
            if (description != null && !description.isEmpty()) {
                parameterLabel.addMouseListener(new MouseAdapter() {

                    @Override
                    public void mouseEntered(final MouseEvent e) {
                        final DescriptionPopupFactory popupFactory = DescriptionPopupFactory.getInstance();

                        final Popup parameterDescriptionPopup = popupFactory.getPopup(parameterLabel,
                                description, dashboard.getCssStyle());

                        parameterDescriptionPopup.show();
                    }

                });
            }

            if (oldNode != null)
                userData.setSecond(field);
            else {
                final Pair<ParameterInfo, JComponent> pair = new Pair<ParameterInfo, JComponent>(parameterInfo,
                        field);
                final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(pair);
                parentNode.add(newNode);
            }

            if (field instanceof JCheckBox) {
                parameterLabel
                        .setText("<html><div style=\"margin-bottom: 4pt; margin-top: 6pt; margin-left: 4pt\">"
                                + parameterLabel.getText() + "</div></html>");
                formBuilder.append(parameterLabel, field);

                //            appendCheckBoxFieldToPresentation(
                //               formBuilder, parameterLabel.getText(), (JCheckBox) field);
            } else {
                formBuilder.append(parameterLabel, field);
                final CellConstraints constraints = formBuilder.getLayout().getConstraints(parameterLabel);
                constraints.vAlign = CellConstraints.TOP;
                constraints.insets = new Insets(5, 0, 0, 0);
                formBuilder.getLayout().setConstraints(parameterLabel, constraints);
            }

            // prepare the parameterInfo for the param sweeps
            parameterInfo.setRuns(0);
            parameterInfo.setDefinitionType(ParameterInfo.CONST_DEF);
            parameterInfo.setValue(batchParameterInfo.getDefaultValue());
            info.add(parameterInfo);
        }
    }
    appendVerticalSpaceToPresentation(formBuilder);

    final JPanel panel = formBuilder.getPanel();
    singleRunParametersPanel.add(panel);

    if (singleRunParametersPanel.getComponentCount() > 1) {
        panel.setBorder(
                BorderFactory.createCompoundBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, Color.GRAY),
                        BorderFactory.createEmptyBorder(0, 5, 0, 5)));
    } else {
        panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    }

    Style.apply(panel, dashboard.getCssStyle());

    return info;
}

From source file:it.isislab.dmason.util.SystemManagement.Master.thrower.DMasonMaster.java

private void checkPeers() throws Exception {
    peers = master.getTopicList();//from www .j  av  a2  s . com
    for (String p : peers) {
        master.info(p);
        root.add(new DefaultMutableTreeNode(p));
    }
    labelWriteNumOfPeer.setText("" + peers.size());
}

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

private void addSubParametersToTree(final SubmodelInfo sInfo, final JTree tree,
        final DefaultMutableTreeNode node) {
    try {//from www  . j a va2 s  .  com
        final List<ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?>> subparameters = ParameterTreeUtils
                .fetchSubparameters(currentModelHandler, sInfo);

        final List<ParameterInfo> convertedSubparameters = new ArrayList<ParameterInfo>(subparameters.size());
        for (ai.aitia.meme.paramsweep.batch.param.ParameterInfo<?> parameterInfo : subparameters) {
            final ParameterInfo converted = InfoConverter.parameterInfo2ParameterInfo(parameterInfo);
            converted.setRuns(0);
            convertedSubparameters.add(converted);
        }
        Collections.sort(convertedSubparameters);

        final DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel();

        if (node.getChildCount() > 0) {
            node.removeAllChildren();
            treeModel.nodeStructureChanged(node);
        }

        for (final ParameterInfo pInfo : convertedSubparameters) {
            final DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(
                    new ParameterInATree(pInfo, currentModelHandler.getModelClass()));
            treeModel.insertNodeInto(newNode, node, node.getChildCount());

            if (pInfo instanceof SubmodelInfo) {
                final SubmodelInfo ssInfo = (SubmodelInfo) pInfo;
                if (ssInfo.getActualType() != null)
                    addSubParametersToTree(ssInfo, tree, newNode);
            }
        }

        //tree.expandPath(new TreePath(treeModel.getPathToRoot(node)));
    } catch (final ModelInformationException e) {
        sInfo.setActualType(null, null);
        JOptionPane.showMessageDialog(wizard, new JLabel(e.getMessage()), "Error while analyizing model",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
        submodelTypeBox.setSelectedIndex(0);
    }
}

From source file:lcmc.gui.resources.ServiceInfo.java

/**
 * Adds service panel to the position 'pos'.
 * TODO: is it used?/*from w ww.  jav  a2 s  .c  om*/
 */
public void addServicePanel(final ServiceInfo serviceInfo, final Point2D pos, final boolean colocation,
        final boolean order, final boolean reloadNode, final Host dcHost, final boolean testOnly) {
    final ResourceAgent ra = serviceInfo.getResourceAgent();
    if (ra != null) {
        serviceInfo.getService().setResourceClass(ra.getResourceClass());
    }
    if (getBrowser().getCRMGraph().addResource(serviceInfo, this, pos, colocation, order, testOnly)) {
        Tools.waitForSwing();
        /* edge added */
        if (isConstraintPH() || serviceInfo.isConstraintPH()) {
            final ConstraintPHInfo cphi;
            final ServiceInfo withService;
            final Set<ServiceInfo> withFrom = new TreeSet<ServiceInfo>();
            if (isConstraintPH()) {
                cphi = (ConstraintPHInfo) this;
                withService = serviceInfo;
            } else {
                cphi = (ConstraintPHInfo) serviceInfo;
                withService = this;
                withFrom.add(this);
            }
            withFrom.addAll(getBrowser().getCRMGraph().getParents(cphi));
            final Set<ServiceInfo> with = new TreeSet<ServiceInfo>();
            with.add(withService);
            cphi.addConstraintWithPlaceholder(with, withFrom, colocation, order, dcHost,
                    !cphi.getService().isNew(), testOnly);
            if (!testOnly) {
                final PcmkRscSetsInfo prsi = cphi.getPcmkRscSetsInfo();
                prsi.setApplyButtons(null, prsi.getParametersFromXML());
            }
        } else {
            final String parentId = getHeartbeatId(testOnly);
            final String heartbeatId = serviceInfo.getHeartbeatId(testOnly);
            final List<Map<String, String>> colAttrsList = new ArrayList<Map<String, String>>();
            final List<Map<String, String>> ordAttrsList = new ArrayList<Map<String, String>>();
            final Map<String, String> colAttrs = new LinkedHashMap<String, String>();
            final Map<String, String> ordAttrs = new LinkedHashMap<String, String>();
            colAttrs.put(CRMXML.SCORE_STRING, CRMXML.INFINITY_STRING);
            ordAttrs.put(CRMXML.SCORE_STRING, CRMXML.INFINITY_STRING);
            if (getService().isMaster()) {
                colAttrs.put("with-rsc-role", "Master");
                ordAttrs.put("first-action", "promote");
                ordAttrs.put("then-action", "start");
            }
            if (colocation) {
                colAttrsList.add(colAttrs);
            } else {
                colAttrsList.add(null);
            }
            if (order) {
                ordAttrsList.add(ordAttrs);
            } else {
                ordAttrsList.add(null);
            }
            if (!getService().isNew() && !serviceInfo.getService().isNew()) {
                CRM.setOrderAndColocation(dcHost, heartbeatId, new String[] { parentId }, colAttrsList,
                        ordAttrsList, testOnly);
            }
        }
    } else {
        getBrowser().addNameToServiceInfoHash(serviceInfo);
        final DefaultMutableTreeNode newServiceNode = new DefaultMutableTreeNode(serviceInfo);
        serviceInfo.setNode(newServiceNode);

        getBrowser().getServicesNode().add(newServiceNode);
        if (reloadNode) {
            getBrowser().reload(getBrowser().getServicesNode(), false);
            getBrowser().reload(newServiceNode, false);
        }
        getBrowser().reloadAllComboBoxes(serviceInfo);
    }
    if (reloadNode && ra != null && serviceInfo.getResource().isNew()) {
        if (ra.isProbablyMasterSlave()) {
            serviceInfo.changeType(MASTER_SLAVE_TYPE_STRING);
        } else if (ra.isProbablyClone()) {
            serviceInfo.changeType(CLONE_TYPE_STRING);
        }
    }
    getBrowser().getCRMGraph().reloadServiceMenus();
    if (reloadNode) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                getBrowser().getCRMGraph().scale();
            }
        });
    }
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Clears the tree model/*www . j  a  v  a 2s .  c om*/
 */
private void clearTree() {
    ontModelTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("No Tree Generated")));
    isTreeInSyncWithModel = true;
    colorCodeTabs();
}

From source file:com.monead.semantic.workbench.SemanticWorkbench.java

/**
 * Build a tree representation of the semantic model
 * //w w  w. jav a 2  s  . c o m
 * TODO aggregate items from duplicate nodes
 * 
 * TODO Consider more efficient approach that scans the model once rather than
 * querying for each class, individual and property collection
 * 
 * @see #addClassesToTree(DefaultMutableTreeNode, String)
 * @see OntologyTreeCellRenderer
 * 
 * @return The message to be presented on the status line
 */
private String createTreeFromModel() {
    final String messagePrefix = "Creating the tree view";
    DefaultMutableTreeNode treeTopNode;
    DefaultMutableTreeNode classesNode;
    String message;
    int maxIndividualsPerClass;

    setStatus(messagePrefix);
    setWaitCursor(true);

    clearTree();

    try {
        maxIndividualsPerClass = Integer.parseInt(
                properties.getProperty(ConfigurationProperty.MAX_INDIVIDUALS_PER_CLASS_IN_TREE.key(), "0"));
    } catch (Throwable throwable) {
        maxIndividualsPerClass = 0;
    }

    treeTopNode = new DefaultMutableTreeNode("Model");

    // Ignore latest value since we have just released the old tree (if there
    // was one)
    MemoryWarningSystem.hasLatestAvailableTenuredGenAfterCollectionChanged(this);

    // Classes
    classesNode = new DefaultMutableTreeNode("Classes");
    treeTopNode.add(classesNode);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Building list of classes in the model");
    }

    try {
        addClassesToTree(classesNode, maxIndividualsPerClass, messagePrefix);

        // Select the tree view tab
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                tabbedPane.setSelectedIndex(TAB_NUMBER_TREE_VIEW);
            }
        });

        message = "Tree view of current model created";
        if (maxIndividualsPerClass > 0) {
            message += " (individuals per class limited to " + maxIndividualsPerClass + ")";
        }

        ontModelTree.setModel(new DefaultTreeModel(treeTopNode));
        isTreeInSyncWithModel = true;
        colorCodeTabs();
    } catch (IllegalStateException ise) {
        // Memory exhaustion, keep the incomplete tree
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                tabbedPane.setSelectedIndex(TAB_NUMBER_TREE_VIEW);
            }
        });
        message = "Insufficient memory for entire tree, partial tree view of current model created";
        ontModelTree.setModel(new DefaultTreeModel(treeTopNode));
        isTreeInSyncWithModel = false;
        colorCodeTabs();
        throw ise;
    } catch (RuntimeException rte) {
        if (rte.getMessage().contains("canceled by user")) {
            message = rte.getMessage();
        } else {
            throw rte;
        }
    }

    return message;
}