Vous êtes sur la page 1sur 19

JTREE

JTree adalah komponen Swing yang menampilkan data dalam


hierarki yang mirip pohon.

Root
Leaf
TREE MODELS
Saat JTree menampilkan pohon, representasi data dari pohon ditangani
oleh TreeModel, TreeNode, dan TreePath. TreeModel mewakili seluruh
pohon, TreeNode merepresentasikan sebuah node, dan TreePath
merepresentasikan path ke node. Berbeda dengan ListModel atau
TableModel, model pohon tidak secara langsung menyimpan atau
mengelola data pohon. Data pohon disimpan dan dikelola di TreeNode dan
TreePath.
TreeNode
javax.swing.JTree

-model: TreeModel TreeModel DefaultTreeModel MutableTreeNode


-anchorPath: TreePath TreePath
DefaultMutableTreeNode
-leadPath: TreePath

-selectionModel: TreeSelectionModel TreeSelectionModel DefaultTreeSelectionModel

-cellEditor: TreeCellEditor TreeCellRenderer DefaultTreeCellRenderer


-cellRenderer: TreeCellEditor TreeCellEditor DefaultTreeCellEditor
DefaultTreeCellEditor
dapat digunakan untuk
Antarmuka Kelas DefaultTreeCellRenderer mengedit sel di bidang
TreeSelectionModel menyediakan perender simpul teks.
menangani pemilihan simpul pohon default yang dapat
pohon. menampilkan label dan / atau ikon
javax.swing.JTree
#cellEditor: TreeCellEditor Specifies a cell editor used to edit entries in the tree.

JTREE #cellRenderer: TreeCellRenderer


#editable: boolean
Specifies whether individual cells can be selected (Obsolete since JDK 1.3).
Specifies whether the cells are editable (default: false).
Maintains the tree model.

CLASS
#model: TreeModel
#rootVisible: boolean Specifies whether the root is displayed (depending on the constructor).
#rowHeight: int Specifies the height of the row for the node displayed in the tree
(default: 16 pixels).
#scrollsOnExpand: boolean If true, when a node is expanded, as many of the descendants are
scrolled to be visible (default: 16 pixels).
#selectionModel: TreeSelectionModel Models the set of selected nodes in this tree.
#showsRootHandles: boolean Specifies whether the root handles are displayed (default: true).
#toggleClickCount: int Number of mouse clicks before a node is expanded (default: 2).
-anchorSelectionPath: TreePath The path identified as the anchor.
-expandsSelectedPaths: boolean True if paths in the selection should be expanded (default: true).
-leadSelectionPaths: TreePath The path identified as the lead.
+JTree() Creates a JTree with a sample tree model, as shown in Figure 24.35.
+JTree(value: java.util.Hashtable) Creates a JTree with an invisible root and the keys in the Hashtable
key/value pairs as its children.
+JTree(value: Object[]) Creates a JTree with an invisible root and the elements in the array as
its children.
+JTree(newModel: TreeModel) Creates a JTree with the specified tree model.
+JTree(root: TreeNode) Creates a JTree with the specified tree node as its root.
+JTree(root: TreeNode, asksAllowsChildren: Creates a JTree with the specified tree node as its root and decides
boolean) whether a node is a leaf node in the specified manner.
+JTree(value: Vector) Creates a JTree with an invisible root and the elements in the vector as
its children.
+addSelectionPath(path: TreePath): void Adds the specified TreePath to the current selection.
+addSelectionPaths(paths: TreePath[]): void Adds the specified TreePaths to the current selection.
+addSelectionRow(row: int): void Adds the path at the specified row to the current selection.
+addSelectionRows(rows: int[]): void Adds the path at the specified rows to the current selection.
+clearSelection() : void Clears the selection.
+collapsePath(path: TreePath): void Ensures that the node identified by the specified path is collapsed and
viewable.
+getSelectionPath(): TreePath Returns the path from the root to the first selected node.
+getSelectionPaths(): TreePath[] Returns the paths from the root to all the selected nodes.
+getLastSelectedPathComponent() Returns the last node in the first selected TreePath.
+getRowCount():int Returns the number of rows currently being displayed.
+removeSelectionPath(path: TreePath): void Removes the node in the specified path.
+removeSelectionPaths(paths: TreePath[]):void Removes the node in the specified paths.
CONTOH : SIMPLE TREE
Permasalahan : Tulis program untuk membuat empat pohon:
pohon default menggunakan konstruktor no-arg, pohon yang
dibuat dari larik objek, pohon yang dibuat dari vektor, dan pohon
yang dibuat dari tabel hash. Memungkinkan pengguna untuk
secara dinamis mengatur properti untuk rootVisible, rowHeight,
dan showsRootHandles.
TREEMODEL DAN DEFAULTTREEMODEL
TreeModel berisi
informasi struktural
tentang tree, dan javax.swing.tree.TreeModel
+getChild(parent: Object, index: int): Object Returns the child of parent at the index in the parent's child array.
data tree disimpan +getChildCount(parent: Object): int Returns the number of children of the specified parent in the tree model.

