Example usage for javax.swing.event TreeWillExpandListener TreeWillExpandListener

List of usage examples for javax.swing.event TreeWillExpandListener TreeWillExpandListener

Introduction

In this page you can find the example usage for javax.swing.event TreeWillExpandListener TreeWillExpandListener.

Prototype

TreeWillExpandListener

Source Link

Usage

From source file:TreeExpandSample.java

public static void main(String args[]) {
    String title = ("JTree Expand Sample");
    JFrame frame = new JFrame(title);
    JTree tree = new JTree();
    TreeWillExpandListener treeWillExpandListener = new TreeWillExpandListener() {
        public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException {
            TreePath path = treeExpansionEvent.getPath();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            String data = node.getUserObject().toString();
            if (data.equals("colors")) {
                throw new ExpandVetoException(treeExpansionEvent);
            }/* w  ww  .  j av  a2 s  . c  o  m*/
        }

        public void treeWillExpand(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException {
            TreePath path = treeExpansionEvent.getPath();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            String data = node.getUserObject().toString();
            if (data.equals("sports")) {
                throw new ExpandVetoException(treeExpansionEvent);
            }
        }
    };
    tree.addTreeWillExpandListener(treeWillExpandListener);
    JScrollPane scrollPane = new JScrollPane(tree);
    frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);
}

From source file:Main.java

public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    root.add(new DefaultMutableTreeNode("A"));
    root.add(new DefaultMutableTreeNode("B"));
    root.add(new DefaultMutableTreeNode("C"));
    JTree tree = new JTree(root);

    TreeWillExpandListener treeWillExpandListener = new TreeWillExpandListener() {
        public void treeWillCollapse(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException {
            TreePath path = treeExpansionEvent.getPath();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            String data = node.getUserObject().toString();
            System.out.println("WillCollapse: " + data);

        }//from   ww  w.j a v a  2s .co m

        public void treeWillExpand(TreeExpansionEvent treeExpansionEvent) throws ExpandVetoException {
            TreePath path = treeExpansionEvent.getPath();
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
            String data = node.getUserObject().toString();
            System.out.println("WillExpand: " + data);

        }
    };

    tree.addTreeWillExpandListener(treeWillExpandListener);

    JScrollPane scrollPane = new JScrollPane(tree);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);

}

From source file:Main.java

public static void main(String[] args) throws Exception {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    MyTreeNode root = new MyTreeNode(1, 0);
    DefaultTreeModel model = new DefaultTreeModel(root);
    JProgressBar bar = new JProgressBar();
    PropertyChangeListener progressListener = new PropertyChangeListener() {
        @Override//from   w  w  w .j av  a 2  s.  c o m
        public void propertyChange(PropertyChangeEvent evt) {
            bar.setValue((Integer) evt.getNewValue());
        }
    };
    JTree tree = new JTree();
    tree.setShowsRootHandles(true);
    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            TreePath path = event.getPath();
            if (path.getLastPathComponent() instanceof MyTreeNode) {
                MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
                node.loadChildren(model, progressListener);
            }
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {

        }
    });
    tree.setModel(model);
    root.loadChildren(model, progressListener);
    frame.add(new JScrollPane(tree));
    frame.add(bar, BorderLayout.SOUTH);
    frame.pack();
    frame.setVisible(true);
}

From source file:de.codesourcery.eve.skills.ui.model.impl.MarketGroupTreeModelBuilder.java

public void attach(JTree tree) {
    if (tree == null) {
        throw new IllegalArgumentException("tree cannot be NULL");
    }//from  www. j a  v a2  s .  c o m

    if (this.tree != null && this.tree != tree) {
        throw new IllegalStateException("Already attached to " + this.tree);
    }

    this.tree = tree;
    this.tree.setModel(getTreeModel());

    this.tree.addTreeWillExpandListener(new TreeWillExpandListener() {

        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            final ITreeNode node = (ITreeNode) event.getPath().getLastPathComponent();
            fetchChildren(node, false);
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }
    });
}

From source file:gov.sandia.umf.platform.ui.jobs.RunPanel.java

