对JTree的操作
当右键点击树的某个节点可以对其进行重命名,删除
当右键点击树的某个根节点可以添加节点
用java实现cs版 谢谢大家!!
[解决办法]
图片看不了。。。。
[解决办法]
看不明白。。。
[解决办法]
我也是刚学习,不太懂,这个你运行下,也许对你有用!
/** @version 1.02 2004-08-21 @author Cay Horstmann*/package ultrapower;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.tree.*;/** This program demonstrates tree editing.*/public class TreeEditTest{ public static void main(String[] args) { JFrame frame = new TreeEditFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }}/** A frame with a tree and buttons to edit the tree.*/class TreeEditFrame extends JFrame{ Container c=this.getContentPane(); public TreeEditFrame() { setTitle("TreeEditTest"); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // construct tree TreeNode root = makeSampleTree(); model = new DefaultTreeModel(root); tree = new JTree(model); tree.setEditable(true); // add scroll pane with tree JScrollPane scrollPane = new JScrollPane(tree); c.add(scrollPane, BorderLayout.CENTER); makeButtons(); } public TreeNode makeSampleTree() { DefaultMutableTreeNode root = new DefaultMutableTreeNode("World"); DefaultMutableTreeNode country = new DefaultMutableTreeNode("USA"); root.add(country); DefaultMutableTreeNode state = new DefaultMutableTreeNode("California"); country.add(state); DefaultMutableTreeNode city = new DefaultMutableTreeNode("San Jose"); state.add(city); city = new DefaultMutableTreeNode("San Diego"); state.add(city); state = new DefaultMutableTreeNode("Michigan"); country.add(state); city = new DefaultMutableTreeNode("Ann Arbor"); state.add(city); country = new DefaultMutableTreeNode("Germany"); root.add(country); state = new DefaultMutableTreeNode("Schleswig-Holstein"); country.add(state); city = new DefaultMutableTreeNode("Kiel"); state.add(city); return root; } /** Makes the buttons to add a sibling, add a child, and delete a node. */ public void makeButtons() { JPanel panel = new JPanel(); JButton addSiblingButton = new JButton("Add Sibling"); addSiblingButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (selectedNode == null) return; DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent(); if (parent == null) return; DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New"); int selectedIndex = parent.getIndex(selectedNode); model.insertNodeInto(newNode, parent, selectedIndex + 1); // now display new node TreeNode[] nodes = model.getPathToRoot(newNode); TreePath path = new TreePath(nodes); tree.scrollPathToVisible(path); } }); panel.add(addSiblingButton); JButton addChildButton = new JButton("Add Child"); addChildButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (selectedNode == null) return; DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("New"); model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount()); // now display new node TreeNode[] nodes = model.getPathToRoot(newNode); TreePath path = new TreePath(nodes); tree.scrollPathToVisible(path); } }); panel.add(addChildButton); JButton deleteButton = new JButton("Delete"); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (selectedNode != null && selectedNode.getParent() != null) model.removeNodeFromParent(selectedNode); } }); panel.add(deleteButton); c.add(panel, BorderLayout.SOUTH); } private DefaultTreeModel model; private JTree tree; private static final int DEFAULT_WIDTH = 400; private static final int DEFAULT_HEIGHT = 200;}
[解决办法]
import java.awt.*;import javax.swing.*;import javax.swing.tree.*;import java.awt.event.*;import java.util.Enumeration;import javax.swing.event.*;public class JTreeDemo2 extends JFrame{ private static final long serialVersionUID = 1L; JPanel cp = new JPanel(); JPanel panelStatus=new JPanel(); JTree jtree; JLabel labelStatus=new JLabel(); DefaultMutableTreeNode root; JSplitPane jSplitPane = new JSplitPane(); JScrollPane jscrpane1 = new JScrollPane(); JScrollPane jscrpane2 = new JScrollPane(); JTextArea jta1 = new JTextArea("tree selected\n"); private JButton buttonAddSibling=null, buttonAddChild=null, buttonRefresh=null; private JButton buttonExpandTree=null, buttonCollapseTree=null, buttonDelete=null; private JToolBar toolbar=null; private JPopupMenu popupMenu=null; private JMenuItem menuItemAddSibling, menuItemAddChild, menuItemExit, menuItemDelete; private JMenu menuFile, menuEdit; private JMenuBar menuBar; private final String ADD_SIBLING="addSibling", ADD_CHILD="addChild", DELETE="delete"; public JTreeDemo2() { try { javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e1) { e1.printStackTrace(); } this.setSize(300, 300); this.setTitle("try to use tree"); cp = (JPanel) this.getContentPane(); cp.setLayout(new BorderLayout()); setJMenuBar(createMenuBar()); toolbar= new JToolBar(); toolbar.setRollover(true); toolbar.setFloatable(false); toolbar.add(getAddSiblingNode()); toolbar.add(getAddChildNode()); toolbar.add(getDeleteNode()); toolbar.add(getRefreshButton()); toolbar.addSeparator(); toolbar.add(getExpandTree()); toolbar.add(getCollapseTree()); cp.add(toolbar, BorderLayout.NORTH); jSplitPane.setDividerSize(2); jSplitPane.setOneTouchExpandable(true); jSplitPane.setDividerLocation(190); jSplitPane.setContinuousLayout(true); root = new DefaultMutableTreeNode("school"); createTree(root); jtree = new JTree(root); jtree.setRootVisible(true); treeCellRender(jtree); jscrpane1.getViewport().add(jtree); jSplitPane.add(jscrpane1, JSplitPane.LEFT); jscrpane2.getViewport().add(jta1); //jSplitPane.setRightComponent(jscrpane2); jSplitPane.add(jscrpane2, JSplitPane.RIGHT); cp.add(jSplitPane, BorderLayout.CENTER); panelStatus.setLayout(new BorderLayout()); panelStatus.setBorder(BorderFactory.createLoweredBevelBorder()); panelStatus.setPreferredSize(new Dimension(300, 24)); labelStatus.setText(" over"); panelStatus.add(labelStatus, BorderLayout.WEST); cp.add(panelStatus, BorderLayout.SOUTH); jtree.addTreeSelectionListener(new TreeSelectionListener() { public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = new DefaultMutableTreeNode(); node = (DefaultMutableTreeNode) jtree.getLastSelectedPathComponent(); if (node == null) return; Object info = node.getUserObject(); if (node.isLeaf()) { jta1.append(" "+info.toString() + " is selected, it is a leaf"+ "\n"); labelStatus.setText(" "+info.toString() + " is selected, it is a leaf"); } else { jta1.append(" "+info.toString()+ " is selected, it is not a lesf" + "\n"); labelStatus.setText(" "+info.toString()+ " is selected, it is not a lesf"); } } }); jtree.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(MouseEvent e) { showPopupMenu(e); } }); } private JMenuBar createMenuBar() { menuBar=new JMenuBar(); menuFile=new JMenu("File"); menuFile.setMnemonic(KeyEvent.VK_F); menuItemExit=new JMenuItem("Exit"); menuItemExit.setMnemonic(KeyEvent.VK_E); menuItemExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); menuFile.add(menuItemExit); menuEdit=new JMenu("Edit"); menuEdit.setMnemonic(KeyEvent.VK_E); menuEdit.add(getAddChildMenuItem()); menuEdit.add(getAddSiblingMenuItem()); menuEdit.add(getDeleteMenuItem()); menuBar.add(menuFile); menuBar.add(menuEdit); return menuBar; } private JButton getExpandTree() { buttonExpandTree=new JButton(new ImageIcon(getClass().getResource("/jfcswing/images/expandtree.png"))); buttonExpandTree.setToolTipText("Expand Tree"); buttonExpandTree.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ expandAll(jtree, new TreePath(jtree.getModel().getRoot())); } }); return buttonExpandTree; } private JButton getCollapseTree() { buttonCollapseTree=new JButton(new ImageIcon(getClass().getResource("/jfcswing/images/collapsetree.png"))); buttonCollapseTree.setToolTipText("Collapse Tree"); buttonCollapseTree.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ collapseAll(jtree, new TreePath(jtree.getModel().getRoot())); } }); return buttonCollapseTree; } private JButton getRefreshButton() { buttonRefresh=new JButton(new ImageIcon(getClass().getResource("/jfcswing/images/refresh.png"))); buttonRefresh.setToolTipText("Refresh"); buttonRefresh.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ root = new DefaultMutableTreeNode("school"); createTree(root); } }); return buttonRefresh; }
[解决办法]
private void createTree(DefaultMutableTreeNode root) { DefaultMutableTreeNode classroom = new DefaultMutableTreeNode("classroom"); DefaultMutableTreeNode number = null; root.add(classroom); for (int i = 1; i <= 8; i++) { number = new DefaultMutableTreeNode("no." + String.valueOf(i)); if (i == 4) { for (int j = 1; j <= 5; j++) { number.add(new DefaultMutableTreeNode("seat" + String.valueOf(j))); } } classroom.add(number); } } protected void processWindowEvent(WindowEvent e) { if (e.getID() == WindowEvent.WINDOW_CLOSING) { System.exit(0); } } /** */ private void treeCellRender(JTree tree) { DefaultTreeCellRenderer cellRenderer = (DefaultTreeCellRenderer) tree.getCellRenderer(); cellRenderer.setLeafIcon(new ImageIcon(getClass().getResource("/jfcswing/images/Open16.gif"))); cellRenderer.setOpenIcon(new ImageIcon(getClass().getResource("/jfcswing/images/Save16.gif"))); cellRenderer.setClosedIcon(new ImageIcon(getClass().getResource("/jfcswing/images/Save16.gif"))); tree.setCellRenderer(cellRenderer); } private JButton getAddSiblingNode() { buttonAddSibling=new JButton(new ImageIcon(getClass().getResource("/jfcswing/images/batchadd.png"))); buttonAddSibling.setToolTipText("Add Sibling"); buttonAddSibling.addActionListener(new AddNewNode(ADD_SIBLING)); return buttonAddSibling; } private JButton getAddChildNode() { buttonAddChild=new JButton(new ImageIcon(getClass().getResource("/jfcswing/images/mobile.png"))); buttonAddChild.setToolTipText("Add Child"); buttonAddChild.addActionListener(new AddNewNode(ADD_CHILD)); return buttonAddChild; } private JButton getDeleteNode() { buttonDelete=new JButton(new ImageIcon(getClass().getResource("/jfcswing/images/delete.png"))); buttonDelete.setToolTipText("Delete"); buttonDelete.addActionListener(new AddNewNode(DELETE)); return buttonDelete; } /** * 添加子结点 */ class AddNewNode implements ActionListener { private String nodeType; public AddNewNode(String nodeType) { this.nodeType = nodeType; } public void actionPerformed(ActionEvent e) { DefaultMutableTreeNode newNode=null; DefaultTreeModel treeModel=(DefaultTreeModel) jtree.getModel(); DefaultMutableTreeNode node=selectNode(jtree); if(node==null) return ; DefaultMutableTreeNode parent=(DefaultMutableTreeNode) node.getParent(); if(node!=null) { if(nodeType.equals(ADD_SIBLING)) { if (parent==null) return; newNode= new DefaultMutableTreeNode("New Sibling"); treeModel.insertNodeInto(newNode, parent, parent.getChildCount()); } else if(nodeType.equals(ADD_CHILD)) { newNode= new DefaultMutableTreeNode("New Child"); treeModel.insertNodeInto(newNode, node, 0); } else if(nodeType.equals(DELETE)) { if (parent!= null){ ImageIcon icon=new ImageIcon(getClass().getResource("/jfcswing/images/delete.png")); int answer=JOptionPane.showConfirmDialog(cp, "Confirm to delete this node?", "Prompt", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, icon); if( answer==JOptionPane.YES_OPTION) treeModel.removeNodeFromParent(node); } } // now display new node TreeNode[] nodes = treeModel.getPathToRoot(newNode); if(nodes!=null){ TreePath path = new TreePath(nodes); jtree.scrollPathToVisible(path); } } } } private DefaultMutableTreeNode selectNode(JTree tree) { if(tree==null) return null; DefaultMutableTreeNode node=(DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); return node; } /** * 展开所有树结点 * @param tree * @param path */ private void expandAll(JTree tree, TreePath path) { tree.expandPath(path); TreeNode node = (TreeNode) path.getLastPathComponent(); for (Enumeration i = node.children(); i.hasMoreElements(); ) expandAll(tree, path.pathByAddingChild(i.nextElement())); } /** * 折叠所有树结点 * @param tree * @param path */ private void collapseAll(JTree tree, TreePath path) { //tree.collapseRow(0); tree.collapsePath(path); } private void showPopupMenu(MouseEvent me) { if (me.isPopupTrigger() && selectNode(jtree)!=null) getPopupMenu().show(jtree, me.getX(), me.getY()); } private JPopupMenu getPopupMenu() { popupMenu=new JPopupMenu(); popupMenu.add(getAddSiblingMenuItem()); popupMenu.add(getAddChildMenuItem()); popupMenu.add(getDeleteMenuItem()); return popupMenu; } private JMenuItem getAddSiblingMenuItem() { menuItemAddSibling=new JMenuItem("Add Sibling",'S'); menuItemAddSibling.setIcon(new ImageIcon(getClass().getResource("/jfcswing/images/batchadd.png"))); menuItemAddSibling.addActionListener(new AddNewNode(ADD_SIBLING)); return menuItemAddSibling; } private JMenuItem getAddChildMenuItem() { menuItemAddChild=new JMenuItem("Add Child",'C'); menuItemAddChild.addActionListener(new AddNewNode(ADD_CHILD)); menuItemAddChild.setIcon(new ImageIcon(getClass().getResource("/jfcswing/images/mobile.png"))); return menuItemAddChild; } private JMenuItem getDeleteMenuItem() { menuItemDelete=new JMenuItem("Delete",'D'); menuItemDelete.addActionListener(new AddNewNode(DELETE)); menuItemDelete.setIcon(new ImageIcon(getClass().getResource("/jfcswing/images/delete.png"))); if(selectNode(jtree)==null) menuItemDelete.setEnabled(false); return menuItemDelete; } public static void main(String[] args) { try { javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e1) { e1.printStackTrace(); } JTreeDemo2 jTreeDemo2 = new JTreeDemo2(); jTreeDemo2.setVisible(true); }}
[解决办法]
package com.java;import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.tree.*;public class EditJTree{ JFrame jf; JTree tree; //上面JTree对象对应的model DefaultTreeModel model; //定义几个初始节点 DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); //定义需要被拖动的TreePath TreePath movePath; JButton addSiblingButton = new JButton("添加兄弟节点"); JButton addChildButton = new JButton("添加子节点"); JButton deleteButton = new JButton("删除节点"); JButton editButton = new JButton("编辑当前节点"); public void init() { jf = new JFrame("树"); tree = new JTree(root); //获取JTree对应的TreeModel对象 model = (DefaultTreeModel)tree.getModel(); //设置JTree可编辑 tree.setEditable(true); MouseListener ml = new MouseAdapter() { //按下鼠标时候获得被拖动的节点 public void mousePressed(MouseEvent e) { //如果需要唯一确定某个节点,必须通过TreePath来获取。 TreePath tp = tree.getPathForLocation(e.getX(), e.getY()); if (tp != null) { movePath = tp; } TreeNode target=(TreeNode)movePath.getLastPathComponent(); ((TreeNodeObject) target).nodecount++; System.out.println(((TreeNodeObject) target).nodecount); } //鼠标松开时获得需要拖到哪个父节点 public void mouseReleased(MouseEvent e) { //根据鼠标松开时的TreePath来获取TreePath TreePath tp = tree.getPathForLocation(e.getX(), e.getY()); if (tp != null && movePath != null) { //阻止向子节点拖动 if (movePath.isDescendant(tp) && movePath != tp) { JOptionPane.showMessageDialog(jf, "目标节点是被移动节点的子节点,无法移动!", "非法操作", JOptionPane.ERROR_MESSAGE ); return; } //既不是向子节点移动,而且鼠标按下、松开的不是同一个节点 else if (movePath != tp) { System.out.println(tp.getLastPathComponent()); //add方法可以先将原节点从原父节点删除,再添加到新父节点中 ((DefaultMutableTreeNode)tp.getLastPathComponent()).add( (DefaultMutableTreeNode)movePath.getLastPathComponent()); movePath = null; tree.updateUI(); } } } }; tree.addMouseListener(ml); JPanel panel = new JPanel(); addSiblingButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //获取选中节点 DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //如果节点为空,直接返回 if (selectedNode == null) return; //获取该选中节点的父节点 DefaultMutableTreeNode parent = (DefaultMutableTreeNode)selectedNode.getParent(); //如果父节点为空,直接返回 if (parent == null) return; //创建一个新节点 DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(new TreeNodeObject( 0, "新节点",1)); //获取选中节点的选中索引 int selectedIndex = parent.getIndex(selectedNode); //在选中位置插入新节点 model.insertNodeInto(newNode, parent, selectedIndex + 1); //--------下面代码实现显示新节点(自动展开父节点)------- //获取从根节点到新节点的所有节点 TreeNode[] nodes = model.getPathToRoot(newNode); //使用指定的节点数组来创建TreePath TreePath path = new TreePath(nodes); //显示指定TreePath tree.scrollPathToVisible(path); } }); panel.add(addSiblingButton); addChildButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { //获取选中节点 DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //如果节点为空,直接返回 if (selectedNode == null) return; //创建一个新节点 DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("新节点"); //直接通过model来添加新节点,则无需通过调用JTree的updateUI方法 //model.insertNodeInto(newNode, selectedNode, selectedNode.getChildCount()); //直接通过节点添加新节点,则需要调用tree的updateUI方法 selectedNode.add(newNode); //--------下面代码实现显示新节点(自动展开父节点)------- TreeNode[] nodes = model.getPathToRoot(newNode); TreePath path = new TreePath(nodes); tree.scrollPathToVisible(path); tree.updateUI(); } }); panel.add(addChildButton); deleteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); if (selectedNode != null && selectedNode.getParent() != null) { //删除指定节点 model.removeNodeFromParent(selectedNode); } } }); panel.add(deleteButton); editButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { TreePath selectedPath = tree.getSelectionPath(); if (selectedPath != null) { //编辑选中节点 tree.startEditingAtPath(selectedPath); } } }); panel.add(editButton); jf.add(new JScrollPane(tree)); jf.add(panel , BorderLayout.SOUTH); jf.pack(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } public static void main(String[] args) { new EditJTree().init(); }}class TreeNodeObject { public int nodeId; public String nodeName; public static int nodecount; public TreeNodeObject(int id, String name,int count) { this.nodeId = id; this.nodeName = name; this.nodecount=count; } public void getNodecount() { // TODO Auto-generated method stub } public String toString() { return this.nodeName; } public int getNodeId() { return nodeId; } public void setNodeId(int nodeId) { this.nodeId = nodeId; } public String getNodeName() { return nodeName; } public void setNodeName(String nodeName) { this.nodeName = nodeName; } }
[解决办法]