dan dikelola oleh +getIndexOfChild(parent: Object, child: Object): int


+getRoot(): Object
Returns the index of child in parent. If parent or child is null, returns –1.
Returns the root of the tree. Returns null if the tree is empty.
TreeNode. +isLeaf(node: Object): boolean Returns true if the specified node is a leaf.
+addTreeModelListener(listener: Adds a listener for the TreeModelEvent posted after the tree changes.
TreeModelListener): void
+removeTreeModelListener(listener: Removes a listener previously added with addTreeModelListener.
TreeModelListener): void
DefaultTreeModel +valueForPathChanged(path: TreePath, newValue:
Object): void
Messaged when the user has altered the value for the item identified by
path to newValue.
adalah implementasi
nyata untuk javax.swing.tree.DefaultTreeModel

TreeModel yang #asksAllowsChildren: Boolean Tells how leaf nodes are determined. True if only nodes that do not allow
children are leaf nodes, false if nodes that have no children are leaf nodes.

menggunakan #root: TreeNode The root of the tree.

TreeNodes. +DefaultTreeModel(root: TreeNode) Creates a DefaultTreeModel with the specified root.


+DefaultTreeModel(root: TreeNode, Creates a DefaultTreeModel with the specified root and decides whether a
asksAllowsChildren: boolean) node is a leaf node in the specified manner.
+asksAllowsChildren(): boolean Returns asksAllowsChildren.
+getPathToRoot(aNode: TreeNode): TreeNode[] Returns the nodes in an array from root to the specified node.
+insertNodeInto(newChild: MutableTreeNode, Inserts newChild at location index in parents children.
parent: MutableTreeNode, index: int): void
+reload(): void Reloads the model (invoke this method if the tree has been modified)
+removeNodeFromParent(node: MutableTreeNode): Removes the node from its parent.
void
javax.swing.tree.TreeNode
+children(): java.util.Enumeration Returns the children of this node.
+getAllowsChildren(): boolean Returns true if this node can have children.
TREENODE, +getChildAt(childIndex: int): TreeNode Returns the child TreeNode at index childIndex.
Returns the number of children under this node.
+getChildCount(): int
MUTABLETREENODE, AND +getIndex(node: TreeNode): int Returns the index of the specified node in the current node’s children.
Returns the parent of this node.
DEFAULTMUTABLETREENODE
+getParent(): TreeNode
+isLeaf():boolean Returns true if this node is a leaf.

javax.swing.tree.MutableTreeNode

TreeNode menyimpan +insert(child: MutableTreeNode, index: int): void


+remove(index: int): void
Adds the specified child under this node at the specified index.
Removes the child at the specified index from this node’s child list.

sebuah single node di dalam +remove(node: MutableTreeNode): void


+removeFromParent(): void
Removes the specified node from this node’s child list.
Removes this node from its parent.
tree +setParent(newParent: MutableTreeNode): void Sets the parent of this node to the specified newParent.
MutableTreeNode mendefinisikan +setUserObject(object: Object): void Resets the user object of this node to the specified object.

subinterface TreeNode dengan javax.swing.tree.DefaultMutableTreeNode

metode tambahan untuk #allowsChildren: Boolean