public RunPanel() {
    root = new NodeBase();
    model = new DefaultTreeModel(root);
    tree = new JTree(model);
    tree.setRootVisible(false);/*from  w  w w  .j a  v a 2 s  .  c  o m*/
    tree.setShowsRootHandles(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);

    tree.setCellRenderer(new DefaultTreeCellRenderer() {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
                boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);

            NodeBase node = (NodeBase) value;
            Icon icon = node.getIcon(expanded); // A node knows whether it should hold other nodes or not, so don't pass leaf to it.
            if (icon == null) {
                if (leaf)
                    icon = getDefaultLeafIcon();
                else if (expanded)
                    icon = getDefaultOpenIcon();
                else
                    icon = getDefaultClosedIcon();
            }
            setIcon(icon);

            return this;
        }
    });

    tree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent e) {
            NodeBase newNode = (NodeBase) tree.getLastSelectedPathComponent();
            if (newNode == null)
                return;
            if (newNode == displayNode)
                return;

            if (displayThread != null)
                synchronized (displayText) {
                    displayThread.stop = true;
                }
            displayNode = newNode;
            if (displayNode instanceof NodeFile)
                viewFile();
            else if (displayNode instanceof NodeJob)
                viewJob();
        }
    });

    tree.addKeyListener(new KeyAdapter() {
        public void keyPressed(KeyEvent e) {
            int keycode = e.getKeyCode();
            if (keycode == KeyEvent.VK_DELETE || keycode == KeyEvent.VK_BACK_SPACE) {
                delete();
            }
        }
    });

    tree.addTreeWillExpandListener(new TreeWillExpandListener() {
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            TreePath path = event.getPath(); // TODO: can this ever be null?
            Object o = path.getLastPathComponent();
            if (o instanceof NodeJob)
                ((NodeJob) o).build(tree);
        }

        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }
    });

    tree.addTreeExpansionListener(new TreeExpansionListener() {
        public void treeExpanded(TreeExpansionEvent event) {
            Rectangle node = tree.getPathBounds(event.getPath());
            Rectangle visible = treePane.getViewport().getViewRect();
            visible.height -= node.y - visible.y;
            visible.y = node.y;
            tree.repaint(visible);
        }

        public void treeCollapsed(TreeExpansionEvent event) {
            Rectangle node = tree.getPathBounds(event.getPath());
            Rectangle visible = treePane.getViewport().getViewRect();
            visible.height -= node.y - visible.y;
            visible.y = node.y;
            tree.repaint(visible);
        }
    });

    Thread refreshThread = new Thread() {
        public void run() {
            try {
                // Initial load
                synchronized (running) {
                    for (MNode n : AppData.runs)
                        running.add(0, new NodeJob(n)); // This should be efficient on a doubly-linked list.
                    for (NodeJob job : running)
                        root.add(job);
                }
                EventQueue.invokeLater(new Runnable() {
                    public void run() {
                        model.nodeStructureChanged(root);
                        if (model.getChildCount(root) > 0)
                            tree.setSelectionRow(0);
                    }
                });

                // Periodic refresh to show status of running jobs
                int shortCycles = 100; // Force full scan on first cycle.
                while (true) {
                    NodeBase d = displayNode; // Make local copy (atomic action) to prevent it changing from under us
                    if (d instanceof NodeJob)
                        ((NodeJob) d).monitorProgress(RunPanel.this);
                    if (shortCycles++ < 20) {
                        Thread.sleep(1000);
                        continue;
                    }
                    shortCycles = 0;

                    synchronized (running) {
                        Iterator<NodeJob> i = running.iterator();
                        while (i.hasNext()) {
                            NodeJob job = i.next();
                            if (job != d)
                                job.monitorProgress(RunPanel.this);
                            if (job.complete >= 1)
                                i.remove();
                        }
                    }
                }
            } catch (InterruptedException e) {
            }
        }
    };
    refreshThread.setDaemon(true);
    refreshThread.start();

    displayText = new JTextArea();
    displayText.setEditable(false);

    final JCheckBox chkFixedWidth = new JCheckBox("Fixed-Width Font");
    chkFixedWidth.setFocusable(false);
    chkFixedWidth.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            int size = displayText.getFont().getSize();
            if (chkFixedWidth.isSelected()) {
                displayText.setFont(new Font(Font.MONOSPACED, Font.PLAIN, size));
            } else {
                displayText.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, size));
            }
        }
    });

    displayPane.setViewportView(displayText);

    ActionListener graphListener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (displayNode instanceof NodeFile) {
                NodeFile nf = (NodeFile) displayNode;
                if (nf.type == NodeFile.Type.Output || nf.type == NodeFile.Type.Result) {
                    String graphType = e.getActionCommand();
                    if (displayPane.getViewport().getView() instanceof ChartPanel
                            && displayGraph.equals(graphType)) {
                        viewFile();
                        displayGraph = "";
                    } else {
                        if (graphType.equals("Graph")) {
                            Plot plot = new Plot(nf.path.getAbsolutePath());
                            if (!plot.columns.isEmpty())
                                displayPane.setViewportView(plot.createGraphPanel());
                        } else // Raster
                        {
                            Raster raster = new Raster(nf.path.getAbsolutePath(), displayPane.getHeight());
                            displayPane.setViewportView(raster.createGraphPanel());
                        }
                        displayGraph = graphType;
                    }
                }
            }
        }
    };

    buttonGraph = new JButton("Graph", ImageUtil.getImage("analysis.gif"));
    buttonGraph.setFocusable(false);
    buttonGraph.addActionListener(graphListener);
    buttonGraph.setActionCommand("Graph");

    buttonRaster = new JButton("Raster", ImageUtil.getImage("prnplot.gif"));
    buttonRaster.setFocusable(false);
    buttonRaster.addActionListener(graphListener);
    buttonRaster.setActionCommand("Raster");

    Lay.BLtg(this, "C",
            Lay.SPL(Lay.BL("C", treePane = Lay.sp(tree)), Lay.BL("N",
                    Lay.FL(chkFixedWidth, Lay.FL(buttonGraph, buttonRaster), "hgap=50"), "C", displayPane),
                    "divpixel=250"));
    setFocusCycleRoot(true);
}

From source file:de.codesourcery.eve.skills.ui.components.impl.ItemChooserComponent.java

@Override
protected JPanel createPanelHook() {

    tree.setRootVisible(false);/* w w w  . j  ava 2  s .  c om*/
    tree.setCellRenderer(treeRenderer);

    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    tree.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() != 2 || e.isPopupTrigger()) {
                return;
            }

            final TreePath path = tree.getClosestPathForLocation(e.getX(), e.getY());
            final ITreeNode node = (ITreeNode) path.getLastPathComponent();

            if (node.getValue() instanceof InventoryType) {
                final InventoryType selectedItem = (InventoryType) node.getValue();
                selectedItemsModel.addItem(selectedItem);
                if (selectionMode == SelectionMode.SINGLE_SELECTION) {
                    okButtonClicked();
                } else if (selectionMode == SelectionMode.MULTIPLE_SELECTION) {
                    // ok
                } else {
                    throw new RuntimeException("Unhandled mode " + selectionMode);
                }
            }
        }
    });

    tree.addTreeWillExpandListener(new TreeWillExpandListener() {

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }

        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            handleTreeExpansion(event);
        }
    });

    final JScrollPane pane = new JScrollPane(tree);
    pane.setPreferredSize(new Dimension(400, 400));

    final JPanel result = new JPanel();
    result.setLayout(new GridBagLayout());

    switch (selectionMode) {
    case SINGLE_SELECTION:
        result.add(pane, constraints().useRemainingSpace().resizeBoth().end());
        break;
    case MULTIPLE_SELECTION:
        result.add(pane, constraints(0, 0).useRelativeWidth().resizeBoth().end());
        result.add(createListViewPanel(), constraints(1, 0).useRemainingWidth().resizeBoth().end());
        break;
    default:
        throw new RuntimeException("Unhandled selection mode" + selectionMode);
    }

    return result;
}

From source file:com.orthancserver.SelectImageDialog.java

