示例#1
0
文件: TreeUtil.java 项目: jexp/idea2
  public static void dropSelectionButUnderPoint(JTree tree, Point treePoint) {
    final TreePath toRetain = tree.getPathForLocation(treePoint.x, treePoint.y);
    if (toRetain == null) return;

    TreePath[] selection = tree.getSelectionModel().getSelectionPaths();
    selection = selection == null ? new TreePath[0] : selection;
    for (TreePath each : selection) {
      if (toRetain.equals(each)) continue;
      tree.getSelectionModel().removeSelectionPath(each);
    }
  }
示例#2
0
  @Override
  public void valueChanged(TreeSelectionEvent e) {
    if (e.getSource() == colors && !locked) {
      TreeSelectionModel tsm = colors.getSelectionModel();
      TreePath tp[] = tsm.getSelectionPaths();
      if (tp == null) return;
      Vector<ClassedItem> tmp = new Vector<ClassedItem>();
      for (TreePath element : tp) {
        try {
          Object[] path = element.getPath();
          ClassedItem ci = new ClassedItem(path[1].toString(), path[2].toString());
          tmp.add(ci);
        } catch (Exception exp) {
          // User did not select a leafnode
        }
      }

      if (sceneElement instanceof NenyaImageSceneElement) {
        ((NenyaImageSceneElement) sceneElement).setColorList(tmp.toArray(new ClassedItem[0]));
      }
      if (sceneElement instanceof NenyaTileSceneElement) {
        ((NenyaTileSceneElement) sceneElement).setColorList(tmp.toArray(new ClassedItem[0]));
      }
      if (sceneElement instanceof NenyaComponentSceneElement) {
        ((NenyaComponentSceneElement) sceneElement)
            .getComponents()[itemList.getSelectedIndex()].setColorList(
                tmp.toArray(new ClassedItem[0]));
      }

      submitElement(sceneElement, null);
    } else {
      super.valueChanged(e);
    }
  }
示例#3
0
 public InputFrame(SipModel sipModel) {
   super(Which.INPUT, sipModel, "Input");
   sipModel.addParseListener(
       new SipModel.ParseListener() {
         @Override
         public void updatedRecord(MetadataRecord metadataRecord) {
           exec(new RecordSetter(metadataRecord));
         }
       });
   recordTree =
       new JTree(EMPTY_MODEL) {
         @Override
         public String getToolTipText(MouseEvent evt) {
           TreePath treePath = recordTree.getPathForLocation(evt.getX(), evt.getY());
           return treePath != null
               ? ((GroovyTreeNode) treePath.getLastPathComponent()).toolTip
               : "";
         }
       };
   recordTree.setToolTipText("Input Record");
   recordTree.setCellRenderer(new Renderer());
   recordTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
   recordTree.setTransferHandler(new TreeTransferHandler());
   filterField.addActionListener(rewind);
 }
示例#4
0
    public ReplicatedTreeView(ReplicatedTree tree, Object title) throws Exception {
      this.tree = tree;
      tree.addReplicatedTreeListener(this);

      addNotify();
      setTitle("ReplicatedTreeDemo: mbr=" + title);

      tree_model = new DefaultTreeModel(root);
      jtree = new JTree(tree_model);
      jtree.setDoubleBuffered(true);
      jtree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

      JScrollPane scroll_pane = new JScrollPane(jtree);

      populateTree();

      getContentPane().add(scroll_pane, BorderLayout.CENTER);
      addWindowListener(this);

      table_model.setColumnIdentifiers(new String[] {"Name", "Value"});
      table_model.addTableModelListener(this);

      setTableColumnWidths();

      tablePanel = new JPanel();
      tablePanel.setLayout(new BorderLayout());
      tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
      tablePanel.add(table, BorderLayout.CENTER);

      getContentPane().add(tablePanel, BorderLayout.SOUTH);

      jtree.addTreeSelectionListener(this); // REVISIT

      MouseListener ml =
          new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
              int selRow = jtree.getRowForLocation(e.getX(), e.getY());
              TreePath selPath = jtree.getPathForLocation(e.getX(), e.getY());
              if (selRow != -1) {
                selected_node = makeFQN(selPath.getPath());
                jtree.setSelectionPath(selPath);

                if (e.getModifiers() == java.awt.event.InputEvent.BUTTON3_MASK) {
                  operationsPopup.show(e.getComponent(), e.getX(), e.getY());
                }
              }
            }
          };

      jtree.addMouseListener(ml);

      createMenus();
      setLocation(50, 50);
      setSize(
          getInsets().left + getInsets().right + 485, getInsets().top + getInsets().bottom + 367);

      init();
      setVisible(true);
    }
