Search in sources :

Example 61 with TreeSelectionListener

use of javax.swing.event.TreeSelectionListener in project intellij-community by JetBrains.

the class TemplateListPanel method createTable.

private JPanel createTable() {
    myTreeRoot = new CheckedTreeNode(null);
    myTree = new LiveTemplateTree(new CheckboxTree.CheckboxTreeCellRenderer() {

        @Override
        public void customizeRenderer(final JTree tree, Object value, final boolean selected, final boolean expanded, final boolean leaf, final int row, final boolean hasFocus) {
            if (!(value instanceof DefaultMutableTreeNode))
                return;
            value = ((DefaultMutableTreeNode) value).getUserObject();
            if (value instanceof TemplateImpl) {
                TemplateImpl template = (TemplateImpl) value;
                TemplateImpl defaultTemplate = TemplateSettings.getInstance().getDefaultTemplate(template);
                Color fgColor = defaultTemplate != null && templatesDiffer(template, defaultTemplate) ? JBColor.BLUE : null;
                getTextRenderer().append(template.getKey(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, fgColor));
                String description = template.getDescription();
                if (StringUtil.isNotEmpty(description)) {
                    getTextRenderer().append(" (" + description + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
                }
            } else if (value instanceof TemplateGroup) {
                getTextRenderer().append(((TemplateGroup) value).getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
            }
        }
    }, myTreeRoot, this);
    myTree.setRootVisible(false);
    myTree.setShowsRootHandles(true);
    myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
    myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(@NotNull final TreeSelectionEvent e) {
            TemplateSettings templateSettings = TemplateSettings.getInstance();
            TemplateImpl template = getTemplate(getSingleSelectedIndex());
            if (template != null) {
                templateSettings.setLastSelectedTemplate(template.getGroupName(), template.getKey());
            } else {
                templateSettings.setLastSelectedTemplate(null, null);
                showEmptyCard();
            }
            if (myUpdateNeeded) {
                myAlarm.cancelAllRequests();
                myAlarm.addRequest(() -> updateTemplateDetails(false, false), 100);
            }
        }
    });
    myTree.registerKeyboardAction(new ActionListener() {

        @Override
        public void actionPerformed(@Nullable ActionEvent event) {
            myCurrentTemplateEditor.focusKey();
        }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
    installPopup();
    DnDSupport.createBuilder(myTree).setBeanProvider((NullableFunction<DnDActionInfo, DnDDragStartBean>) dnDActionInfo -> {
        Point point = dnDActionInfo.getPoint();
        if (myTree.getPathForLocation(point.x, point.y) == null)
            return null;
        Map<TemplateImpl, DefaultMutableTreeNode> templates = getSelectedTemplates();
        return !templates.isEmpty() ? new DnDDragStartBean(templates) : null;
    }).setDisposableParent(this).setTargetChecker(new DnDTargetChecker() {

        @Override
        public boolean update(DnDEvent event) {
            @SuppressWarnings("unchecked") Set<String> oldGroupNames = getAllGroups((Map<TemplateImpl, DefaultMutableTreeNode>) event.getAttachedObject());
            TemplateGroup group = getDropGroup(event);
            boolean differentGroup = group != null && !oldGroupNames.contains(group.getName());
            event.setDropPossible(differentGroup, "");
            return true;
        }
    }).setDropHandler(new DnDDropHandler() {

        @Override
        public void drop(DnDEvent event) {
            //noinspection unchecked
            moveTemplates((Map<TemplateImpl, DefaultMutableTreeNode>) event.getAttachedObject(), ObjectUtils.assertNotNull(getDropGroup(event)).getName());
        }
    }).setImageProvider((NullableFunction<DnDActionInfo, DnDImage>) dnDActionInfo -> {
        Point point = dnDActionInfo.getPoint();
        TreePath path = myTree.getPathForLocation(point.x, point.y);
        return path == null ? null : new DnDImage(DnDAwareTree.getDragImage(myTree, path, point).first);
    }).install();
    if (myTemplateGroups.size() > 0) {
        myTree.setSelectionInterval(0, 0);
    }
    return initToolbar().createPanel();
}
Also used : ActionEvent(java.awt.event.ActionEvent) TreeSelectionListener(javax.swing.event.TreeSelectionListener) NullableFunction(com.intellij.util.NullableFunction) ActionListener(java.awt.event.ActionListener) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent)

Example 62 with TreeSelectionListener

use of javax.swing.event.TreeSelectionListener in project intellij-community by JetBrains.

the class PackageChooserDialog method createCenterPanel.

protected JComponent createCenterPanel() {
    JPanel panel = new JPanel();
    panel.setLayout(new BorderLayout());
    myModel = new DefaultTreeModel(new DefaultMutableTreeNode());
    createTreeModel();
    myTree = new Tree(myModel);
    UIUtil.setLineStyleAngled(myTree);
    myTree.setCellRenderer(new DefaultTreeCellRenderer() {

        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            setIcon(PlatformIcons.PACKAGE_ICON);
            if (value instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object object = node.getUserObject();
                if (object instanceof PsiPackage) {
                    String name = ((PsiPackage) object).getName();
                    if (name != null && name.length() > 0) {
                        setText(name);
                    } else {
                        setText(IdeBundle.message("node.default"));
                    }
                }
            }
            return this;
        }
    });
    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(myTree);
    scrollPane.setPreferredSize(JBUI.size(500, 300));
    new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {

        public String convert(TreePath path) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            Object object = node.getUserObject();
            if (object instanceof PsiPackage)
                return ((PsiPackage) object).getName();
            else
                return "";
        }
    });
    myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent e) {
            PsiPackage selection = getTreeSelection();
            if (selection != null) {
                String name = selection.getQualifiedName();
                setTitle(myTitle + " - " + ("".equals(name) ? IdeBundle.message("node.default.package") : name));
            } else {
                setTitle(myTitle);
            }
            updatePathFromTree();
        }
    });
    panel.add(scrollPane, BorderLayout.CENTER);
    DefaultActionGroup group = createActionGroup(myTree);
    final JPanel northPanel = new JPanel(new BorderLayout());
    panel.add(northPanel, BorderLayout.NORTH);
    ActionToolbar toolBar = ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, true);
    northPanel.add(toolBar.getComponent(), BorderLayout.WEST);
    setupPathComponent(northPanel);
    return panel;
}
Also used : DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) TreeSpeedSearch(com.intellij.ui.TreeSpeedSearch) TreeSelectionListener(javax.swing.event.TreeSelectionListener) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) DefaultTreeCellRenderer(javax.swing.tree.DefaultTreeCellRenderer) TreePath(javax.swing.tree.TreePath) Tree(com.intellij.ui.treeStructure.Tree) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent)