public SelectImageDialog() {
    tree_ = new JTree();

    tree_.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override/*from  ww  w . j av a2 s .c  o m*/
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            TreePath path = event.getPath();
            if (path.getLastPathComponent() instanceof MyTreeNode) {
                MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
                node.LoadChildren((DefaultTreeModel) tree_.getModel());
            }
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
        }
    });

    tree_.addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent e) {
            TreePath path = e.getNewLeadSelectionPath();
            if (path != null) {
                MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
                if (node.UpdatePreview(preview_)) {
                    selectedType_ = node.GetResourceType();
                    selectedUuid_ = node.GetUuid();
                    selectedConnection_ = node.GetConnection();
                    okButton_.setEnabled(true);
                }

                removeServer_.setEnabled(node.GetResourceType() == ResourceType.SERVER);
            }
        }
    });

    tree_.addMouseListener(new MouseAdapter() {
        public void mousePressed(MouseEvent e) {
            TreePath path = tree_.getPathForLocation(e.getX(), e.getY());
            if (path != null) {
                MyTreeNode node = (MyTreeNode) path.getLastPathComponent();
                if (e.getClickCount() == 2 && node.GetResourceType() == ResourceType.INSTANCE) {
                    // Double click on an instance, close the dialog
                    isSuccess_ = true;
                    setVisible(false);
                }
            }
        }
    });

    final JPanel contentPanel = new JPanel();
    getContentPane().setLayout(new BorderLayout());
    contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
    getContentPane().add(contentPanel, BorderLayout.CENTER);
    contentPanel.setLayout(new BorderLayout(0, 0));
    {
        JSplitPane splitPane = new JSplitPane();
        splitPane.setResizeWeight(0.6);
        contentPanel.add(splitPane);

        splitPane.setLeftComponent(new JScrollPane(tree_));
        splitPane.setRightComponent(preview_);
    }
    {
        JPanel buttonPane = new JPanel();
        buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
        {
            JButton btnAddServer = new JButton("Add server");
            btnAddServer.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg) {
                    OrthancConfigurationDialog dd = new OrthancConfigurationDialog();
                    dd.setLocationRelativeTo(null); // Center dialog on screen

                    OrthancConnection orthanc = dd.ShowModal();
                    if (orthanc != null) {
                        AddOrthancServer(orthanc);
                        ((DefaultTreeModel) tree_.getModel()).reload();
                    }
                }
            });
            buttonPane.add(btnAddServer);
        }

        {
            buttonPane.add(removeServer_);
            removeServer_.setEnabled(false);

            removeServer_.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg) {
                    MyTreeNode selected = (MyTreeNode) tree_.getLastSelectedPathComponent();
                    if (selected.GetResourceType() == ResourceType.SERVER && JOptionPane.showConfirmDialog(null,
                            "Remove server \"" + selected.getUserObject() + "\"?", "WARNING",
                            JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                        ((DefaultTreeModel) tree_.getModel()).removeNodeFromParent(selected);
                    }
                }
            });
        }

        {
            okButton_.setEnabled(false);
            okButton_.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg) {
                    isSuccess_ = true;
                    setVisible(false);
                }
            });
            buttonPane.add(okButton_);
            getRootPane().setDefaultButton(okButton_);
        }
        {
            JButton cancelButton = new JButton("Cancel");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg) {
                    setVisible(false);
                }
            });
            buttonPane.add(cancelButton);
        }
    }

    setUndecorated(false);
    setSize(500, 500);
    setTitle("Select some series or some instance in Orthanc");
    setModal(true);
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplateImportDialog.java

