1. Java Swing Tree API
package com.home.swing; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreePath; public class JSTree { public JTree ctrl; public JSTree(String rootName, Runnable handler) { DefaultMutableTreeNode root = new DefaultMutableTreeNode(rootName); /* root.add( new DefaultMutableTreeNode("하위1") ); root.add( new DefaultMutableTreeNode("하위2") ); */ ctrl = new JTree(root); if( handler != null ) { setTreeHandler(handler); } } public void showTreeRoot() { ctrl.setRootVisible(true);} public void hideTreeRoot() { ctrl.setRootVisible(false);} public void setTreeHandler(Runnable runnable) { ctrl.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener(){ public void valueChanged(TreeSelectionEvent event) { runnable.run(); } }); } public String getTreeSelectionPath() { return ctrl.getSelectionModel().getSelectionPath().toString(); } public void addTreeToRoot(String name) { DefaultTreeModel model = (DefaultTreeModel) ctrl.getModel(); DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot(); DefaultMutableTreeNode node = new DefaultMutableTreeNode(name); model.insertNodeInto(node, root, root.getChildCount()); //model.insertNodeInto(node, root, model.getChildCount(root)); model.reload(root); } public DefaultMutableTreeNode getSelectedNode() { return (DefaultMutableTreeNode)ctrl.getLastSelectedPathComponent(); } public String[] getSelectedTreePath() { TreePath path = ctrl.getSelectionPath(); if( path != null ) { int count = path.getPathCount(); String[] nodes = new String[count]; for( int i = 0; i < count; i++ ) { nodes[count-i-1] = path.getLastPathComponent().toString(); path = path.getParentPath(); } return nodes; } return null; } }
댓글 없음:
댓글 쓰기