熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java Swing編程:JTree樹

2013-11-23 18:48:46  來源: Java核心技術 

  樹這東西給用戶的感覺極為方便但給程序員帶來很大的麻煩它是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方法建立樹節點之間的父子關系

          guangdongadd(foshan)

          guangdongadd(shantou)

          guangxiadd(guilin)

          guangxiadd(nanning)

          rootadd(guangdong)

          rootadd(guangxi)

          //以根節點創建樹

          tree = new JTree(root)

  

          //默認連線

          //treeputClientProperty(JTreelineStyle Angeled

          //沒有連線

          treeputClientProperty(JTreelineStyle None

          //水平分隔線

          //treeputClientProperty(JTreelineStyle Horizontal

  

  

          //設置是否顯示根節點的展開/折疊圖標默認是false

          treesetShowsRootHandles(true)

          //設置節點是否可見默認是true

          treesetRootVisible(true)

  

          jfadd(new JScrollPane(tree))

          jfpack()

          jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE)

          jfsetVisible(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()

      {

          guangdongadd(foshan)

          guangdongadd(shantou)

          guangxiadd(guilin)

          guangxiadd(nanning)

          rootadd(guangdong)

          rootadd(guangxi)

  

          jf = new JFrame(

          tree = new JTree(root)

          //獲取JTree對應的TreeModel對象

          model = (DefaultTreeModel)treegetModel()

          //設置JTree可編輯

          treesetEditable(true)

          MouseListener ml = new MouseAdapter()

          {

              //按下鼠標時候獲得被拖動的節點

              public void mousePressed(MouseEvent e)

              {

                  //如果需要唯一確定某個節點必須通過TreePath來獲取

                  TreePath tp = treegetPathForLocation(egetX() egetY())

                  if (tp != null)

                  {

                      movePath = tp;

                  }

              }

              //鼠標松開時獲得需要拖到哪個父節點

              public void mouseReleased(MouseEvent e)

              {

                  //根據鼠標松開時的TreePath來獲取TreePath

                  TreePath tp = treegetPathForLocation(egetX() egetY())

  

                  if (tp != null && movePath != null)

                  {

                      //阻止向子節點拖動

                      if (movePathisDescendant(tp) && movePath != tp)

                      {

                          JOptionPaneshowMessageDialog(jf 目標節點是被移動節點的子節點無法移動!

                              非法操作 JOptionPaneERROR_MESSAGE )

                          return;

                      }

                      //既不是向子節點移動而且鼠標按下松開的不是同一個節點

                      else if (movePath != tp)

                      {

                          Systemoutprintln(tpgetLastPathComponent())

                          //add方法可以先將原節點從原父節點刪除再添加到新父節點中

                          ((DefaultMutableTreeNode)tpgetLastPathComponent())add(

                              (DefaultMutableTreeNode)movePathgetLastPathComponent())

                          movePath = null;

                          treeupdateUI()

                      }

                  }

              }

          };

          treeaddMouseListener(ml)

  

          JPanel panel = new JPanel()

  

          addSiblingButtonaddActionListener(new ActionListener()

          {

              public void actionPerformed(ActionEvent event)

              {

                  //獲取選中節點

                  DefaultMutableTreeNode selectedNode

                      = (DefaultMutableTreeNode) treegetLastSelectedPathComponent()

                  //如果節點為空直接返回

                  if (selectedNode == null) return;

                  //獲取該選中節點的父節點

                  DefaultMutableTreeNode parent

                      = (DefaultMutableTreeNode)selectedNodegetParent()

                  //如果父節點為空直接返回

                  if (parent == null) return;

                  //創建一個新節點

                  DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(新節點

                  //獲取選中節點的選中索引

                  int selectedIndex = parentgetIndex(selectedNode)

                  //在選中位置插入新節點

                  modelinsertNodeInto(newNode parent selectedIndex +

                  //下面代碼實現顯示新節點(自動展開父節點)

                  //獲取從根節點到新節點的所有節點

                  TreeNode[] nodes = modelgetPathToRoot(newNode)

                  //使用指定的節點數組來創建TreePath

                  TreePath path = new TreePath(nodes)

                  //顯示指定TreePath

                  treescrollPathToVisible(path)

              }

          })

          paneladd(addSiblingButton)

  

          addChildButtonaddActionListener(new ActionListener()

          {

              public void actionPerformed(ActionEvent event)

              {

                  //獲取選中節點

                  DefaultMutableTreeNode selectedNode

                      = (DefaultMutableTreeNode) treegetLastSelectedPathComponent()

                  //如果節點為空直接返回

                  if (selectedNode == null) return;

                  //創建一個新節點

                  DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(新節點

                  //直接通過model來添加新節點則無需通過調用JTree的updateUI方法

                  //modelinsertNodeInto(newNode selectedNode selectedNodegetChildCount())

                  //直接通過節點添加新節點則需要調用tree的updateUI方法

                  selectedNodeadd(newNode)

                  //下面代碼實現顯示新節點(自動展開父節點)

                  TreeNode[] nodes = modelgetPathToRoot(newNode)

                  TreePath path = new TreePath(nodes)

                  treescrollPathToVisible(path)

                  treeupdateUI()

              }

          })

          paneladd(addChildButton)

  

          deleteButtonaddActionListener(new ActionListener()

          {

              public void actionPerformed(ActionEvent event)

              {

                  DefaultMutableTreeNode selectedNode

                      = (DefaultMutableTreeNode) treegetLastSelectedPathComponent()

                  if (selectedNode != null && selectedNodegetParent() != null)

                  {

                      //刪除指定節點

                      modelremoveNodeFromParent(selectedNode)

                  }

              }

          })

          paneladd(deleteButton)

  

          editButtonaddActionListener(new ActionListener()

          {

              public void actionPerformed(ActionEvent event)

              {

                  TreePath selectedPath = treegetSelectionPath()

                  if (selectedPath != null)

                  {

                      //編輯選中節點

                      treestartEditingAtPath(selectedPath)

                  }

              }

          })

          paneladd(editButton)

  

          jfadd(new JScrollPane(tree))

          jfadd(panel BorderLayoutSOUTH)

          jfpack()

          jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE)

          jfsetVisible(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(DBObjectTypeROOT 數據庫導航))

      DefaultMutableTreeNode salaryDb = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeDATABASE 公司工資數據庫))

      DefaultMutableTreeNode customerDb = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeDATABASE 公司客戶數據庫))

      //定義salaryDb的兩個子節點

      DefaultMutableTreeNode employee = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeTABLE 員工表))

      DefaultMutableTreeNode attend = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeTABLE 考勤表))

      //定義customerDb的一個子節點

      DefaultMutableTreeNode contact = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeTABLE 聯系方式表))

  

      //定義employee的三個子節點

      DefaultMutableTreeNode id = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeINDEX 員工ID))

      DefaultMutableTreeNode name = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeCOLUMN 姓名))

      DefaultMutableTreeNode gender = new DefaultMutableTreeNode(

          new NodeData(DBObjectTypeCOLUMN 性別))

  

      public void init()throws Exception

      {

          //通過add方法建立樹節點之間的父子關系

          rootadd(salaryDb)

          rootadd(customerDb)

          salaryDbadd(employee)

          salaryDbadd(attend)

          customerDbadd(contact)

          employeeadd(id)

          employeeadd(name)

          employeeadd(gender)

          //以根節點創建樹

          tree = new JTree(root)

  

          //設置該JTree使用自定義的節點繪制器

          treesetCellRenderer(new MyRenderer())

  

          //設置是否顯示根節點的展開/折疊圖標默認是false

          treesetShowsRootHandles(true)

          //設置節點是否可見默認是true

          treesetRootVisible(true)

  

          //設置使用Windows風格外觀

          UIManagersetLookAndFeel(comsunjavaswingplafwindowsWindowsLookAndFeel

          //更新JTree的UI外觀

          SwingUtilitiesupdateComponentTreeUI(tree)

  

          jfadd(new JScrollPane(tree))

          jfpack()

          jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE)

          jfsetVisible(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)

      {

          thisnodeType = nodeType;

          thisnodeData = nodeData;

      }

      public String toString()

      {

          return nodeData;

      }

  }

  //定義一個接口該接口裡包含數據庫對象類型的常量

  interface DBObjectType

  {

      int ROOT = ;

      int DATABASE = ;

      int TABLE = ;

      int COLUMN = ;

      int INDEX = ;

  }

  class MyRenderer extends DefaultTreeCellRenderer

  {

      //初始化個圖標

      ImageIcon rootIcon = new ImageIcon(icon/rootgif

      ImageIcon databaseIcon = new ImageIcon(icon/databasegif

      ImageIcon tableIcon = new ImageIcon(icon/tablegif

      ImageIcon columnIcon = new ImageIcon(icon/columngif

      ImageIcon indexIcon = new ImageIcon(icon/indexgif

  

      public Component getTreeCellRendererComponent(JTree tree Object value

          boolean sel boolean expanded  boolean leaf int row boolean hasFocus)

      {

          //執行父類默認的節點繪制操作

          supergetTreeCellRendererComponent(tree value sel expanded leaf row hasFocus)

  

          DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;

          NodeData data = (NodeData)nodegetUserObject()

          //根據數據節點裡的nodeType數據決定節點圖標

          ImageIcon icon = null;

          switch(datanodeType)

          {

              case DBObjectTypeROOT:

                  icon = rootIcon;

                  break;

              case DBObjectTypeDATABASE:

                  icon = databaseIcon;

                  break;

              case DBObjectTypeTABLE:

                  icon = tableIcon;

                  break;

              case DBObjectTypeCOLUMN:

                  icon = columnIcon;

                  break;

              case DBObjectTypeINDEX:

                  icon = indexIcon;

                  break;

          }

          //改變圖標

          thissetIcon(icon)

          return this;

      }

  }


From:http://tw.wingwit.com/Article/program/Java/hx/201311/25782.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.