private void initComponents() {
    setBackground(UIConstants.BACKGROUND_COLOR);
    getContentPane().setBackground(getBackground());

    topPanel = new JPanel();
    topPanel.setBackground(getBackground());

    linkPanel = new JPanel();
    linkPanel.setBackground(topPanel.getBackground());

    linkLeftPanel = new JPanel();
    linkLeftPanel.setBackground(linkPanel.getBackground());

    linkLeftSelectAllLabel = new JLabel("<html><u>All</u></html>");
    linkLeftSelectAllLabel.setForeground(Color.BLUE);
    linkLeftSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkLeftSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                importTreeTable.getModel().setValueAt(true, row, IMPORT_SELECTED_COLUMN);
            }/* ww  w  . ja va  2  s  .  c om*/
        }
    });

    linkLeftDeselectAllLabel = new JLabel("<html><u>None</u></html>");
    linkLeftDeselectAllLabel.setForeground(Color.BLUE);
    linkLeftDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkLeftDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                importTreeTable.getModel().setValueAt(false, row, IMPORT_SELECTED_COLUMN);
            }
        }
    });

    linkRightPanel = new JPanel();
    linkRightPanel.setBackground(linkPanel.getBackground());

    linkRightOverwriteAllLabel = new JLabel("<html><u>All</u></html>");
    linkRightOverwriteAllLabel.setForeground(Color.BLUE);
    linkRightOverwriteAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkRightOverwriteAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                TreePath path = importTreeTable.getPathForRow(row);
                if (path != null) {
                    ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent();
                    if (node instanceof ImportLibraryTreeTableNode) {
                        ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node;
                        if (libraryNode.getConflicts().getMatchingLibrary() != null) {
                            importTreeTable.getModel().setValueAt(true, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    } else if (node instanceof ImportCodeTemplateTreeTableNode) {
                        ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node;
                        if (codeTemplateNode.getConflicts().getMatchingCodeTemplate() != null) {
                            importTreeTable.getModel().setValueAt(true, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    }
                }
            }
        }
    });

    linkRightOverwriteNoneLabel = new JLabel("<html><u>None</u></html>");
    linkRightOverwriteNoneLabel.setForeground(Color.BLUE);
    linkRightOverwriteNoneLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    linkRightOverwriteNoneLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            for (int row = 0; row < importTreeTable.getRowCount(); row++) {
                TreePath path = importTreeTable.getPathForRow(row);
                if (path != null) {
                    ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent();
                    if (node instanceof ImportLibraryTreeTableNode) {
                        ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node;
                        if (libraryNode.getConflicts().getMatchingLibrary() != null) {
                            importTreeTable.getModel().setValueAt(false, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    } else if (node instanceof ImportCodeTemplateTreeTableNode) {
                        ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node;
                        if (codeTemplateNode.getConflicts().getMatchingCodeTemplate() != null) {
                            importTreeTable.getModel().setValueAt(false, row, IMPORT_OVERWRITE_COLUMN);
                        }
                    }
                }
            }
        }
    });

    final TableCellEditor templateCellEditor = new NameCellEditor();

    importTreeTable = new JXTreeTable() {
        @Override
        public boolean isCellEditable(int row, int column) {
            return (column == IMPORT_OVERWRITE_COLUMN || column == IMPORT_SELECTED_COLUMN
                    || column == IMPORT_NAME_COLUMN);
        }

        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return templateCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

    importTreeTable.setLargeModel(true);
    DefaultTreeTableModel model = new ImportTreeTableModel();
    model.setColumnIdentifiers(Arrays.asList(new String[] { "", "Name", "Overwrite", "Conflicts", "Id" }));

    DefaultMutableTreeTableNode rootNode = new DefaultMutableTreeTableNode();
    model.setRoot(rootNode);
    importTreeTable.setTreeTableModel(model);

    Set<String> addedCodeTemplateIds = new HashSet<String>();

    if (unassignedCodeTemplates) {
        ImportTreeTableNode libraryNode = new ImportUnassignedLibraryTreeTableNode("Select a library", "");
        CodeTemplateLibrary library = importLibraries.get(0);

        for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
            if (!addedCodeTemplateIds.contains(codeTemplate.getId())) {
                libraryNode
                        .add(new ImportCodeTemplateTreeTableNode(codeTemplate.getName(), codeTemplate.getId()));
                addedCodeTemplateIds.add(codeTemplate.getId());
                importCodeTemplateMap.put(codeTemplate.getId(), codeTemplate);
            }
        }

        rootNode.add(libraryNode);
    } else {
        Set<String> addedLibraryIds = new HashSet<String>();

        for (CodeTemplateLibrary library : importLibraries) {
            if (!addedLibraryIds.contains(library.getId())) {
                ImportTreeTableNode libraryNode = new ImportLibraryTreeTableNode(library.getName(),
                        library.getId());
                importLibraryMap.put(library.getId(), library);

                for (CodeTemplate codeTemplate : library.getCodeTemplates()) {
                    if (!addedCodeTemplateIds.contains(codeTemplate.getId())) {
                        libraryNode.add(new ImportCodeTemplateTreeTableNode(codeTemplate.getName(),
                                codeTemplate.getId()));
                        addedCodeTemplateIds.add(codeTemplate.getId());
                        importCodeTemplateMap.put(codeTemplate.getId(), codeTemplate);
                    }
                }

                rootNode.add(libraryNode);
                addedLibraryIds.add(library.getId());
            }
        }
    }

    importTreeTable.setOpenIcon(null);
    importTreeTable.setClosedIcon(null);
    importTreeTable.setLeafIcon(null);
    importTreeTable.setRootVisible(false);
    importTreeTable.setDoubleBuffered(true);
    importTreeTable.setDragEnabled(false);
    importTreeTable.setRowSelectionAllowed(true);
    importTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    importTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    importTreeTable.setFocusable(true);
    importTreeTable.setOpaque(true);
    importTreeTable.getTableHeader().setReorderingAllowed(false);
    importTreeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    importTreeTable.setEditable(true);
    importTreeTable.setSortable(false);
    importTreeTable.setAutoCreateColumnsFromModel(false);
    importTreeTable.setShowGrid(true, true);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        importTreeTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    importTreeTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelection(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelection(evt);
        }

        private void checkSelection(MouseEvent evt) {
            int row = importTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY()));

            if (row < 0) {
                importTreeTable.clearSelection();
            }
        }
    });

    importTreeTable.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
            throw new ExpandVetoException(event);
        }
    });

    importTreeTable.setTreeCellRenderer(new NameCellRenderer());

    importTreeTable.getModel().addTableModelListener(new TableModelListener() {
        @Override
        public void tableChanged(TableModelEvent evt) {
            if (evt.getColumn() != IMPORT_CONFLICTS_COLUMN) {
                for (int row = evt.getFirstRow(); row <= evt.getLastRow()
                        && row < importTreeTable.getRowCount(); row++) {
                    TreePath path = importTreeTable.getPathForRow(row);
                    if (path != null) {
                        ImportTreeTableNode node = (ImportTreeTableNode) path.getLastPathComponent();

                        if (path.getPathCount() == 2) {
                            if (node instanceof ImportUnassignedLibraryTreeTableNode) {
                                String libraryName = (String) node.getValueAt(IMPORT_NAME_COLUMN);
                                String libraryId = null;
                                for (CodeTemplateLibrary library : PlatformUI.MIRTH_FRAME.codeTemplatePanel
                                        .getCachedCodeTemplateLibraries().values()) {
                                    if (library.getName().equals(libraryName)) {
                                        libraryId = library.getId();
                                        break;
                                    }
                                }
                                node.setValueAt(libraryId, IMPORT_ID_COLUMN);
                            } else if (node instanceof ImportLibraryTreeTableNode) {
                                ImportLibraryTreeTableNode libraryNode = (ImportLibraryTreeTableNode) node;
                                libraryNode.setConflicts(getLibraryConflicts(node));
                            }

                            for (Enumeration<? extends TreeTableNode> codeTemplateNodes = node
                                    .children(); codeTemplateNodes.hasMoreElements();) {
                                ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) codeTemplateNodes
                                        .nextElement();
                                codeTemplateNode.setConflicts(getCodeTemplateConflicts(codeTemplateNode));
                            }

                            importTreeTable.updateUI();
                        } else if (path.getPathCount() == 3) {
                            ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) node;
                            codeTemplateNode.setConflicts(getCodeTemplateConflicts(node));
                        }
                    }
                }
            }

            updateImportButton();
            updateErrorsAndWarnings();
        }
    });

    importTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting()) {
                updateImportButton();
                updateErrorsAndWarnings();
            }
        }
    });

    importTreeTable.expandAll();

    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN).setMinWidth(20);
    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN).setMaxWidth(20);
    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN)
            .setCellRenderer(new ImportSelectedCellRenderer());
    importTreeTable.getColumnModel().getColumn(IMPORT_SELECTED_COLUMN)
            .setCellEditor(new ImportSelectedCellEditor());

    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN).setMinWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN).setMaxWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN)
            .setCellRenderer(new OverwriteCellRenderer());
    importTreeTable.getColumnModel().getColumn(IMPORT_OVERWRITE_COLUMN)
            .setCellEditor(new OverwriteCellEditor());

    importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setMinWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setMaxWidth(60);
    importTreeTable.getColumnModel().getColumn(IMPORT_CONFLICTS_COLUMN).setCellRenderer(new IconCellRenderer());

    importTreeTable.getColumnModel().removeColumn(importTreeTable.getColumnModel().getColumn(IMPORT_ID_COLUMN));

    importTreeTableScrollPane = new JScrollPane(importTreeTable);
    importTreeTableScrollPane.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, new Color(0x6E6E6E)));

    warningsPanel = new JPanel();
    warningsPanel.setBackground(getBackground());
    warningsPanel.setVisible(false);

    warningsLabel = new JLabel(UIConstants.ICON_WARNING);

    warningsTextArea = new JTextArea();
    warningsTextArea.setLineWrap(true);
    warningsTextArea.setWrapStyleWord(true);

    errorsPanel = new JPanel();
    errorsPanel.setBackground(getBackground());
    errorsPanel.setVisible(false);

    errorsLabel = new JLabel(UIConstants.ICON_ERROR);

    errorsTextArea = new JTextArea();
    errorsTextArea.setLineWrap(true);
    errorsTextArea.setWrapStyleWord(true);

    separator = new JSeparator();

    buttonPanel = new JPanel();
    buttonPanel.setBackground(getBackground());

    importButton = new JButton("Import");
    importButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            try {
                boolean warnings = false;
                for (Enumeration<? extends TreeTableNode> libraryNodes = ((TreeTableNode) importTreeTable
                        .getTreeTableModel().getRoot()).children(); libraryNodes.hasMoreElements();) {
                    for (Enumeration<? extends TreeTableNode> codeTemplateNodes = libraryNodes.nextElement()
                            .children(); codeTemplateNodes.hasMoreElements();) {
                        ImportCodeTemplateTreeTableNode codeTemplateNode = (ImportCodeTemplateTreeTableNode) codeTemplateNodes
                                .nextElement();

                        if ((boolean) codeTemplateNode.getValueAt(IMPORT_SELECTED_COLUMN)) {
                            CodeTemplateConflicts conflicts = codeTemplateNode.getConflicts();
                            if (conflicts.getMatchingCodeTemplate() != null) {
                                warnings = true;
                                break;
                            }
                        }
                    }

                    if (warnings) {
                        break;
                    }
                }

                if (!warnings || PlatformUI.MIRTH_FRAME.alertOption(CodeTemplateImportDialog.this,
                        "Some selected rows have warnings. Are you sure you wish to continue?")) {
                    save();
                    dispose();
                }
            } catch (Exception e) {
                PlatformUI.MIRTH_FRAME.alertThrowable(CodeTemplateImportDialog.this, e,
                        "Unable to import: " + e.getMessage());
            }
        }
    });

    cancelButton = new JButton("Cancel");
    cancelButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            if (confirmClose()) {
                dispose();
            }
        }
    });

    updateImportButton();
}