Example 63 with TreeSelectionListener

use of javax.swing.event.TreeSelectionListener in project intellij-community by JetBrains.

the class MapExternalResourceDialog method setupSchemasTree.

private void setupSchemasTree(String uri, @NotNull Project project, @Nullable PsiFile file, @Nullable String location) {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode();
    mySchemasTree.setModel(new DefaultTreeModel(root));
    ConfigFileSearcher searcher = new ConfigFileSearcher(file == null ? null : ModuleUtilCore.findModuleForPsiElement(file), project) {

        @Override
        public Set<PsiFile> search(@Nullable Module module, @NotNull Project project) {
            List<IndexedRelevantResource<String, XsdNamespaceBuilder>> resources = XmlNamespaceIndex.getAllResources(module, project, null);
            HashSet<PsiFile> files = new HashSet<>();
            PsiManager psiManager = PsiManager.getInstance(project);
            for (IndexedRelevantResource<String, XsdNamespaceBuilder> resource : resources) {
                VirtualFile file = resource.getFile();
                PsiFile psiFile = psiManager.findFile(file);
                ContainerUtil.addIfNotNull(files, psiFile);
            }
            return files;
        }
    };
    searcher.search();
    new ConfigFilesTreeBuilder(mySchemasTree).buildTree(root, searcher);
    TreeUtil.expandAll(mySchemasTree);
    mySchemasTree.setRootVisible(false);
    mySchemasTree.setShowsRootHandles(true);
    ColoredTreeCellRenderer renderer = new ColoredTreeCellRenderer() {

        @Override
        public void customizeCellRenderer(@NotNull JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            ConfigFilesTreeBuilder.renderNode(value, expanded, this);
        }
    };
    renderer.setFont(EditorColorsManager.getInstance().getGlobalScheme().getFont(EditorFontType.PLAIN));
    mySchemasTree.setCellRenderer(renderer);
    MouseAdapter mouseAdapter = new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() > 1 && isOKActionEnabled()) {
                doOKAction();
            }
        }
    };
    mySchemasTree.addMouseListener(mouseAdapter);
    mySchemasTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            validateInput();
        }
    });
    mySchemasTree.setSelectionRow(0);
    PsiFile schema = null;
    if (file != null) {
        schema = XmlUtil.findNamespaceByLocation(file, uri);
    } else if (location != null) {
        VirtualFile virtualFile = VfsUtilCore.findRelativeFile(location, null);
        if (virtualFile != null) {
            schema = PsiManager.getInstance(project).findFile(virtualFile);
        }
    }
    if (schema != null) {
        DefaultMutableTreeNode node = TreeUtil.findNodeWithObject(root, schema);
        if (node != null) {
            mySchemaFound = true;
            TreeUtil.selectNode(mySchemasTree, node);
        }
        myFileTextField.setText(schema.getVirtualFile().getCanonicalPath());
    }
}
Also used : VirtualFile(com.intellij.openapi.vfs.VirtualFile) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) TreeSelectionListener(javax.swing.event.TreeSelectionListener) NotNull(org.jetbrains.annotations.NotNull) IndexedRelevantResource(com.intellij.xml.index.IndexedRelevantResource) ConfigFilesTreeBuilder(com.intellij.xml.config.ConfigFilesTreeBuilder) PsiFile(com.intellij.psi.PsiFile) HashSet(java.util.HashSet) ColoredTreeCellRenderer(com.intellij.ui.ColoredTreeCellRenderer) MouseEvent(java.awt.event.MouseEvent) MouseAdapter(java.awt.event.MouseAdapter) PsiManager(com.intellij.psi.PsiManager) XsdNamespaceBuilder(com.intellij.xml.index.XsdNamespaceBuilder) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) Project(com.intellij.openapi.project.Project) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent) Module(com.intellij.openapi.module.Module) Nullable(org.jetbrains.annotations.Nullable) ConfigFileSearcher(com.intellij.xml.config.ConfigFileSearcher)

