緩侃斤JTree序佩制婢?幹秀CheckBoxTree?乎窃峪頁葎JTree耶紗阻匯倖MouseListener?參寥油報炎僉嶄峯准泣朔?泌採譜崔拘僉炎芝?旺嶷紙峯。
public class CheckBoxTree extends JTree {
private static final long serialVersionUID = -217950037507321241L;
public CheckBoxTree(TreeModel newModel) {
super(newModel);
addCheckingListener();
}
private void addCheckingListener() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int row = getRowForLocation(e.getX(), e.getY());
TreePath treePath = getPathForRow(row);
if (treePath == null) {
return;
}
CheckBoxTreeNode node = ((CheckBoxTreeNode) treePath.getLastPathComponent());
boolean checking = !node.isChecked(); // 泌惚乎准泣厮瓜拘僉貧?夸緩肝繍函?拘僉?郡岻?呀郡。
checkNode(node, checking);
repaint(); // 嶷紙屁臣峯。
}
// 弓拷仇拘僉賜函?拘僉峺協准泣式凪侭嗤和雫准泣議CheckBox。
private void checkNode(CheckBoxTreeNode node, boolean checking) {
node.setChecked(checking);
if (!node.isLeaf()) {
Enumeration<CheckBoxTreeNode> children = node.children();
while (children.hasMoreElements()) {
checkNode(children.nextElement(), checking);
}
}
}
});
}
}
貧峰殻會嗤曾倖購囚泣?
1. 譜崔輝念准泣式凪徨准泣議拘僉炎芝--checkNode?
2. 嶷紙峯--repaint。距喘repaint圭隈斤峯序佩紙崙扮?圭隈TreeCellRenderer.getTreeCellRendererComponent祥氏瓜距喘?緩扮殻會祥氏功象checkNode圭隈譜協議isChecked栖 |