From source file:com.mirth.connect.client.ui.codetemplate.CodeTemplatePanel.java

private void initComponents() {
    splitPane = new JSplitPane();
    splitPane.setBackground(getBackground());
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    splitPane.setBorder(BorderFactory.createEmptyBorder());
    splitPane.setOneTouchExpandable(true);
    splitPane.setDividerLocation(/*from  w  w  w . j  a  v a 2s.c  o  m*/
            Preferences.userNodeForPackage(Mirth.class).getInt("height", UIConstants.MIRTH_HEIGHT) / 3);
    splitPane.setResizeWeight(0.5);

    topPanel = new JPanel();
    topPanel.setBackground(UIConstants.COMBO_BOX_BACKGROUND);

    final CodeTemplateTreeTableCellEditor templateCellEditor = new CodeTemplateTreeTableCellEditor(this);

    templateTreeTable = new MirthTreeTable("CodeTemplate", new HashSet<String>(
            Arrays.asList(new String[] { "Name", "Description", "Revision", "Last Modified" }))) {

        private TreeTableNode selectedNode;

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == TEMPLATE_NAME_COLUMN;
        }

        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return templateCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }

        @Override
        protected void beforeSort() {
            updateCurrentNode();
            updateCurrentNode.set(false);

            int selectedRow = templateTreeTable.getSelectedRow();
            selectedNode = selectedRow >= 0
                    ? (TreeTableNode) templateTreeTable.getPathForRow(selectedRow).getLastPathComponent()
                    : null;
        }

        @Override
        protected void afterSort() {
            final TreePath selectedPath = selectPathFromNodeId(selectedNode,
                    (CodeTemplateRootTreeTableNode) templateTreeTable.getTreeTableModel().getRoot());
            if (selectedPath != null) {
                selectTemplatePath(selectedPath);
            }

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    if (selectedPath != null) {
                        selectTemplatePath(selectedPath);
                    }
                    updateCurrentNode.set(true);
                }
            });
        }
    };

    DefaultTreeTableModel model = new CodeTemplateTreeTableModel();
    model.setColumnIdentifiers(
            Arrays.asList(new String[] { "Name", "Id", "Type", "Description", "Revision", "Last Modified" }));

    CodeTemplateRootTreeTableNode rootNode = new CodeTemplateRootTreeTableNode();
    model.setRoot(rootNode);

    fullModel = new CodeTemplateTreeTableModel();
    fullModel.setColumnIdentifiers(
            Arrays.asList(new String[] { "Name", "Id", "Type", "Description", "Revision", "Last Modified" }));

    CodeTemplateRootTreeTableNode fullRootNode = new CodeTemplateRootTreeTableNode();
    fullModel.setRoot(fullRootNode);

    templateTreeTable.setColumnFactory(new CodeTemplateTableColumnFactory());
    templateTreeTable.setTreeTableModel(model);
    templateTreeTable.setOpenIcon(null);
    templateTreeTable.setClosedIcon(null);
    templateTreeTable.setLeafIcon(null);
    templateTreeTable.setRootVisible(false);
    templateTreeTable.setDoubleBuffered(true);
    templateTreeTable.setDragEnabled(false);
    templateTreeTable.setRowSelectionAllowed(true);
    templateTreeTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    templateTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    templateTreeTable.setFocusable(true);
    templateTreeTable.setOpaque(true);
    templateTreeTable.getTableHeader().setReorderingAllowed(true);
    templateTreeTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
    templateTreeTable.setEditable(true);
    templateTreeTable.setSortable(true);
    templateTreeTable.setAutoCreateColumnsFromModel(false);
    templateTreeTable.setShowGrid(true, true);
    templateTreeTable.restoreColumnPreferences();
    templateTreeTable.setMirthColumnControlEnabled(true);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        templateTreeTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    templateTreeTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelection(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelection(evt);
        }

        private void checkSelection(MouseEvent evt) {
            int row = templateTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY()));

            if (row < 0) {
                templateTreeTable.clearSelection();
            }

            if (evt.isPopupTrigger()) {
                if (row != -1) {
                    if (!templateTreeTable.isRowSelected(row)) {
                        templateTreeTable.setRowSelectionInterval(row, row);
                    }
                }
                codeTemplatePopupMenu.show(evt.getComponent(), evt.getX(), evt.getY());
            }
        }
    });

    templateTreeTable.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                TreePath selectedPath = templateTreeTable.getTreeSelectionModel().getSelectionPath();
                if (selectedPath != null) {
                    MutableTreeTableNode selectedNode = (MutableTreeTableNode) selectedPath
                            .getLastPathComponent();
                    if (selectedNode instanceof CodeTemplateLibraryTreeTableNode && codeTemplateTasks
                            .getContentPane().getComponent(TASK_CODE_TEMPLATE_LIBRARY_DELETE).isVisible()) {
                        doDeleteLibrary();
                    } else if (selectedNode instanceof CodeTemplateTreeTableNode && codeTemplateTasks
                            .getContentPane().getComponent(TASK_CODE_TEMPLATE_DELETE).isVisible()) {
                        doDeleteCodeTemplate();
                    }
                }
            }
        }
    });

    templateTreeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent evt) {
            if (!evt.getValueIsAdjusting() && !templateTreeTable.getSelectionModel().getValueIsAdjusting()) {
                int selectedRow = templateTreeTable.getSelectedRow();

                boolean saveEnabled = isSaveEnabled();
                boolean adjusting = saveAdjusting.getAndSet(true);

                printTreeTable();

                updateCurrentNode();
                currentSelectedRow = selectedRow;

                if (selectedRow < 0) {
                    if (!adjusting) {
                        switchSplitPaneComponent(blankPanel);
                    }
                } else {
                    TreePath path = templateTreeTable.getPathForRow(selectedRow);
                    if (path != null) {
                        TreeTableNode node = (TreeTableNode) path.getLastPathComponent();

                        if (node instanceof CodeTemplateLibraryTreeTableNode) {
                            setLibraryProperties((CodeTemplateLibraryTreeTableNode) node);
                            switchSplitPaneComponent(libraryPanel);
                        } else if (node instanceof CodeTemplateTreeTableNode) {
                            setCodeTemplateProperties((CodeTemplateTreeTableNode) node);
                            switchSplitPaneComponent(templatePanel);
                        }
                    }
                }

                updateTasks();

                setSaveEnabled(saveEnabled);
                if (!adjusting) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            saveAdjusting.set(false);
                        }
                    });
                }
            }
        }
    });

    templateTreeTable.addTreeWillExpandListener(new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException {
            treeExpansionChanged();
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
            treeExpansionChanged();
        }

        private void treeExpansionChanged() {
            updateCurrentNode();
            updateCurrentNode.set(false);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    updateCurrentNode.set(true);
                }
            });
        }
    });

    templateTreeTableScrollPane = new JScrollPane(templateTreeTable);
    templateTreeTableScrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(0x6E6E6E)));

    templateFilterNotificationLabel = new JLabel();

    templateFilterLabel = new JLabel("Filter:");

    templateFilterField = new JTextField();
    templateFilterField.setToolTipText(
            "Filters (by name) the code templates and libraries that show up in the table above.");

    templateFilterField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            filterChanged(evt);
        }

        private void filterChanged(DocumentEvent evt) {
            try {
                updateTemplateFilter(evt.getDocument().getText(0, evt.getLength()));
            } catch (BadLocationException e) {
            }
        }
    });

    templateFilterField.addKeyListener(new KeyAdapter() {
        @Override
        public void keyReleased(KeyEvent evt) {
            updateTemplateFilter(templateFilterField.getText());
        }
    });

    blankPanel = new JPanel();

    libraryPanel = new JPanel();
    libraryPanel.setBackground(splitPane.getBackground());

    libraryLeftPanel = new JPanel();
    libraryLeftPanel.setBackground(libraryPanel.getBackground());

    librarySummaryLabel = new JLabel("Summary:");
    librarySummaryValue = new JLabel();

    libraryDescriptionLabel = new JLabel("Description:");
    libraryDescriptionScrollPane = new MirthRTextScrollPane(null, false, SyntaxConstants.SYNTAX_STYLE_NONE,
            false);

    DocumentListener codeChangeListener = new DocumentListener() {

        @Override
        public void removeUpdate(DocumentEvent evt) {
            codeChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            codeChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            codeChanged();
        }

        private void codeChanged() {
            if (codeChangeWorker != null) {
                codeChangeWorker.cancel(true);
            }

            int selectedRow = templateTreeTable.getSelectedRow();
            if (selectedRow >= 0) {
                TreePath selectedPath = templateTreeTable.getPathForRow(selectedRow);
                if (selectedPath != null) {
                    codeChangeWorker = new CodeChangeWorker(
                            (String) ((TreeTableNode) selectedPath.getLastPathComponent())
                                    .getValueAt(TEMPLATE_ID_COLUMN));
                    codeChangeWorker.execute();
                }
            }
        }
    };
    libraryDescriptionScrollPane.getDocument().addDocumentListener(codeChangeListener);

    libraryRightPanel = new JPanel();
    libraryRightPanel.setBackground(libraryPanel.getBackground());

    libraryChannelsSelectPanel = new JPanel();
    libraryChannelsSelectPanel.setBackground(libraryRightPanel.getBackground());

    libraryChannelsLabel = new JLabel("<html><b>Channels</b></html>");
    libraryChannelsLabel.setForeground(new Color(64, 64, 64));

    libraryChannelsSelectAllLabel = new JLabel("<html><u>Select All</u></html>");
    libraryChannelsSelectAllLabel.setForeground(Color.BLUE);
    libraryChannelsSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    libraryChannelsSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            if (evt.getComponent().isEnabled()) {
                for (int row = 0; row < libraryChannelsTable.getRowCount(); row++) {
                    ChannelInfo channelInfo = (ChannelInfo) libraryChannelsTable.getValueAt(row,
                            LIBRARY_CHANNELS_NAME_COLUMN);
                    channelInfo.setEnabled(true);
                    libraryChannelsTable.setValueAt(channelInfo, row, LIBRARY_CHANNELS_NAME_COLUMN);
                }
                setSaveEnabled(true);
            }
        }
    });

    libraryChannelsDeselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    libraryChannelsDeselectAllLabel.setForeground(Color.BLUE);
    libraryChannelsDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    libraryChannelsDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            if (evt.getComponent().isEnabled()) {
                for (int row = 0; row < libraryChannelsTable.getRowCount(); row++) {
                    ChannelInfo channelInfo = (ChannelInfo) libraryChannelsTable.getValueAt(row,
                            LIBRARY_CHANNELS_NAME_COLUMN);
                    channelInfo.setEnabled(false);
                    libraryChannelsTable.setValueAt(channelInfo, row, LIBRARY_CHANNELS_NAME_COLUMN);
                }
                setSaveEnabled(true);
            }
        }
    });

    libraryChannelsFilterLabel = new JLabel("Filter:");
    libraryChannelsFilterField = new JTextField();
    libraryChannelsFilterField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }

        @Override
        public void changedUpdate(DocumentEvent evt) {
            libraryChannelsTable.getRowSorter().allRowsChanged();
        }
    });

    libraryChannelsTable = new MirthTable();
    libraryChannelsTable.setModel(new RefreshTableModel(new Object[] { "Name", "Id" }, 0));
    libraryChannelsTable.setDragEnabled(false);
    libraryChannelsTable.setRowSelectionAllowed(false);
    libraryChannelsTable.setRowHeight(UIConstants.ROW_HEIGHT);
    libraryChannelsTable.setFocusable(false);
    libraryChannelsTable.setOpaque(true);
    libraryChannelsTable.getTableHeader().setReorderingAllowed(false);
    libraryChannelsTable.setEditable(true);

    OffsetRowSorter libraryChannelsRowSorter = new OffsetRowSorter(libraryChannelsTable.getModel(), 1);
    libraryChannelsRowSorter.setRowFilter(new RowFilter<TableModel, Integer>() {
        @Override
        public boolean include(Entry<? extends TableModel, ? extends Integer> entry) {
            String name = entry.getStringValue(LIBRARY_CHANNELS_NAME_COLUMN);
            return name.equals(NEW_CHANNELS) || StringUtils.containsIgnoreCase(name,
                    StringUtils.trim(libraryChannelsFilterField.getText()));
        }
    });
    libraryChannelsTable.setRowSorter(libraryChannelsRowSorter);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        libraryChannelsTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_NAME_COLUMN)
            .setCellRenderer(new ChannelsTableCellRenderer());
    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_NAME_COLUMN)
            .setCellEditor(new ChannelsTableCellEditor());

    // Hide ID column
    libraryChannelsTable.getColumnExt(LIBRARY_CHANNELS_ID_COLUMN).setVisible(false);

    libraryChannelsScrollPane = new JScrollPane(libraryChannelsTable);

    templatePanel = new JPanel();
    templatePanel.setBackground(splitPane.getBackground());

    templateLeftPanel = new JPanel();
    templateLeftPanel.setBackground(templatePanel.getBackground());

    templateLibraryLabel = new JLabel("Library:");
    templateLibraryComboBox = new JComboBox<String>();
    templateLibraryComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            libraryComboBoxActionPerformed();
        }
    });

    templateTypeLabel = new JLabel("Type:");
    templateTypeComboBox = new JComboBox<CodeTemplateType>(CodeTemplateType.values());
    templateTypeComboBox.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            setSaveEnabled(true);
        }
    });

    templateCodeLabel = new JLabel("Code:");
    templateCodeTextArea = new MirthRTextScrollPane(ContextType.GLOBAL_DEPLOY);
    templateCodeTextArea.getDocument().addDocumentListener(codeChangeListener);

    templateAutoGenerateDocumentationButton = new JButton("Update JSDoc");
    templateAutoGenerateDocumentationButton.setToolTipText(
            "<html>Generates/updates a JSDoc at the beginning of your<br/>code, with parameter/return annotations as needed.</html>");
    templateAutoGenerateDocumentationButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            String currentText = templateCodeTextArea.getText();
            String newText = CodeTemplateUtil.updateCode(templateCodeTextArea.getText());
            templateCodeTextArea.setText(newText, false);
            if (!currentText.equals(newText)) {
                setSaveEnabled(true);
            }
        }
    });

    templateRightPanel = new JPanel();
    templateRightPanel.setBackground(templatePanel.getBackground());

    templateContextSelectPanel = new JPanel();
    templateContextSelectPanel.setBackground(templateRightPanel.getBackground());

    templateContextLabel = new JLabel("<html><b>Context</b></html>");
    templateContextLabel.setForeground(new Color(64, 64, 64));

    templateContextSelectAllLabel = new JLabel("<html><u>Select All</u></html>");
    templateContextSelectAllLabel.setForeground(Color.BLUE);
    templateContextSelectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    templateContextSelectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            TreeTableNode root = (TreeTableNode) templateContextTreeTable.getTreeTableModel().getRoot();
            for (Enumeration<? extends TreeTableNode> groups = root.children(); groups.hasMoreElements();) {
                TreeTableNode group = groups.nextElement();
                ((MutablePair<Integer, String>) group.getUserObject()).setLeft(MirthTriStateCheckBox.CHECKED);
                for (Enumeration<? extends TreeTableNode> children = group.children(); children
                        .hasMoreElements();) {
                    ((MutablePair<Integer, String>) children.nextElement().getUserObject())
                            .setLeft(MirthTriStateCheckBox.CHECKED);
                }
            }
            templateContextTreeTable.updateUI();
            setSaveEnabled(true);
        }
    });

    templateContextDeselectAllLabel = new JLabel("<html><u>Deselect All</u></html>");
    templateContextDeselectAllLabel.setForeground(Color.BLUE);
    templateContextDeselectAllLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
    templateContextDeselectAllLabel.addMouseListener(new MouseAdapter() {
        public void mouseReleased(MouseEvent evt) {
            TreeTableNode root = (TreeTableNode) templateContextTreeTable.getTreeTableModel().getRoot();
            for (Enumeration<? extends TreeTableNode> groups = root.children(); groups.hasMoreElements();) {
                TreeTableNode group = groups.nextElement();
                ((MutablePair<Integer, String>) group.getUserObject()).setLeft(MirthTriStateCheckBox.UNCHECKED);
                for (Enumeration<? extends TreeTableNode> children = group.children(); children
                        .hasMoreElements();) {
                    ((MutablePair<Integer, String>) children.nextElement().getUserObject())
                            .setLeft(MirthTriStateCheckBox.UNCHECKED);
                }
            }
            templateContextTreeTable.updateUI();
            setSaveEnabled(true);
        }
    });

    final TableCellEditor contextCellEditor = new ContextTreeTableCellEditor(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent evt) {
            setSaveEnabled(true);
        }
    });

    templateContextTreeTable = new MirthTreeTable() {
        @Override
        public TableCellEditor getCellEditor(int row, int column) {
            if (isHierarchical(column)) {
                return contextCellEditor;
            } else {
                return super.getCellEditor(row, column);
            }
        }
    };

    DefaultMutableTreeTableNode rootContextNode = new DefaultMutableTreeTableNode();
    DefaultMutableTreeTableNode globalScriptsNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Global Scripts"));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_DEPLOY)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_UNDEPLOY)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_PREPROCESSOR)));
    globalScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.GLOBAL_POSTPROCESSOR)));
    rootContextNode.add(globalScriptsNode);
    DefaultMutableTreeTableNode channelScriptsNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Channel Scripts"));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_DEPLOY)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_UNDEPLOY)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_PREPROCESSOR)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_POSTPROCESSOR)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_ATTACHMENT)));
    channelScriptsNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.CHANNEL_BATCH)));
    rootContextNode.add(channelScriptsNode);
    DefaultMutableTreeTableNode sourceConnectorNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Source Connector"));
    sourceConnectorNode.add(new DefaultMutableTreeTableNode(
            new MutablePair<Integer, ContextType>(MirthTriStateCheckBox.CHECKED, ContextType.SOURCE_RECEIVER)));
    sourceConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.SOURCE_FILTER_TRANSFORMER)));
    rootContextNode.add(sourceConnectorNode);
    DefaultMutableTreeTableNode destinationConnectorNode = new DefaultMutableTreeTableNode(
            new MutablePair<Integer, String>(MirthTriStateCheckBox.CHECKED, "Destination Connector"));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_FILTER_TRANSFORMER)));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_DISPATCHER)));
    destinationConnectorNode.add(new DefaultMutableTreeTableNode(new MutablePair<Integer, ContextType>(
            MirthTriStateCheckBox.CHECKED, ContextType.DESTINATION_RESPONSE_TRANSFORMER)));
    rootContextNode.add(destinationConnectorNode);

    DefaultTreeTableModel contextModel = new SortableTreeTableModel(rootContextNode);
    contextModel.setColumnIdentifiers(Arrays.asList(new String[] { "Context" }));
    templateContextTreeTable.setTreeTableModel(contextModel);

    templateContextTreeTable.setRootVisible(false);
    templateContextTreeTable.setDragEnabled(false);
    templateContextTreeTable.setRowSelectionAllowed(false);
    templateContextTreeTable.setRowHeight(UIConstants.ROW_HEIGHT);
    templateContextTreeTable.setFocusable(false);
    templateContextTreeTable.setOpaque(true);
    templateContextTreeTable.getTableHeader().setReorderingAllowed(false);
    templateContextTreeTable.setEditable(true);
    templateContextTreeTable.setSortable(false);
    templateContextTreeTable.setShowGrid(true, true);

    if (Preferences.userNodeForPackage(Mirth.class).getBoolean("highlightRows", true)) {
        templateContextTreeTable.setHighlighters(HighlighterFactory
                .createAlternateStriping(UIConstants.HIGHLIGHTER_COLOR, UIConstants.BACKGROUND_COLOR));
    }

    templateContextTreeTable.setTreeCellRenderer(new ContextTreeTableCellRenderer());
    templateContextTreeTable.setOpenIcon(null);
    templateContextTreeTable.setClosedIcon(null);
    templateContextTreeTable.setLeafIcon(null);

    templateContextTreeTable.addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent evt) {
            checkSelection(evt);
        }

        @Override
        public void mouseReleased(MouseEvent evt) {
            checkSelection(evt);
        }

        private void checkSelection(MouseEvent evt) {
            if (templateContextTreeTable.rowAtPoint(new Point(evt.getX(), evt.getY())) < 0) {
                templateContextTreeTable.clearSelection();
            }
        }
    });

    templateContextTreeTable.getTreeTableModel().addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeNodesChanged(TreeModelEvent evt) {
            if (ArrayUtils.isNotEmpty(evt.getChildren())) {
                TreeTableNode node = (TreeTableNode) evt.getChildren()[0];

                if (evt.getTreePath().getPathCount() == 2) {
                    boolean allChildren = true;
                    boolean noChildren = true;
                    for (Enumeration<? extends TreeTableNode> children = node.getParent().children(); children
                            .hasMoreElements();) {
                        TreeTableNode child = children.nextElement();
                        if (((Pair<Integer, ContextType>) child.getUserObject())
                                .getLeft() == MirthTriStateCheckBox.UNCHECKED) {
                            allChildren = false;
                        } else {
                            noChildren = false;
                        }
                    }

                    int value;
                    if (allChildren) {
                        value = MirthTriStateCheckBox.CHECKED;
                    } else if (noChildren) {
                        value = MirthTriStateCheckBox.UNCHECKED;
                    } else {
                        value = MirthTriStateCheckBox.PARTIAL;
                    }

                    ((MutablePair<Integer, String>) node.getParent().getUserObject()).setLeft(value);
                } else if (evt.getTreePath().getPathCount() == 1) {
                    int value = ((Pair<Integer, String>) node.getUserObject()).getLeft();

                    for (Enumeration<? extends TreeTableNode> children = node.children(); children
                            .hasMoreElements();) {
                        ((MutablePair<Integer, ContextType>) children.nextElement().getUserObject())
                                .setLeft(value);
                    }
                }
            }
        }

        @Override
        public void treeNodesInserted(TreeModelEvent evt) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent evt) {
        }

        @Override
        public void treeStructureChanged(TreeModelEvent evt) {
        }
    });

    templateContextTreeTableScrollPane = new JScrollPane(templateContextTreeTable);
}

