我创建了一个自定义JTree。可以过滤该树以仅显示包含给定条件(字符串)的那些节点。现在,有没有办法只粗体化那个包含搜索字符串的DefaulMutableTreeNode部分?
如果树节点具有label =“StackOverflow”且用户正在搜索包含“Stack”的节点,则“StackOverflow”节点将以“Stack”部分粗体呈现。
如何实现?
答案 0 :(得分:9)
您需要设置自己的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);