[英]Strikethrough a node in a JTree
In my project i have a Jtree with custom node (which extends DefaultMutableTreeNode). 在我的项目中,我有一个带有自定义节点的Jtree(扩展了DefaultMutableTreeNode)。 Each node is associated with a boolean value. 每个节点都与一个布尔值相关联。 When the boolean is False i woul like to strike the texte of my node. 当布尔值为False时,我想敲击节点的texte。 So for example : 因此,例如:
I tried to create a new Font but i don't find any properties to strike the text and i only managed to add my custom font to the whole tree and not node by node. 我试图创建一个新的字体,但是我没有找到任何属性来删除文本,我只设法将自定义字体添加到整个树中,而不是逐个节点地添加。
I think that i should use the TreeRenderer but i can't find any method to help me strike the node. 我认为我应该使用TreeRenderer,但是我找不到任何方法来帮助我击中该节点。
Does someone have an idea on i can do it ? 有人对我有想法吗?
Check out the example below. 查看以下示例。 For keeping it simple, I am just striking through the selected node. 为了简单起见,我仅介绍了所选节点。 You need to, of course, use your own check on the value. 当然,您需要对值使用自己的检查。
package snippet;
import java.awt.Component;
import java.awt.Font;
import java.awt.font.TextAttribute;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultTreeCellRenderer;
public class JTreeTest extends JFrame {
private final class StrikeoutCellRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1L;
@Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
Component c = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Font font = c.getFont();
Map attributes = font.getAttributes();
if(sel)
attributes.put(TextAttribute.STRIKETHROUGH, TextAttribute.STRIKETHROUGH_ON);
else
attributes.remove(TextAttribute.STRIKETHROUGH);
Font newFont = new Font(attributes);
c.setFont(newFont);
return c;
}
}
private static final long serialVersionUID = 1L;
public JTreeTest() {
super(JTreeTest.class.getName());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents();
}
private void initComponents() {
JTree tree = new JTree();
tree.setCellRenderer(new StrikeoutCellRenderer());
add(tree);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override public void run() {
JTreeTest t = new JTreeTest();
t.setVisible(true);
}
});
}
}
Note that even if the node doesn't need a strike through, you need to reset the attribute, since a single component is used for painting all the nodes. 请注意,即使节点不需要删除线,您也需要重置属性,因为单个组件用于绘制所有节点。
最简单的方法是定义一个渲染器(扩展DefaultTreeCellRenderer
),并调用setText()
传递html字符串(例如“ <html><u>node1.2</u></html>
”)作为删除线的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.