From source file:org.apache.cayenne.modeler.ProjectTreeView.java

private void initController() {
    treeSelectionListener = new TreeSelectionListener() {

        public void valueChanged(TreeSelectionEvent e) {
            TreePath[] paths = getSelectionPaths();

            if (paths != null) {
                if (paths.length > 1) {
                    ConfigurationNode projectParentPath = null;
                    ConfigurationNode[] projectPaths = new ConfigurationNode[paths.length];
                    boolean commonParentPath = true;

                    for (int i = 0; i < paths.length; i++) {
                        projectPaths[i] = createProjectPath(paths[i]);

                        TreePath parentPath = paths[i].getParentPath();
                        if (i > 0 && parentPath != null && !parentPath.equals(paths[i - 1].getParentPath())) {
                            commonParentPath = false;
                        }//  w w w. jav a 2s  .c o m
                    }

                    if (commonParentPath) {
                        TreePath parentPath = paths[0].getParentPath();
                        projectParentPath = createProjectPath(parentPath);
                    }

                    mediator.fireMultipleObjectsDisplayEvent(
                            new MultipleObjectsDisplayEvent(this, projectPaths, projectParentPath));
                } else if (paths.length == 1) {
                    processSelection(paths[0]);
                }
            }
        }

        /**
         * Converts TreePath to Object
         */
        private ConfigurationNode createProjectPath(TreePath treePath) {
            Object[] path = treePath.getPath();
            ConfigurationNode projectPath = (ConfigurationNode) ((DefaultMutableTreeNode) path[path.length - 1])
                    .getUserObject();

            return projectPath;
        }
    };

    treeWillExpandListener = new TreeWillExpandListener() {
        @Override
        public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException {
            TreePath path = e.getPath();
            if (!isPathSelected(path) && !isSelectionEmpty()) {
                setSelectionPath(path);
            }
        }

        @Override
        public void treeWillCollapse(TreeExpansionEvent e) throws ExpandVetoException {
            TreePath path = e.getPath();
            if (!isPathSelected(path) && !isSelectionEmpty()) {
                setSelectionPath(path);
            }
        }
    };

    addTreeSelectionListener(treeSelectionListener);
    addTreeWillExpandListener(treeWillExpandListener);

    addMouseListener(new PopupHandler());

    mediator.addDomainListener(this);
    mediator.addDomainDisplayListener(this);
    mediator.addDataNodeListener(this);
    mediator.addDataNodeDisplayListener(this);
    mediator.addDataMapListener(this);
    mediator.addDataMapDisplayListener(this);
    mediator.addObjEntityListener(this);
    mediator.addObjEntityDisplayListener(this);
    mediator.addDbEntityListener(this);
    mediator.addDbEntityDisplayListener(this);
    mediator.addEmbeddableDisplayListener(this);
    mediator.addEmbeddableListener(this);
    mediator.addProcedureListener(this);
    mediator.addProcedureDisplayListener(this);
    mediator.addQueryListener(this);
    mediator.addQueryDisplayListener(this);
    mediator.addMultipleObjectsDisplayListener(this);

    mediator.getApplication().getActionManager().setupCutCopyPaste(this, CutAction.class, CopyAction.class);
}