日期:2014-05-20 浏览次数:20750 次
import java.util.Enumeration; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; class TreeFrame implements TreeSelectionListener { private JTree example = null; public TreeFrame() { DefaultMutableTreeNode root = new DefaultMutableTreeNode(" root ", true); DefaultMutableTreeNode a = new DefaultMutableTreeNode(" A "); root.add(a); a.add(new DefaultMutableTreeNode(" AA ")); a.add(new DefaultMutableTreeNode(" AB ")); DefaultMutableTreeNode b = new DefaultMutableTreeNode(" B "); root.add(b); b.add(new DefaultMutableTreeNode(" BA ")); b.add(new DefaultMutableTreeNode(" BB ")); DefaultMutableTreeNode c = new DefaultMutableTreeNode(" C "); root.add(c); c.add(new DefaultMutableTreeNode(" AA ")); c.add(new DefaultMutableTreeNode(" AB ")); example = new JTree(root); example.addTreeSelectionListener(this); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); panel.add(new JScrollPane(example)); JFrame frame = new JFrame(" JTreeDemo "); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.setSize(250, 400); frame.setVisible(true); } public void valueChanged(TreeSelectionEvent e) { example.expandPath(e.getPath()); DefaultMutableTreeNode dm = (DefaultMutableTreeNode) e.getPath() .getLastPathComponent(); for (Enumeration em = dm.children(); em.hasMoreElements();) { TreeNode n = (TreeNode) em.nextElement(); TreePath visiblePath = new TreePath(((DefaultTreeModel) example .getModel()).getPathToRoot(n)); example.addSelectionPath(visiblePath); } } } public class TreeTest { public static void main(String[] args) { new TreeFrame(); } }
------解决方案--------------------
不太懂这个,期待高手尽快出现,希望楼主早点解决难题。
帮顶一下
------解决方案--------------------
不懂 绑定 顺便借点分
------解决方案--------------------
嘿嘿 在5楼那哥们基础上改了一下 不知道是楼主的要的不
public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode dm = (DefaultMutableTreeNode) e.getPath().getLastPathComponent(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) example.getModel().getRoot(); for (Enumeration em = dm.children(); em.hasMoreElements();) { TreeNode n = (TreeNode) em.nextElement(); for (Enumeration rootem = root.breadthFirstEnumeration(); rootem.hasMoreElements();) { TreeNode rootn = (TreeNode) rootem.nextElement(); if (String.valueOf(n).equals(String.valueOf(rootn))) { TreePath path = new TreePath(((DefaultTreeModel) example.getModel()).getPathToRoot(rootn)); example.addSelectionPath(path); } } TreePath visiblePath = new TreePath(((DefaultTreeModel) example.getModel()).getPathToRoot(n)); example.addSelectionPath(visiblePath); } }