#parent: MutableTreeNode
True if the node is able to have children.
Stores the parent of this node.

mengubah konten dari node, #userObject: Object


+DefaultMutableTreeNode()
Stores the content of this node.
Creates a tree node without user object, and allows children.
untuk memasukkan dan +DefaultMutableTreeNode(userObject: Object)
+DefaultMutableTreeNode(userObject: Object,
Creates a tree node with the specified user object, and allows children.
Creates a tree node with the specified user object and the specified mode to
menghapus simpul anak, untuk allowsChildren: boolean)
+add(MutableTreeNode newChild)
indicate whether children are allowed.
Adds the specified node to the end of this node's child vector.

menetapkan induk baru, dan +getChildAfter(aChild: TreeNode): TreeNode


+getChildBefore(aChild: TreeNode): TreeNode
Returns the next (previous) sibling of the specified child in this node's child
vector.

untuk menghapus node itu sendiri +getFirstChild(): TreeNode


+getLastChild(): TreeNode
These two methods return this node's first (last) child in the child’s vector of
this node.
+getFirstLeaf(): DefaultMutableTreeNode These four methods return the first (last, next, and previous) leaf that is a
DefaultMutableTreeNode adalah +getLastLeaf(): DefaultMutableTreeNode
+getNextLeaf(): DefaultMutableTreeNode
descendant of this node. The first (last, next, and previous) leaf is
recursively defined as the first (last, next, and previous) child’s first (last,

implementasi nyata dari


+getPreviousLeaf(): DefaultMutableTreeNode next, and previous) leaf.
+getLeafCount(): int Returns the total number of leaves that are descendants of this node.

MutableTreeNode
+getDepth(): int Returns the depth of the tree rooted at this node.
+getLevel(): int Returns the distance from the root to this node.
+getNextNode(): DefaultMutableTreeNode Returns the node that follows (precedes) this node in a preorder traversal of
+getPreviousNode(): DefaultMutableTreeNode this node.
+getSiblingCount(): int Returns the number of siblings of this node.
+getNextSibling(): DefaultMutableTreeNode Returns the next sibling of this node in the parent's child vector.
+getPath(): TreeNode[] Returns the path from the root to this node.
+getRoot(): TreeNode Returns the root of the tree that contains this node.
+isRoot(): boolean Returns true if this node is the root of the tree.
+breadthFirstEnumeration(): Enumeration Creates and returns an enumeration that traverses the subtree rooted at this
+depthFirstEnumeration(): Enumeration node in breadth-first order (depth-first order, postorder, preorder). These
+postorderEnumeration(): Enumeration traversals were discussed in Chapter 17, “Data Structure
+preorderEnumeration(): Enumeration Implementations.”
CONTOH : TREE MODEL DEMO
Masalah: Menulis program untuk membuat dua tree yang
menampilkan “World”, benua, negara dan negara bagian.
Kedua tree menampilkan konten yang identik. Program ini
juga menampilkan properti dari pohon di area teks.
TREESELECTIONMODEL DAN
DEFAULTTREESELECTIONMODEL
Pemilihan node Tree
didefinisikan dalam
antarmuka javax.swing.tree.TreeSelectionModel
TreeSelectionModel. +addSelectionPath(path: TreePath): void Adds the specified TreePath to the current selection.
+addSelectionPaths(paths: TreePath[]): void Adds the specified TreePaths to the current selection.
+clearSelection() : void Clears the selection.
+getLeadSelectionPath(): TreePath Returns the last path in the selection.
+getSelectionCount(): int Returns the number of paths in the selection.
+getSelectionPath(): TreePath Returns the first path in the selection.
Class +getSelectionPaths(): TreePath[] Returns all the paths in the selection.
DefaultTreeSelection +getSelectionMode(): int Returns the current selection mode,

