3

我创建了一个自定义 JTree。可以过滤该树以仅显示那些包含给定条件(字符串)的节点。现在,有没有办法只加粗包含搜索字符串的 DefaulMutableTreeNode 部分?

如果树节点的标签为“StackOverflow”并且用户正在搜索包含“Stack”的节点,则“StackOverflow”节点将呈现“Stack”部分加粗。

如何做到这一点?

4

1 回答 1

8

您需要设置自己的TreeCellRenderer.

例子:

下面的代码产生了这个屏幕截图:

截屏

final JTextField field = new JTextField();
final JTree tree = new JTree(new String[] {"Hello World", "StackOverflow"});
tree.setCellRenderer(new DefaultTreeCellRenderer() {
    @Override
    public Component getTreeCellRendererComponent(JTree tree,
            Object value, boolean sel, boolean expanded, boolean leaf,
            int row, boolean hasFocus) {

        String search = field.getText();
        String text = value.toString();

        StringBuffer html = new StringBuffer("<html>");
        Matcher m = Pattern.compile(Pattern.quote(search)).matcher(text);
        while (m.find())
            m.appendReplacement(html, "<b>" + m.group() + "</b>");
        m.appendTail(html).append("</html>");

        return super.getTreeCellRendererComponent(
                tree, html.toString(), sel, expanded, leaf, row, hasFocus);
    }
});
field.addKeyListener(new KeyAdapter() {
    @Override public void keyReleased(KeyEvent e) { update(); }
    private void update() { 
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged((TreeNode) model.getRoot());
    }
});
JFrame frame = new JFrame("Test");
frame.add(field, BorderLayout.NORTH);
frame.add(tree, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setVisible(true);

于 2012-06-11T08:25:42.753 回答