Example usage for javax.swing.event TreeModelListener TreeModelListener

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

Introduction

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

Prototype

TreeModelListener

Source Link

Usage

From source file:Main.java

public static void main(String args[]) {
    JFrame f = new JFrame("JTree Demo");
    f.setSize(260, 240);//from   w ww. j  a va2s .co m
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode aNode = new DefaultMutableTreeNode("A");
    root.add(aNode);

    DefaultMutableTreeNode bNode = new DefaultMutableTreeNode("B");
    aNode.add(bNode);

    DefaultMutableTreeNode cNode = new DefaultMutableTreeNode("C");
    aNode.add(cNode);

    cNode.add(new DefaultMutableTreeNode("D"));
    cNode.add(new DefaultMutableTreeNode("E"));

    DefaultMutableTreeNode fNode = new DefaultMutableTreeNode("F");
    root.add(fNode);

    DefaultMutableTreeNode gNode = new DefaultMutableTreeNode("G");
    fNode.add(gNode);
    fNode.add(new DefaultMutableTreeNode("H"));
    gNode.add(new DefaultMutableTreeNode("I"));

    JTree jtree = new JTree(root);
    jtree.setEditable(true);

    TreeSelectionModel tsm = jtree.getSelectionModel();
    tsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    jtree.addTreeExpansionListener(new TreeExpansionListener() {
        public void treeExpanded(TreeExpansionEvent tee) {
            TreePath tp = tee.getPath();
            System.out.println("Expansion: " + tp.getLastPathComponent());
        }

        public void treeCollapsed(TreeExpansionEvent tee) {
            TreePath tp = tee.getPath();
            System.out.println("Collapse: " + tp.getLastPathComponent());
        }
    });

    jtree.addTreeSelectionListener(new TreeSelectionListener() {
        public void valueChanged(TreeSelectionEvent tse) {
            TreePath tp = tse.getPath();
            System.out.println("Selection event: " + tp.getLastPathComponent());
        }
    });

    jtree.getModel().addTreeModelListener(new TreeModelListener() {
        public void treeNodesChanged(TreeModelEvent tme) {
            TreePath tp = tme.getTreePath();
            Object[] children = tme.getChildren();
            DefaultMutableTreeNode changedNode;
            if (children != null)
                changedNode = (DefaultMutableTreeNode) children[0];
            else
                changedNode = (DefaultMutableTreeNode) tp.getLastPathComponent();

            System.out.println("Model change path: " + tp + "New data: " + changedNode.getUserObject());

        }

        public void treeNodesInserted(TreeModelEvent tme) {
        }

        public void treeNodesRemoved(TreeModelEvent tme) {
        }

        public void treeStructureChanged(TreeModelEvent tme) {
        }
    });

    f.add(new JScrollPane(jtree));
    f.setVisible(true);
}

From source file:gov.nij.er.ui.RawDataFilteredTreeModel.java

RawDataFilteredTreeModel(RecordTreeModel rawDataTreeModel) {
    this.rawDataTreeModel = rawDataTreeModel;
    rawDataTreeModel.addTreeModelListener(new TreeModelListener() {

        public void treeNodesChanged(TreeModelEvent e) {
            if (!isFiltered) {
                for (TreeModelListener l : listeners) {
                    l.treeNodesChanged(e);
                }// w ww  .j  av  a2 s  .co m
            }
        }

        public void treeNodesInserted(TreeModelEvent e) {
            if (!isFiltered) {
                for (TreeModelListener l : listeners) {
                    l.treeNodesInserted(e);
                }
            }
        }

        public void treeNodesRemoved(TreeModelEvent e) {
            if (!isFiltered) {
                for (TreeModelListener l : listeners) {
                    l.treeNodesRemoved(e);
                }
            }
        }

        public void treeStructureChanged(TreeModelEvent e) {
            if (!isFiltered) {
                for (TreeModelListener l : listeners) {
                    l.treeStructureChanged(e);
                }
            }
        }
    });
    root = new DefaultMutableTreeNode(ROOT_NODE_LABEL);

}

From source file:com.diversityarrays.kdxplore.trials.AddScoringSetDialog.java

