樹這東西給用戶的感覺極為方便,但給程序員帶來很大的麻煩,它是swing中最麻煩的控件之一。樹要弄的好非常麻煩,圖標的美化,層次的劃分,各種事件的處理。。。對於初學者來說,就不要太講究樣式,下面舉個粗糙的例子,eg
- public class SimpleJTree
- {
- JFrame jf = new JFrame("簡單樹");
- JTree tree;
- //定義幾個初始節點
- DefaultMutableTreeNode root = new DefaultMutableTreeNode("中國");
- DefaultMutableTreeNode guangdong = new DefaultMutableTreeNode("廣東");
- DefaultMutableTreeNode guangxi = new DefaultMutableTreeNode("廣西");
- DefaultMutableTreeNode foshan = new DefaultMutableTreeNode("佛山");
- DefaultMutableTreeNode shantou = new DefaultMutableTreeNode("汕頭");
- DefaultMutableTreeNode guilin = new DefaultMutableTreeNode("桂林");
- DefaultMutableTreeNode nanning = new DefaultMutableTreeNode("南寧");
- public void init()
- {
- //通過add方法建立樹節點之間的父子關系
- guangdong.add(foshan);
- guangdong.add(shantou);
- guangxi.add(guilin);
- guangxi.add(nanning);
- root.add(guangdong);
- root.add(guangxi);
- //以根節點創建樹
- tree = new JTree(root);
- //默認連線
- //tree.putClIEntProperty("JTree.lineStyle" , "Angeled");
- //沒有連線
- tree.putClIEntProperty("JTree.lineStyle" , "None");
- //水平分隔線
- //tree.putClIEntProperty("JTree.lineStyle" , "Horizontal");
- //設置是否顯示根節點的“展開/折疊”圖標,默認是false
- tree.setShowsRootHandles(true);
- //設置節點是否可見,默認是true
- tree.setRootVisible(true);
- jf.add(new JScrollPane(tree));
- jf.pack();
- jf.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- jf.setVisible(true);
- }
- public static void main(String[] args)
- {
- new SimpleJTree().init();
- }
- }
拖動,編輯樹節點也是樹的基本功能,下面就在上面例子的基礎上,加上這些功能,eg
- public class EditJTree
- {
- JFrame jf;
- JTree tree;
- //上面JTree對象對應的model
- DefaultTreeModel model;
- //定義幾個初始節點
- DefaultMutableTreeNode root = new DefaultMutableTreeNode("中國");
- DefaultMutableTreeNode guangdong = new DefaultMutableTreeNode("廣東");
- DefaultMutableTreeNode guangxi = new DefaultMutableTreeNode("廣西");
- DefaultMutableTreeNode foshan = new DefaultMutableTreeNode("佛山");
- DefaultMutableTreeNode shantou = new DefaultMutableTreeNode("汕頭");
- DefaultMutableTreeNode guilin = new DefaultMutableTreeNode("桂林");
- DefaultMutableTreeNode nanning = new DefaultMutableTreeNode("南寧");
- //定義需要被拖動的TreePath
- TreePath movePath;
- JButton addSiblingButton = new JButton("添加兄弟節點");
- JButton addChildButton = new JButton("添加子節點");
- JButton deleteButton = new JButton("刪除節點");
- JButton editButton = new JButton("編輯當前節點");
- public void init()
- {
- guangdong.add(foshan);
- guangdong.add(shantou);
- guangxi.add(guilin);
- guangxi.add(nanning);
- root.add(guangdong);
- root.add(guangxi);
- 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;
- }
- }
- //鼠標松開時獲得需要拖到哪個父節點
- 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("新節點");
- //獲取選中節點的選中索引
- 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();
- }
- }
最後講下如何修飾tree的圖標,主要是通過拓展TreeCellRenderer來實現,eg
- public class ExtendsDefaultTreeCellRenderer
- {
- JFrame jf = new JFrame("根據節點類型定義圖標");
- JTree tree;
- //定義幾個初始節點
- DefaultMutableTreeNode root = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.ROOT , "數據庫導航"));
- DefaultMutableTreeNode salaryDb = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.DATABASE , "公司工資數據庫"));
- DefaultMutableTreeNode customerDb = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.DATABASE , "公司客戶數據庫"));
- //定義salaryDb的兩個子節點
- DefaultMutableTreeNode employee = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.TABLE , "員工表"));
- DefaultMutableTreeNode attend = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.TABLE , "考勤表"));
- //定義customerDb的一個子節點
- DefaultMutableTreeNode contact = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.TABLE , "聯系方式表"));
- //定義employee的三個子節點
- DefaultMutableTreeNode id = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.INDEX , "員工ID"));
- DefaultMutableTreeNode name = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.COLUMN , "姓名"));
- DefaultMutableTreeNode gender = new DefaultMutableTreeNode(
- new NodeData(DBObjectType.COLUMN , "性別"));
- public void init()throws Exception
- {
- //通過add方法建立樹節點之間的父子關系
- root.add(salaryDb);
- root.add(customerDb);
- salaryDb.add(employee);
- salaryDb.add(attend);
- customerDb.add(contact);
- employee.add(id);
- employee.add(name);
- employee.add(gender);
- //以根節點創建樹
- tree = new JTree(root);
- //設置該JTree使用自定義的節點繪制器
- tree.setCellRenderer(new MyRenderer());
- //設置是否顯示根節點的“展開/折疊”圖標,默認是false
- tree.setShowsRootHandles(true);
- //設置節點是否可見,默認是true
- tree.setRootVisible(true);
- //設置使用Windows風格外觀
- UIManager.setLookAndFeel("com.sun.Java.swing.plaf.windows.WindowsLookAndFeel");
- //更新JTree的UI外觀
- SwingUtilitIEs.updateComponentTreeUI(tree);
- jf.add(new JScrollPane(tree));
- jf.pack();
- jf.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
- jf.setVisible(true);
- }
- public static void main(String[] args) throws Exception
- {
- new ExtendsDefaultTreeCellRenderer().init();
- }
- }
- //定義一個NodeData類,用於封裝節點數據
- class NodeData
- {
- public int nodeType;
- public String nodeData;
- public NodeData(int nodeType , String nodeData)
- {
- this.nodeType = nodeType;
- this.nodeData = nodeData;
- }
- public String toString()
- {
- return nodeData;
- }
- }
- //定義一個接口,該接口裡包含數據庫對象類型的常量
- interface DBObjectType
- {
- int ROOT = 0;
- int DATABASE = 1;
- int TABLE = 2;
- int COLUMN = 3;
- int INDEX = 4;
- }
- class MyRenderer extends DefaultTreeCellRenderer
- {
- //初始化5個圖標
- ImageIcon rootIcon = new ImageIcon("icon/root.gif");
- ImageIcon databaseIcon = new ImageIcon("icon/database.gif");
- ImageIcon tableIcon = new ImageIcon("icon/table.gif");
- ImageIcon columnIcon = new ImageIcon("icon/column.gif");
- ImageIcon indexIcon = new ImageIcon("icon/index.gif");
- public Component getTreeCellRendererComponent(JTree tree, Object value,
- boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
- {
- //執行父類默認的節點繪制操作
- super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
- DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
- NodeData data = (NodeData)node.getUserObject();
- //根據數據節點裡的nodeType數據決定節點圖標
- ImageIcon icon = null;
- switch(data.nodeType)
- {
- case DBObjectType.ROOT:
- icon = rootIcon;
- break;
- case DBObjectType.DATABASE:
- icon = databaseIcon;
- break;
- case DBObjectType.TABLE:
- icon = tableIcon;
- break;
- case DBObjectType.COLUMN:
- icon = columnIcon;
- break;
- case DBObjectType.INDEX:
- icon = indexIcon;
- break;
- }
- //改變圖標
- this.setIcon(icon);
- return this;
- }
- }
圖標大家就自己搞幾個吧,不搞也可以看到效果。明天我將講下JTable,也是個麻煩的控件。