注意:我不是在问如何在 JTree 中放置一个复选框——以前,一个困惑的版主认为这就是我要问的。我已经在树中有复选框。我在问什么类或方法控制复选框的可检查性......
为了在 Tree 节点中获得一个复选框,我读到您必须制作一个复选框渲染器,所以我做了一个:
class CheckboxCellRenderer implements TreeCellRenderer {
final static Logger logger = LoggerFactory.getLogger(CheckboxCellRenderer.class);
JLabel firstNameLabel = new JLabel(" ");
JPanel renderer = new JPanel();
JCheckBox checkbox;
DefaultTreeCellRenderer defaultRenderer = new DefaultTreeCellRenderer();
public CheckboxCellRenderer() {
super();
checkbox = new JCheckBox(firstNameLabel.getText(), false);
renderer.add(checkbox);
renderer.add(firstNameLabel);
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
Component returnValue = null;
firstNameLabel.setText(value.toString());
if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
renderer.setEnabled(tree.isEnabled());
if(((DefaultMutableTreeNode) value).getLevel()==1){
returnValue = renderer;
}
}
if (returnValue == null) {
returnValue = defaultRenderer.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
}
return returnValue;
}
}
这将在树节点中创建复选框。但是由于某种原因,这使得复选框无法选中,当我单击它时没有任何反应。为什么在渲染器中创建复选框会“破坏”复选框?如何使复选框可选中(即当我单击复选框时它会被选中,而当我再次单击它时它会被取消选中)?