public AddScoringSetDialog(Window owner, KdxploreDatabase kdxdb, Trial trial,
        Map<Trait, List<TraitInstance>> instancesByTrait, SampleGroup curatedSampleGroup) {
    super(owner, Msg.TITLE_ADD_SCORING_SET(), ModalityType.APPLICATION_MODAL);

    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    this.kdxploreDatabase = kdxdb;
    this.trial = trial;
    this.curatedSampleGroupId = curatedSampleGroup == null ? 0 : curatedSampleGroup.getSampleGroupId();

    Map<Trait, List<TraitInstance>> noCalcs = instancesByTrait.entrySet().stream()
            .filter(e -> TraitDataType.CALC != e.getKey().getTraitDataType())
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

    Map<Trait, List<TraitInstance>> noCalcsSorted = new TreeMap<>(TRAIT_COMPARATOR);
    noCalcsSorted.putAll(noCalcs);/*from   w w  w . ja v  a2  s  .c  om*/

    BiFunction<Trait, TraitInstance, String> parentNameProvider = new BiFunction<Trait, TraitInstance, String>() {
        @Override
        public String apply(Trait t, TraitInstance ti) {
            if (ti == null) {
                List<TraitInstance> list = noCalcsSorted.get(t);
                if (list == null || list.size() != 1) {
                    OptionalInt opt = traitInstanceChoiceTreeModel.getChildChosenCountIfNotAllChosen(t);
                    StringBuilder sb = new StringBuilder(t.getTraitName());

                    if (opt.isPresent()) {
                        // only some of the children are chosen
                        int childChosenCount = opt.getAsInt();
                        if (childChosenCount > 0) {
                            sb.append(" (").append(childChosenCount).append(" of ").append(list.size())
                                    .append(")");
                        }
                    } else {
                        // all of the children are chosen
                        if (list != null) {
                            sb.append(" (").append(list.size()).append(")");
                        }
                    }
                    return sb.toString();
                }
            }
            return t.getTraitName();
        }
    };

    Optional<List<TraitInstance>> opt = noCalcsSorted.values().stream().filter(list -> list.size() > 1)
            .findFirst();
    String heading1 = opt.isPresent() ? "Trait/Instance" : "Trait";

    traitInstanceChoiceTreeModel = new ChoiceTreeTableModel<>(heading1, "Use?", //$NON-NLS-1$
            noCalcsSorted, parentNameProvider, childNameProvider);

    //        traitInstanceChoiceTreeModel = new TTChoiceTreeTableModel(instancesByTrait);

    traitInstanceChoiceTreeModel.addChoiceChangedListener(new ChoiceChangedListener() {
        @Override
        public void choiceChanged(Object source, ChoiceNode[] changedNodes) {
            updateCreateAction("choiceChanged");
            treeTable.repaint();
        }
    });

    traitInstanceChoiceTreeModel.addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeStructureChanged(TreeModelEvent e) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent e) {
        }

        @Override
        public void treeNodesInserted(TreeModelEvent e) {
        }

        @Override
        public void treeNodesChanged(TreeModelEvent e) {
            updateCreateAction("treeNodesChanged");
        }
    });

    warningMsg.setText(PLEASE_PROVIDE_A_DESCRIPTION);
    warningMsg.setForeground(Color.RED);

    Container cp = getContentPane();

    Box sampleButtons = null;
    if (curatedSampleGroup != null && curatedSampleGroup.getAnyScoredSamples()) {
        sampleButtons = createWantSampleButtons(curatedSampleGroup);
    }

    Box top = Box.createVerticalBox();
    if (sampleButtons == null) {
        top.add(new JLabel(Msg.MSG_THERE_ARE_NO_CURATED_SAMPLES()));
    } else {
        top.add(sampleButtons);
    }
    top.add(descriptionField);

    cp.add(top, BorderLayout.NORTH);

    descriptionField.getDocument().addDocumentListener(new DocumentListener() {
        @Override
        public void removeUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            updateCreateAction("documentListener");
        }
    });

    updateCreateAction("init");
    //        KDClientUtils.initAction(ImageId.`CHECK_ALL, useAllAction, "Click to Use All");

    treeTable = new JXTreeTable(traitInstanceChoiceTreeModel);
    treeTable.setAutoResizeMode(JXTreeTable.AUTO_RESIZE_ALL_COLUMNS);

    TableCellRenderer renderer = treeTable.getDefaultRenderer(Integer.class);
    if (renderer instanceof JLabel) {
        ((JLabel) renderer).setHorizontalAlignment(JLabel.CENTER);
    }

    Box buttons = Box.createHorizontalBox();

    buttons.add(new JButton(useAllAction));
    buttons.add(new JButton(useNoneAction));

    buttons.add(Box.createHorizontalGlue());
    buttons.add(warningMsg);

    buttons.add(new JButton(cancelAction));
    buttons.add(Box.createHorizontalStrut(10));
    buttons.add(new JButton(createAction));

    cp.add(new JScrollPane(treeTable), BorderLayout.CENTER);
    cp.add(buttons, BorderLayout.SOUTH);

    pack();
}

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  www . ja v a  2s . co  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.languagetool.gui.ConfigurationDialog.java