Model adalah +removeSelectionPath(path: TreePath): void Removes path from the selection.
+removeSelectionPaths(paths: TreePath[]):void Removes paths from the selection.
implementasi nyata +setSelectionMode(mode: int): void Sets the selection mode.
dari +setSelectionPath(path: TreePath): void Sets the selection to path.
TreeSelectionModel, +setSelectionPaths(paths: TreePath[]): void Sets the selection to paths.
+addTreeSelectionListener(x: TreeSelectionListener): void Register a TreeSelectionListener.
yang +removeTreeSelectionListener(x: TreeSelectionListener): void Remove a TreeSelectionListener.
mempertahankan
array objek TreePath javax.swing.tree.DefaultTreeSelectionModel
yang mewakili pilihan
CONTOH : MODIFIYING TREES
Masalah: Menulis program untuk membuat dua pohon yang menampilkan
konten yang sama: dunia, benua, negara dan negara bagian, seperti yang
ditunjukkan pada Gambar dibawah. Untuk tree di sebelah kiri, aktifkan
pengguna untuk memilih mode pilihan, tambahkan anak baru di bawah simpul
yang dipilih pertama, dan hapus semua simpul yang dipilih.
TREE NODE RENDERING
DefaultTreeCellRenderer renderer =
(DefaultTreeCellRenderer)jTree1.getCellRenderer();
renderer.setLeafIcon(yourCustomLeafImageIcon);
renderer.setOpenIcon(yourCustomOpenImageIcon);

renderer.setClosedIcon(yourCustomClosedImageIcon);
renderer.setBackgroundSelectionColor(Color.red);
TREE EDITING
// Customize editor
JComboBox jcboColor = new JComboBox();
jcboColor.addItem("red");
jcboColor.addItem("green");
jcboColor.addItem("blue");
jcboColor.addItem("yellow");
jcboColor.addItem("orange");

jTree1.setCellEditor(new DefaultCellEditor(jcboColor));
jTree1.setEditable(true);
TREE RENDERING AND EDITING
jTree1.setCellEditor
(new DefaultTreeCellEditor(jTree1,
new DefaultTreeCellRenderer(),
new DefaultCellEditor(jcboColor)));
JTree dapat mengaktifkan TreeSelectionEvent dan
TreeExpansionEvent, di antara banyak acara lainnya. Setiap kali
simpul baru dipilih, JTree mengaktifkan TreeSelectionEvent.
Setiap kali node diperluas atau diciutkan, JTree mengaktifkan
TreeExpansionEvent. Untuk menangani peristiwa pemilihan
pohon, pendengar harus mengimplementasikan antarmuka
TreeSelectionListener, yang berisi metode valueChanged handler
tunggal. TreeExpansionListener berisi dua penangan bernama
treeCollapsed dan treeExpanded untuk menangani node
expansion atau node closing.
ARRAY + JTABLE
&
DATABASE
JTABLE
 Tabel digunakan untuk menampilkan data dalam mode
spreadsheet
 Jadi konsep-konsep kunci dalam model tabel:
 cell, baris, kolom
 Nilai (s) di masing-masing
 Setiap tabel mendapatkan datanya dari sebuah objek
yang mengimplementasikan TableModel Interface
 Dapat digunakan class DefaultTableModel, atau
 Membuat class baru dimana mengimplementasikan
AbstractTableModel Interface dan mengimplemntasikan
metode berikut
 getColumnName
import
 getRowCount java.swingx.table.*;
 getColumnCount
 getValueAt
JAVA
MENGGUNAKAN DEFAULTTABLEMODEL

Object[][] data = { {"Mary", "Campione","Snowboarding", new Integer(5) ...}


{"Alison", "Huml","Rowing", new Integer(3), new Boolean(true)} ...};

String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};

DefaultTableModel defaultTableModel = new DefaultTableModel(data, columnNames);

...

table = new JTable(defaultTableModel);


JAVA
MENGGUNAKAN ABSTRACTTABLEMODEL
 Langkah-langkah dalam membuat dan menggunakan AbstractTableModel
 Membuat sebuah AbstractTableModel

 Mengimplementasikan method getRowCount(), ,getColumnCount() , and


getValueAt()

JTable table = new JTable(new AbstractTableModel() {


public int getColumnCount() { return 10; }
public int getRowCount() { return 5;}
extends
AbstractTableModel
public Object getValueAt(int row, int col) {
return new Integer((row+1)*(col+1));
}
});

getContentPane().add(table, BorderLayout.CENTER);
LATIHAN

Vous aimerez peut-être aussi