Example 64 with TreeSelectionListener

use of javax.swing.event.TreeSelectionListener in project JMRI by JMRI.

the class PaneProgDp3Action method actionPerformed.

@Override
public void actionPerformed(ActionEvent e) {
    // NOI18N
    log.debug("Pane programmer requested");
    if (f == null) {
        log.debug("found f==null");
        // create the initial frame that steers
        // NOI18N
        f = new JmriJFrame(apps.gui3.dp3.Bundle.getMessage("FrameProgrammerSetup"));
        f.getContentPane().setLayout(new BorderLayout());
        // ensure status line is cleared on close so it is normal if re-opened
        f.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent we) {
                // NOI18N
                statusLabel.setText(SymbolicProgBundle.getMessage("StateIdle"));
                f.windowClosing(we);
            }
        });
        // add the Roster menu
        JMenuBar menuBar = new JMenuBar();
        // NOI18N
        JMenu j = new JMenu(SymbolicProgBundle.getMessage("MenuFile"));
        // NOI18N
        j.add(new jmri.jmrit.decoderdefn.PrintDecoderListAction(SymbolicProgBundle.getMessage("MenuPrintDecoderDefinitions"), f, false));
        // NOI18N
        j.add(new jmri.jmrit.decoderdefn.PrintDecoderListAction(SymbolicProgBundle.getMessage("MenuPrintPreviewDecoderDefinitions"), f, true));
        menuBar.add(j);
        // NOI18N
        menuBar.add(new jmri.jmrit.roster.swing.RosterMenu(SymbolicProgBundle.getMessage("MenuRoster"), jmri.jmrit.roster.swing.RosterMenu.MAINMENU, f));
        f.setJMenuBar(menuBar);
        final JPanel bottomPanel = new JPanel(new BorderLayout());
        // new Loco on programming track
        combinedLocoSelTree = new CombinedLocoSelTreePane(statusLabel, modePane) {

            @Override
            protected void startProgrammer(DecoderFile decoderFile, RosterEntry re, String progName) {
                // progName is ignored here
                log.debug("startProgrammer");
                String title = // NOI18N
                java.text.MessageFormat.format(// NOI18N
                SymbolicProgBundle.getMessage("FrameServiceProgrammerTitle"), // NOI18N
                new Object[] { Bundle.getMessage("NewDecoder") });
                if (re != null) {
                    title = // NOI18N
                    java.text.MessageFormat.format(// NOI18N
                    SymbolicProgBundle.getMessage("FrameServiceProgrammerTitle"), new Object[] { re.getId() });
                }
                JFrame p;
                if (!modePane.isSelected() || modePane.getProgrammer() == null) {
                    p = new PaneProgFrame(decoderFile, re, // NOI18N
                    title, // NOI18N
                    "programmers" + File.separator + "Comprehensive.xml", null, false) {

                        @Override
                        protected JPanel getModePane() {
                            return null;
                        }
                    };
                } else {
                    p = new PaneServiceProgFrame(decoderFile, re, // NOI18N
                    title, // NOI18N
                    "programmers" + File.separator + "Comprehensive.xml", modePane.getProgrammer());
                }
                p.pack();
                p.setVisible(true);
            }

            @Override
            protected void openNewLoco() {
                log.debug("openNewLoco");
                // find the decoderFile object
                DecoderFile decoderFile = DecoderIndexFile.instance().fileFromTitle(selectedDecoderType());
                // NOI18N
                log.debug("decoder file: {}", decoderFile.getFilename());
                if (rosterIdField.getText().equals(SymbolicProgBundle.getMessage("LabelNewDecoder"))) {
                    // NOI18N
                    re = new RosterEntry();
                    re.setDecoderFamily(decoderFile.getFamily());
                    re.setDecoderModel(decoderFile.getModel());
                    // NOI18N
                    re.setId(SymbolicProgBundle.getMessage("LabelNewDecoder"));
                    //re.writeFile(cvModel, iCvModel, variableModel );
                    // note that we're leaving the filename null
                    // add the new roster entry to the in-memory roster
                    Roster.getDefault().addEntry(re);
                } else {
                    try {
                        saveRosterEntry();
                    } catch (JmriException ex) {
                        // NOI18N
                        log.warn("Exception while saving roster entry", ex);
                        return;
                    }
                }
                // create a dummy RosterEntry with the decoder info
                // no programmer name in this case
                startProgrammer(decoderFile, re, "");
                //Set our roster entry back to null so that a fresh roster entry can be created if needed
                re = null;
            }

            @Override
            protected JPanel layoutRosterSelection() {
                log.debug("layoutRosterSelection");
                return null;
            }

            @Override
            protected JPanel layoutDecoderSelection() {
                log.debug("layoutDecoderSelection");
                JPanel pan = super.layoutDecoderSelection();
                dTree.removeTreeSelectionListener(dListener);
                dTree.addTreeSelectionListener(dListener = new TreeSelectionListener() {

                    @Override
                    public void valueChanged(TreeSelectionEvent e) {
                        if (!dTree.isSelectionEmpty() && dTree.getSelectionPath() != null && // check that this isn't just a model
                        ((TreeNode) dTree.getSelectionPath().getLastPathComponent()).isLeaf() && // can't be just a mfg, has to be at least a family
                        dTree.getSelectionPath().getPathCount() > 2 && // can't be a multiple decoder selection
                        dTree.getSelectionCount() < 2) {
                            log.debug("Selection event with " + dTree.getSelectionPath().toString());
                            //if (locoBox != null) locoBox.setSelectedIndex(0);
                            go2.setEnabled(true);
                            go2.setRequestFocusEnabled(true);
                            go2.requestFocus();
                            // NOI18N
                            go2.setToolTipText(SymbolicProgBundle.getMessage("TipClickToOpen"));
                            decoderFile = DecoderIndexFile.instance().fileFromTitle(selectedDecoderType());
                            setUpRosterPanel();
                        } else {
                            decoderFile = null;
                            // decoder not selected - require one
                            go2.setEnabled(false);
                            // NOI18N
                            go2.setToolTipText(SymbolicProgBundle.getMessage("TipSelectLoco"));
                            setUpRosterPanel();
                        }
                    }
                });
                return pan;
            }

            @Override
            protected void selectDecoder(int mfgID, int modelID, int productID) {
                log.debug("selectDecoder");
                //On selecting a new decoder start a fresh with a new roster entry
                super.selectDecoder(mfgID, modelID, productID);
                findDecoderAddress();
            }

            @Override
            protected JPanel createProgrammerSelection() {
                log.debug("createProgrammerSelection");
                JPanel pane3a = new JPanel();
                pane3a.setLayout(new BoxLayout(pane3a, BoxLayout.Y_AXIS));
                // NOI18N
                go2 = new JButton(Bundle.getMessage("OpenProgrammer"));
                go2.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent e) {
                        // NOI18N
                        log.debug("Open programmer pressed");
                        openButton();
                        // close this window to prevent having
                        // two windows processing at the same time
                        //
                        // Alternately, could have just cleared out a 
                        // bunch of stuff to force starting over, but 
                        // that seems to be an even more confusing
                        // user experience.
                        log.debug("Closing f {}", f);
                        WindowEvent wev = new WindowEvent(f, WindowEvent.WINDOW_CLOSING);
                        java.awt.Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(wev);
                    }
                });
                go2.setAlignmentX(JLabel.RIGHT_ALIGNMENT);
                go2.setEnabled(false);
                // NOI18N
                go2.setToolTipText(SymbolicProgBundle.getMessage("TipSelectLoco"));
                bottomPanel.add(go2, BorderLayout.EAST);
                return pane3a;
            }
        };
        // load primary frame
        JPanel topPanel = new JPanel();
        topPanel.add(modePane);
        topPanel.add(new JSeparator(javax.swing.SwingConstants.HORIZONTAL));
        f.getContentPane().add(topPanel, BorderLayout.NORTH);
        //f.getContentPane().add(modePane);
        //f.getContentPane().add(new JSeparator(javax.swing.SwingConstants.HORIZONTAL));
        combinedLocoSelTree.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        f.getContentPane().add(combinedLocoSelTree, BorderLayout.CENTER);
        //f.getContentPane().add(new JSeparator(javax.swing.SwingConstants.HORIZONTAL));
        //basicRoster.setEnabled(false);
        statusLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
        bottomPanel.add(statusLabel, BorderLayout.SOUTH);
        f.getContentPane().add(bottomPanel, BorderLayout.SOUTH);
        f.pack();
        // NOI18N
        log.debug("Tab-Programmer setup created");
    } else {
        re = null;
        combinedLocoSelTree.resetSelections();
    }
    f.setVisible(true);
}
Also used : JPanel(javax.swing.JPanel) DecoderFile(jmri.jmrit.decoderdefn.DecoderFile) PaneProgFrame(jmri.jmrit.symbolicprog.tabbedframe.PaneProgFrame) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) WindowAdapter(java.awt.event.WindowAdapter) TreeSelectionListener(javax.swing.event.TreeSelectionListener) jmri(jmri) JSeparator(javax.swing.JSeparator) BorderLayout(java.awt.BorderLayout) JmriJFrame(jmri.util.JmriJFrame) JFrame(javax.swing.JFrame) TreeNode(javax.swing.tree.TreeNode) PaneServiceProgFrame(jmri.jmrit.symbolicprog.tabbedframe.PaneServiceProgFrame) CombinedLocoSelTreePane(jmri.jmrit.symbolicprog.CombinedLocoSelTreePane) ActionListener(java.awt.event.ActionListener) JmriJFrame(jmri.util.JmriJFrame) WindowEvent(java.awt.event.WindowEvent) RosterEntry(jmri.jmrit.roster.RosterEntry) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent) JMenuBar(javax.swing.JMenuBar) JMenu(javax.swing.JMenu)