@NotNull
private DefaultTreeModel getTreeModel(DefaultMutableTreeNode rootNode) {
    DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    treeModel.addTreeModelListener(new TreeModelListener() {
        @Override//from www .  j a v  a  2  s . c  om
        public void treeNodesChanged(TreeModelEvent e) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getTreePath().getLastPathComponent();
            int index = e.getChildIndices()[0];
            node = (DefaultMutableTreeNode) node.getChildAt(index);
            if (node instanceof RuleNode) {
                RuleNode o = (RuleNode) node;
                if (o.getRule().isDefaultOff() || o.getRule().getCategory().isDefaultOff()) {
                    if (o.isEnabled()) {
                        config.getEnabledRuleIds().add(o.getRule().getId());
                        config.getDisabledRuleIds().remove(o.getRule().getId());
                    } else {
                        config.getEnabledRuleIds().remove(o.getRule().getId());
                        config.getDisabledRuleIds().add(o.getRule().getId());
                    }
                } else {
                    if (o.isEnabled()) {
                        config.getDisabledRuleIds().remove(o.getRule().getId());
                    } else {
                        config.getDisabledRuleIds().add(o.getRule().getId());
                    }
                }
            }
            if (node instanceof CategoryNode) {
                CategoryNode o = (CategoryNode) node;
                if (o.getCategory().isDefaultOff()) {
                    if (o.isEnabled()) {
                        config.getDisabledCategoryNames().remove(o.getCategory().getName());
                        config.getEnabledCategoryNames().add(o.getCategory().getName());
                    } else {
                        config.getDisabledCategoryNames().add(o.getCategory().getName());
                        config.getEnabledCategoryNames().remove(o.getCategory().getName());
                    }
                } else {
                    if (o.isEnabled()) {
                        config.getDisabledCategoryNames().remove(o.getCategory().getName());
                    } else {
                        config.getDisabledCategoryNames().add(o.getCategory().getName());
                    }
                }
            }
        }

        @Override
        public void treeNodesInserted(TreeModelEvent e) {
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent e) {
        }

        @Override
        public void treeStructureChanged(TreeModelEvent e) {
        }
    });
    return treeModel;
}

From source file:plugin.notes.gui.NotesView.java

private void initTree() {
    dataDir.listFiles();//from w ww  .j a  v a  2  s . c  o  m
    root = new NotesTreeNode(dataDir.getName(), dataDir, notesTree);

    TreeModel model = new DefaultTreeModel(root);
    notesTree.setModel(model);
    notesTree.addTreeSelectionListener(new TreeSelectionListener() {
        @Override
        public void valueChanged(TreeSelectionEvent evt) {
            notesTreeActionPerformed();
        }
    });
    notesTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    notesTree.setEditable(true);
    model.addTreeModelListener(new TreeModelListener() {
        @Override
        public void treeNodesChanged(TreeModelEvent e) {
            notesTreeNodesChanged();
        }

        @Override
        public void treeNodesInserted(TreeModelEvent e) {
            // TODO:  Method does nothing?
        }

        @Override
        public void treeNodesRemoved(TreeModelEvent e) {
            // TODO:  Method does nothing?
        }

        @Override
        public void treeStructureChanged(TreeModelEvent e) {
            // TODO:  Method does nothing?
        }
    });
}