示例#5
0
  @Override
  public void adoptElement(SceneElement elem) {
    if (!(elem instanceof NenyaImageSceneElement
        || elem instanceof NenyaTileSceneElement
        || elem instanceof NenyaComponentSceneElement)) {
      enableEditor(false);
      return;
    }

    DefaultComboBoxModel dcm = (DefaultComboBoxModel) itemList.getModel();

    // Important: Work on a copy, not on the original. Otherwise we mess up the undomanager
    sceneElement = elem.copy();

    if ((sceneElement instanceof NenyaImageSceneElement) && !locked) {
      dcm.removeAllElements();
      String[] tmp = ((NenyaImageSceneElement) sceneElement).getPath();
      dcm.addElement(tmp[tmp.length - 1]);
    }
    if ((sceneElement instanceof NenyaTileSceneElement) && !locked) {
      dcm.removeAllElements();
      dcm.addElement(((NenyaTileSceneElement) sceneElement).getTileName());
    }
    if ((sceneElement instanceof NenyaComponentSceneElement) && !locked) {
      dcm.removeAllElements();
      NenyaComponentItem[] ni = ((NenyaComponentSceneElement) sceneElement).getComponents();
      for (NenyaComponentItem element : ni) {
        dcm.addElement(element);
      }
    }

    try {
      ClassedItem[] cols = null;
      if (elem instanceof NenyaTileSceneElement)
        cols = ((NenyaTileSceneElement) elem).getColorList();
      if (elem instanceof NenyaImageSceneElement)
        cols = ((NenyaImageSceneElement) elem).getColorList();
      if (elem instanceof NenyaComponentSceneElement) {
        NenyaComponentItem nci = (NenyaComponentItem) dcm.getSelectedItem();
        cols = nci.getColorList();
      }
      Vector<TreePath> collect = new Vector<TreePath>();
      TreeNode root = (TreeNode) colors.getModel().getRoot();
      for (ClassedItem col : cols) {
        String[] tmp = {root.toString(), col.getClassName(), col.getItemName()};
        collect.add(TreeUtil.findPath(root, tmp));
      }
      TreePath[] path = collect.toArray(new TreePath[0]);
      colors.getSelectionModel().setSelectionPaths(path);
    } catch (Exception e) {
      // Either the tree is filtered away or the selected item is not colorized.
    }

    enableEditor(true);
    itemList.setEnabled(elem instanceof NenyaComponentSceneElement);
  }
  private static void printImpl(
      JTree tree,
      Object root,
      Collection<String> strings,
      int level,
      boolean withSelection,
      @Nullable Condition<String> nodePrintCondition) {
    DefaultMutableTreeNode defaultMutableTreeNode = (DefaultMutableTreeNode) root;

    final Object userObject = defaultMutableTreeNode.getUserObject();
    String nodeText;
    if (userObject != null) {
      nodeText = toString(userObject, null);
    } else {
      nodeText = "null";
    }

    if (nodePrintCondition != null && !nodePrintCondition.value(nodeText)) return;

    final StringBuilder buff = new StringBuilder();
    StringUtil.repeatSymbol(buff, ' ', level);

    final boolean expanded = tree.isExpanded(new TreePath(defaultMutableTreeNode.getPath()));
    if (!defaultMutableTreeNode.isLeaf()) {
      buff.append(expanded ? "-" : "+");
    }

    final boolean selected =
        tree.getSelectionModel().isPathSelected(new TreePath(defaultMutableTreeNode.getPath()));
    if (withSelection && selected) {
      buff.append("[");
    }

    buff.append(nodeText);

    if (withSelection && selected) {
      buff.append("]");
    }

    strings.add(buff.toString());

    int childCount = tree.getModel().getChildCount(root);
    if (expanded) {
      for (int i = 0; i < childCount; i++) {
        printImpl(
            tree,
            tree.getModel().getChild(root, i),
            strings,
            level + 1,
            withSelection,
            nodePrintCondition);
      }
    }
  }
 private void restoreUsageExpandState(final Collection<UsageState> states) {
   // always expand the last level group
   final DefaultMutableTreeNode root = (DefaultMutableTreeNode) myTree.getModel().getRoot();
   for (int i = root.getChildCount() - 1; i >= 0; i--) {
     final DefaultMutableTreeNode child = (DefaultMutableTreeNode) root.getChildAt(i);
     if (child instanceof GroupNode) {
       final TreePath treePath = new TreePath(child.getPath());
       myTree.expandPath(treePath);
     }
   }
   myTree.getSelectionModel().clearSelection();
   for (final UsageState usageState : states) {
     usageState.restore();
   }
 }
    public static Image createImage(final JTree tree) {
      final TreeSelectionModel model = tree.getSelectionModel();
      final TreePath[] paths = model.getSelectionPaths();

      int count = 0;
      final List<ChangesBrowserNode> nodes = new ArrayList<ChangesBrowserNode>();
      for (final TreePath path : paths) {
        final ChangesBrowserNode node = (ChangesBrowserNode) path.getLastPathComponent();
        if (!node.isLeaf()) {
          nodes.add(node);
          count += node.getCount();
        }
      }

      for (TreePath path : paths) {
        final ChangesBrowserNode element = (ChangesBrowserNode) path.getLastPathComponent();
        boolean child = false;
        for (final ChangesBrowserNode node : nodes) {
          if (node.isNodeChild(element)) {
            child = true;
            break;
          }
        }

        if (!child) {
          if (element.isLeaf()) count++;
        } else if (!element.isLeaf()) {
          count -= element.getCount();
        }
      }

      final JLabel label = new JLabel(VcsBundle.message("changes.view.dnd.label", count));
      label.setOpaque(true);
      label.setForeground(tree.getForeground());
      label.setBackground(tree.getBackground());
      label.setFont(tree.getFont());
      label.setSize(label.getPreferredSize());
      final BufferedImage image =
          new BufferedImage(label.getWidth(), label.getHeight(), BufferedImage.TYPE_INT_ARGB);

      Graphics2D g2 = (Graphics2D) image.getGraphics();
      g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
      label.paint(g2);
      g2.dispose();

      return image;
    }
  /**
   * Initialize the common user interface components.
   *
   * <p>
   */
  protected JButton[] initUI(
      String title, JComponent extraComps, String confirm, String[][] extra, String cancel) {
    JButton[] extraBtns = null;

    /* create dialog body components */
    {
      JPanel body = new JPanel();
      body.setName("MainDialogPanel");

      body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS));

      body.add(UIFactory.createPanelLabel("Existing Layouts:"));

      body.add(Box.createRigidArea(new Dimension(0, 4)));

      {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode(new TreeData(), true);
        DefaultTreeModel model = new DefaultTreeModel(root, true);

        JTree tree = new JFancyTree(model);
        pTree = tree;
        tree.setName("DarkTree");

        tree.setCellRenderer(new JLayoutTreeCellRenderer());
        tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

        {
          JScrollPane scroll =
              UIFactory.createScrollPane(
                  pTree,
                  ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED,
                  ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                  new Dimension(230, 120),
                  new Dimension(230, 150),
                  null);

          body.add(scroll);
        }
      }

      if (extraComps != null) body.add(extraComps);

      extraBtns = super.initUI(title, body, confirm, null, extra, cancel);
    }

    return extraBtns;
  }
 @NotNull
 private Collection<DefaultMutableTreeNode> getSelectedNodes() {
   if (!isValid()) {
     return Collections.emptyList();
   }
   JTree tree = myStructureViewComponent.getTree();
   if (tree == null) return Collections.emptyList();
   TreePath[] selected = tree.getSelectionModel().getSelectionPaths();
   if (selected == null || selected.length == 0) return Collections.emptyList();
   return ContainerUtil.map(
       selected,
       new Function<TreePath, DefaultMutableTreeNode>() {
         @Override
         public DefaultMutableTreeNode fun(TreePath treePath) {
           return (DefaultMutableTreeNode) treePath.getLastPathComponent();
         }
       });
 }
 private void captureUsagesExpandState(TreePath pathFrom, final Collection<UsageState> states) {
   if (!myTree.isExpanded(pathFrom)) {
     return;
   }
   final DefaultMutableTreeNode node = (DefaultMutableTreeNode) pathFrom.getLastPathComponent();
   final int childCount = node.getChildCount();
   for (int idx = 0; idx < childCount; idx++) {
     final TreeNode child = node.getChildAt(idx);
     if (child instanceof UsageNode) {
       final Usage usage = ((UsageNode) child).getUsage();
       states.add(
           new UsageState(
               usage,
               myTree.getSelectionModel().isPathSelected(pathFrom.pathByAddingChild(child))));
     } else {
       captureUsagesExpandState(pathFrom.pathByAddingChild(child), states);
     }
   }
 }
  public CustomizableActionsPanel() {

    //noinspection HardCodedStringLiteral
    Group rootGroup = new Group("root", null, null);
    final DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootGroup);
    DefaultTreeModel model = new DefaultTreeModel(root);
    myActionsTree.setModel(model);

    myActionsTree.setRootVisible(false);
    myActionsTree.setShowsRootHandles(true);
    UIUtil.setLineStyleAngled(myActionsTree);
    myActionsTree.setCellRenderer(new MyTreeCellRenderer());

    setButtonsDisabled();
    final ActionManager actionManager = ActionManager.getInstance();
    myActionsTree
        .getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {
              public void valueChanged(TreeSelectionEvent e) {
                final TreePath[] selectionPaths = myActionsTree.getSelectionPaths();
                final boolean isSingleSelection =
                    selectionPaths != null && selectionPaths.length == 1;
                myAddActionButton.setEnabled(isSingleSelection);
                if (isSingleSelection) {
                  final DefaultMutableTreeNode node =
                      (DefaultMutableTreeNode) selectionPaths[0].getLastPathComponent();
                  String actionId = getActionId(node);
                  if (actionId != null) {
                    final AnAction action = actionManager.getAction(actionId);
                    myEditIconButton.setEnabled(
                        action != null && action.getTemplatePresentation() != null);
                  } else {
                    myEditIconButton.setEnabled(false);
                  }
                } else {
                  myEditIconButton.setEnabled(false);
                }
                myAddSeparatorButton.setEnabled(isSingleSelection);
                myRemoveActionButton.setEnabled(selectionPaths != null);
                if (selectionPaths != null) {
                  for (TreePath selectionPath : selectionPaths) {
                    if (selectionPath.getPath() != null && selectionPath.getPath().length <= 2) {
                      setButtonsDisabled();
                      return;
                    }
                  }
                }
                myMoveActionUpButton.setEnabled(isMoveSupported(myActionsTree, -1));
                myMoveActionDownButton.setEnabled(isMoveSupported(myActionsTree, 1));
                myRestoreDefaultButton.setEnabled(!findActionsUnderSelection().isEmpty());
              }
            });

    myAddActionButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree);
            final TreePath selectionPath = myActionsTree.getLeadSelectionPath();
            if (selectionPath != null) {
              DefaultMutableTreeNode node =
                  (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
              final FindAvailableActionsDialog dlg = new FindAvailableActionsDialog();
              dlg.show();
              if (dlg.isOK()) {
                final Set<Object> toAdd = dlg.getTreeSelectedActionIds();
                if (toAdd == null) return;
                for (final Object o : toAdd) {
                  final ActionUrl url =
                      new ActionUrl(
                          ActionUrl.getGroupPath(new TreePath(node.getPath())),
                          o,
                          ActionUrl.ADDED,
                          node.getParent().getIndex(node) + 1);
                  addCustomizedAction(url);
                  ActionUrl.changePathInActionsTree(myActionsTree, url);
                  if (o instanceof String) {
                    DefaultMutableTreeNode current = new DefaultMutableTreeNode(url.getComponent());
                    current.setParent((DefaultMutableTreeNode) node.getParent());
                    editToolbarIcon((String) o, current);
                  }
                }
                ((DefaultTreeModel) myActionsTree.getModel()).reload();
              }
            }
            TreeUtil.restoreExpandedPaths(myActionsTree, expandedPaths);
          }
        });

    myEditIconButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            myRestoreAllDefaultButton.setEnabled(true);
            final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree);
            final TreePath selectionPath = myActionsTree.getLeadSelectionPath();
            if (selectionPath != null) {
              EditIconDialog dlg =
                  new EditIconDialog((DefaultMutableTreeNode) selectionPath.getLastPathComponent());
              dlg.show();
              if (dlg.isOK()) {
                myActionsTree.repaint();
              }
            }
            TreeUtil.restoreExpandedPaths(myActionsTree, expandedPaths);
          }
        });

    myAddSeparatorButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree);
            final TreePath selectionPath = myActionsTree.getLeadSelectionPath();
            if (selectionPath != null) {
              DefaultMutableTreeNode node =
                  (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
              final ActionUrl url =
                  new ActionUrl(
                      ActionUrl.getGroupPath(selectionPath),
                      Separator.getInstance(),
                      ActionUrl.ADDED,
                      node.getParent().getIndex(node) + 1);
              ActionUrl.changePathInActionsTree(myActionsTree, url);
              addCustomizedAction(url);
              ((DefaultTreeModel) myActionsTree.getModel()).reload();
            }
            TreeUtil.restoreExpandedPaths(myActionsTree, expandedPaths);
          }
        });

    myRemoveActionButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree);
            final TreePath[] selectionPath = myActionsTree.getSelectionPaths();
            if (selectionPath != null) {
              for (TreePath treePath : selectionPath) {
                final ActionUrl url = CustomizationUtil.getActionUrl(treePath, ActionUrl.DELETED);
                ActionUrl.changePathInActionsTree(myActionsTree, url);
                addCustomizedAction(url);
              }
              ((DefaultTreeModel) myActionsTree.getModel()).reload();
            }
            TreeUtil.restoreExpandedPaths(myActionsTree, expandedPaths);
          }
        });

    myMoveActionUpButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree);
            final TreePath[] selectionPath = myActionsTree.getSelectionPaths();
            if (selectionPath != null) {
              for (TreePath treePath : selectionPath) {
                final ActionUrl url = CustomizationUtil.getActionUrl(treePath, ActionUrl.MOVE);
                final int absolutePosition = url.getAbsolutePosition();
                url.setInitialPosition(absolutePosition);
                url.setAbsolutePosition(absolutePosition - 1);
                ActionUrl.changePathInActionsTree(myActionsTree, url);
                addCustomizedAction(url);
              }
              ((DefaultTreeModel) myActionsTree.getModel()).reload();
              TreeUtil.restoreExpandedPaths(myActionsTree, expandedPaths);
              for (TreePath path : selectionPath) {
                myActionsTree.addSelectionPath(path);
              }
            }
          }
        });

    myMoveActionDownButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myActionsTree);
            final TreePath[] selectionPath = myActionsTree.getSelectionPaths();
            if (selectionPath != null) {
              for (int i = selectionPath.length - 1; i >= 0; i--) {
                TreePath treePath = selectionPath[i];
                final ActionUrl url = CustomizationUtil.getActionUrl(treePath, ActionUrl.MOVE);
                final int absolutePosition = url.getAbsolutePosition();
                url.setInitialPosition(absolutePosition);
                url.setAbsolutePosition(absolutePosition + 1);
                ActionUrl.changePathInActionsTree(myActionsTree, url);
                addCustomizedAction(url);
              }
              ((DefaultTreeModel) myActionsTree.getModel()).reload();
              TreeUtil.restoreExpandedPaths(myActionsTree, expandedPaths);
              for (TreePath path : selectionPath) {
                myActionsTree.addSelectionPath(path);
              }
            }
          }
        });

    myRestoreAllDefaultButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            mySelectedSchema.copyFrom(new CustomActionsSchema());
            patchActionsTreeCorrespondingToSchema(root);
            myRestoreAllDefaultButton.setEnabled(false);
          }
        });

    myRestoreDefaultButton.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            final List<ActionUrl> otherActions =
                new ArrayList<ActionUrl>(mySelectedSchema.getActions());
            otherActions.removeAll(findActionsUnderSelection());
            mySelectedSchema.copyFrom(new CustomActionsSchema());
            for (ActionUrl otherAction : otherActions) {
              mySelectedSchema.addAction(otherAction);
            }
            final List<TreePath> treePaths = TreeUtil.collectExpandedPaths(myActionsTree);
            patchActionsTreeCorrespondingToSchema(root);
            restorePathsAfterTreeOptimization(treePaths);
            myRestoreDefaultButton.setEnabled(false);
          }
        });

    patchActionsTreeCorrespondingToSchema(root);

    myTreeExpansionMonitor = TreeExpansionMonitor.install(myActionsTree);
  }
    protected JComponent createCenterPanel() {
      Group rootGroup =
          ActionsTreeUtil.createMainGroup(
              null, null, QuickListsManager.getInstance().getAllQuickLists());
      DefaultMutableTreeNode root = ActionsTreeUtil.createNode(rootGroup);
      DefaultTreeModel model = new DefaultTreeModel(root);
      myTree = new Tree();
      myTree.setModel(model);
      myTree.setCellRenderer(new MyTreeCellRenderer());
      final ActionManager actionManager = ActionManager.getInstance();

      mySetIconButton = new JButton(IdeBundle.message("button.set.icon"));
      mySetIconButton.setEnabled(false);
      mySetIconButton.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              final TreePath selectionPath = myTree.getSelectionPath();
              if (selectionPath != null) {
                doSetIcon(
                    (DefaultMutableTreeNode) selectionPath.getLastPathComponent(),
                    myTextField.getText(),
                    getContentPane());
                myTree.repaint();
              }
            }
          });
      myTextField = createBrowseField();
      myTextField
          .getTextField()
          .getDocument()
          .addDocumentListener(
              new DocumentAdapter() {
                protected void textChanged(DocumentEvent e) {
                  enableSetIconButton(actionManager);
                }
              });
      JPanel northPanel = new JPanel(new BorderLayout());
      northPanel.add(myTextField, BorderLayout.CENTER);
      final JLabel label = new JLabel(IdeBundle.message("label.icon.path"));
      label.setLabelFor(myTextField.getChildComponent());
      northPanel.add(label, BorderLayout.WEST);
      northPanel.add(mySetIconButton, BorderLayout.EAST);
      northPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
      JPanel panel = new JPanel(new BorderLayout());
      panel.add(northPanel, BorderLayout.NORTH);

      panel.add(ScrollPaneFactory.createScrollPane(myTree), BorderLayout.CENTER);
      myTree
          .getSelectionModel()
          .addTreeSelectionListener(
              new TreeSelectionListener() {
                public void valueChanged(TreeSelectionEvent e) {
                  enableSetIconButton(actionManager);
                  final TreePath selectionPath = myTree.getSelectionPath();
                  if (selectionPath != null) {
                    final DefaultMutableTreeNode node =
                        (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
                    final String actionId = getActionId(node);
                    if (actionId != null) {
                      final String iconPath = mySelectedSchema.getIconPath(actionId);
                      myTextField.setText(FileUtil.toSystemDependentName(iconPath));
                    }
                  }
                }
              });
      return panel;
    }
  /**
   * Constructs a X509 certificate panel.
   *
   * @param certificates <tt>X509Certificate</tt> objects
   */
  public X509CertificatePanel(Certificate[] certificates) {
    setLayout(new BorderLayout(5, 5));

    // Certificate chain list
    TransparentPanel topPanel = new TransparentPanel(new BorderLayout());
    topPanel.add(
        new JLabel(
            "<html><body><b>"
                + R.getI18NString("service.gui.CERT_INFO_CHAIN")
                + "</b></body></html>"),
        BorderLayout.NORTH);

    DefaultMutableTreeNode top = new DefaultMutableTreeNode();
    DefaultMutableTreeNode previous = top;
    for (int i = certificates.length - 1; i >= 0; i--) {
      Certificate cert = certificates[i];
      DefaultMutableTreeNode next = new DefaultMutableTreeNode(cert);
      previous.add(next);
      previous = next;
    }
    JTree tree = new JTree(top);
    tree.setBorder(new BevelBorder(BevelBorder.LOWERED));
    tree.setRootVisible(false);
    tree.setExpandsSelectedPaths(true);
    tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    tree.setCellRenderer(
        new DefaultTreeCellRenderer() {

          @Override
          public Component getTreeCellRendererComponent(
              JTree tree,
              Object value,
              boolean sel,
              boolean expanded,
              boolean leaf,
              int row,
              boolean hasFocus) {
            JLabel component =
                (JLabel)
                    super.getTreeCellRendererComponent(
                        tree, value, sel, expanded, leaf, row, hasFocus);
            if (value instanceof DefaultMutableTreeNode) {
              Object o = ((DefaultMutableTreeNode) value).getUserObject();
              if (o instanceof X509Certificate) {
                component.setText(getSimplifiedName((X509Certificate) o));
              } else {
                // We don't know how to represent this certificate type,
                // let's use the first 20 characters
                String text = o.toString();
                if (text.length() > 20) {
                  text = text.substring(0, 20);
                }
                component.setText(text);
              }
            }
            return component;
          }
        });
    tree.getSelectionModel()
        .addTreeSelectionListener(
            new TreeSelectionListener() {

              @Override
              public void valueChanged(TreeSelectionEvent e) {
                valueChangedPerformed(e);
              }
            });
    tree.setSelectionPath(
        new TreePath((((DefaultTreeModel) tree.getModel()).getPathToRoot(previous))));
    topPanel.add(tree, BorderLayout.CENTER);

    add(topPanel, BorderLayout.NORTH);

    // Certificate details pane
    Caret caret = infoTextPane.getCaret();
    if (caret instanceof DefaultCaret) {
      ((DefaultCaret) caret).setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
    }

    /*
     * Make JEditorPane respect our default font because we will be using it
     * to just display text.
     */
    infoTextPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true);

    infoTextPane.setOpaque(false);
    infoTextPane.setEditable(false);
    infoTextPane.setContentType("text/html");
    infoTextPane.setText(toString(certificates[0]));

    final JScrollPane certScroll = new JScrollPane(infoTextPane);
    certScroll.setPreferredSize(new Dimension(300, 500));
    add(certScroll, BorderLayout.CENTER);
  }