Example 65 with TreeSelectionListener

use of javax.swing.event.TreeSelectionListener in project JMRI by JMRI.

the class EcosLocoToRoster method layoutDecoderSelection.

//@TODO this could do with being re-written so that it reuses the combined loco select tree code
protected JPanel layoutDecoderSelection() {
    JPanel pane1a = new JPanel();
    pane1a.setLayout(new BoxLayout(pane1a, BoxLayout.X_AXIS));
    // create the list of manufacturers; get the list of decoders, and add elements
    dRoot = new DefaultMutableTreeNode("Root");
    dModel = new DefaultTreeModel(dRoot);
    dTree = new JTree(dModel) {

        @Override
        public String getToolTipText(MouseEvent evt) {
            if (getRowForLocation(evt.getX(), evt.getY()) == -1) {
                return null;
            }
            TreePath curPath = getPathForLocation(evt.getX(), evt.getY());
            return ((DecoderTreeNode) curPath.getLastPathComponent()).getToolTipText();
        }
    };
    dTree.setToolTipText("");
    List<DecoderFile> decoders = DecoderIndexFile.instance().matchingDecoderList(null, null, null, null, null, null);
    int len = decoders.size();
    DefaultMutableTreeNode mfgElement = null;
    DefaultMutableTreeNode familyElement = null;
    for (int i = 0; i < len; i++) {
        DecoderFile decoder = decoders.get(i);
        String mfg = decoder.getMfg();
        String family = decoder.getFamily();
        String model = decoder.getModel();
        log.debug(" process " + mfg + "/" + family + "/" + model + " on nodes " + (mfgElement == null ? "<null>" : mfgElement.toString() + "(" + mfgElement.getChildCount() + ")") + "/" + (familyElement == null ? "<null>" : familyElement.toString() + "(" + familyElement.getChildCount() + ")"));
        // build elements
        if (mfgElement == null || !mfg.equals(mfgElement.toString())) {
            // need new mfg node
            mfgElement = new DecoderTreeNode(mfg, "CV8 = " + DecoderIndexFile.instance().mfgIdFromName(mfg), "");
            dModel.insertNodeInto(mfgElement, dRoot, dRoot.getChildCount());
            familyElement = null;
        }
        String famComment = decoders.get(i).getFamilyComment();
        String verString = decoders.get(i).getVersionsAsString();
        String hoverText = "";
        if (famComment == null || famComment.equals("")) {
            if (verString != null && !verString.equals("")) {
                hoverText = "CV7=" + verString;
            }
        } else {
            if (verString == null || verString.equals("")) {
                hoverText = famComment;
            } else {
                hoverText = famComment + "  CV7=" + verString;
            }
        }
        if (familyElement == null || !family.equals(familyElement.toString())) {
            // appears to have decoder names separate from the family name
            if ((i + 2 >= len) || decoders.get(i + 2).getFamily().equals(family) || !decoders.get(i + 1).getModel().equals(family)) {
                // normal here; insert the new family element & exit
                log.debug("normal family update case: " + family);
                familyElement = new DecoderTreeNode(family, hoverText, decoders.get(i).titleString());
                dModel.insertNodeInto(familyElement, mfgElement, mfgElement.getChildCount());
                continue;
            } else {
                // this is short case; insert decoder entry (next) here
                log.debug("short case, i=" + i + " family=" + family + " next " + decoders.get(i + 1).getModel());
                if (i + 1 > len) {
                    log.error("Unexpected single entry for family: " + family);
                }
                family = decoders.get(i + 1).getModel();
                familyElement = new DecoderTreeNode(family, hoverText, decoders.get(i).titleString());
                dModel.insertNodeInto(familyElement, mfgElement, mfgElement.getChildCount());
                i = i + 1;
                continue;
            }
        }
        // insert at the decoder level, except if family name is the same
        if (!family.equals(model)) {
            dModel.insertNodeInto(new DecoderTreeNode(model, hoverText, decoders.get(i).titleString()), familyElement, familyElement.getChildCount());
        }
    }
    // end of loop over decoders
    // build the tree GUI
    pane1a.add(new JScrollPane(dTree));
    dTree.expandPath(new TreePath(dRoot));
    dTree.setRootVisible(false);
    dTree.setShowsRootHandles(true);
    dTree.setScrollsOnExpand(true);
    dTree.setExpandsSelectedPaths(true);
    dTree.getSelectionModel().setSelectionMode(DefaultTreeSelectionModel.SINGLE_TREE_SELECTION);
    // tree listener
    dTree.addTreeSelectionListener(dListener = new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            if (!dTree.isSelectionEmpty() && dTree.getSelectionPath() != null && // can't be just a mfg, has to be at least a family
            dTree.getSelectionPath().getPathCount() > 2 && // can't be a multiple decoder selection
            dTree.getSelectionCount() < 2) {
                // decoder selected - reset and disable loco selection
                log.debug("Selection event with " + dTree.getSelectionPath().toString());
                if (locoBox != null) {
                    locoBox.setSelectedIndex(0);
                }
            }
        }
    });
    //      Mouselistener for doubleclick activation of proprammer   
    dTree.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent me) {
            // Clear any status messages and ensure the tree is in single path select mode
            //if (_statusLabel != null) _statusLabel.setText("StateIdle");
            dTree.getSelectionModel().setSelectionMode(DefaultTreeSelectionModel.SINGLE_TREE_SELECTION);
            /* check for both double click and that it's a decoder 
                 that is being clicked on.  If it's just a Family, the programmer
                 button is enabled by the TreeSelectionListener, but we don't
                 want to automatically open a programmer so a user has the opportunity
                 to select an individual decoder
                 */
            if (me.getClickCount() == 2) {
                if (((TreeNode) dTree.getSelectionPath().getLastPathComponent()).isLeaf()) {
                    okayButton();
                }
            }
        }
    });
    this.selectDecoder(ecosLoco.getCVAsString(8), ecosLoco.getCVAsString(7));
    return pane1a;
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) DecoderFile(jmri.jmrit.decoderdefn.DecoderFile) MouseEvent(java.awt.event.MouseEvent) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) BoxLayout(javax.swing.BoxLayout) MouseAdapter(java.awt.event.MouseAdapter) TreeSelectionListener(javax.swing.event.TreeSelectionListener) DefaultTreeModel(javax.swing.tree.DefaultTreeModel) JTree(javax.swing.JTree) TreePath(javax.swing.tree.TreePath) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent)

Aggregations

TreeSelectionListener (javax.swing.event.TreeSelectionListener)87 TreeSelectionEvent (javax.swing.event.TreeSelectionEvent)82 DefaultMutableTreeNode (javax.swing.tree.DefaultMutableTreeNode)36 TreePath (javax.swing.tree.TreePath)33 JTree (javax.swing.JTree)27 JScrollPane (javax.swing.JScrollPane)25 ActionEvent (java.awt.event.ActionEvent)23 JPanel (javax.swing.JPanel)22 ActionListener (java.awt.event.ActionListener)20 MouseEvent (java.awt.event.MouseEvent)16 DefaultTreeModel (javax.swing.tree.DefaultTreeModel)16 BorderLayout (java.awt.BorderLayout)14 Dimension (java.awt.Dimension)14 GridBagConstraints (java.awt.GridBagConstraints)12 GridBagLayout (java.awt.GridBagLayout)12 Insets (java.awt.Insets)12 JButton (javax.swing.JButton)11 Tree (com.intellij.ui.treeStructure.Tree)10 KeyAdapter (java.awt.event.KeyAdapter)9 KeyEvent (java.awt.event.KeyEvent)9