示例#15
0
文件: TreeUtil.java 项目: jexp/idea2
 public static boolean isOverSelection(final JTree tree, final Point point) {
   TreePath path = tree.getPathForLocation(point.x, point.y);
   return path != null && tree.getSelectionModel().isPathSelected(path);
 }
示例#16
0
文件: TreeUtil.java 项目: jexp/idea2
  public static ActionCallback showAndSelect(
      final JTree tree,
      int top,
      int bottom,
      final int row,
      final int previous,
      boolean addToSelection,
      final boolean scroll) {
    final TreePath path = tree.getPathForRow(row);

    if (path == null) return new ActionCallback.Done();

    final int size = tree.getRowCount();
    if (size == 0) {
      tree.clearSelection();
      return new ActionCallback.Done();
    }
    if (top < 0) {
      top = 0;
    }
    if (bottom >= size) {
      bottom = size - 1;
    }

    if (row >= tree.getRowCount()) return new ActionCallback.Done();

    if (!tree.isValid()) {
      tree.validate();
    }

    final Rectangle rowBounds = tree.getRowBounds(row);
    if (rowBounds == null) return new ActionCallback.Done();

    Rectangle topBounds = tree.getRowBounds(top);
    if (topBounds == null) {
      topBounds = rowBounds;
    }

    Rectangle bottomBounds = tree.getRowBounds(bottom);
    if (bottomBounds == null) {
      bottomBounds = rowBounds;
    }

    Rectangle bounds = topBounds.union(bottomBounds);
    bounds.x = rowBounds.x;
    bounds.width = rowBounds.width;

    final Rectangle visible = tree.getVisibleRect();
    if (visible.contains(bounds)) {
      bounds = null;
    } else {
      final Component comp =
          tree.getCellRenderer()
              .getTreeCellRendererComponent(
                  tree, path.getLastPathComponent(), true, true, false, row, false);

      if (comp instanceof SimpleColoredComponent) {
        final SimpleColoredComponent renderer = ((SimpleColoredComponent) comp);
        final Dimension scrollableSize = renderer.computePreferredSize(true);
        bounds.width = scrollableSize.width;
      }
    }

    final ActionCallback callback = new ActionCallback();

    if (!tree.isRowSelected(row)) {
      if (addToSelection) {
        tree.getSelectionModel().addSelectionPath(tree.getPathForRow(row));
      } else {
        tree.setSelectionRow(row);
      }
    }

    if (bounds != null) {
      final Range<Integer> range = getExpandControlRange(tree, path);
      if (range != null) {
        int delta = bounds.x - range.getFrom().intValue();
        bounds.x -= delta;
        bounds.width -= delta;
      }

      if (visible.width < bounds.width) {
        bounds.width = visible.width;
      }

      final Rectangle b1 = bounds;
      final Runnable runnable =
          new Runnable() {
            public void run() {
              if (scroll) {
                tree.scrollRectToVisible(b1);
              }
              callback.setDone();
            }
          };

      if (ApplicationManager.getApplication().isUnitTestMode()) {
        runnable.run();
      } else {
        SwingUtilities.invokeLater(runnable);
      }
    } else {
      callback.setDone();
    }

    return callback;
  }