public class Tree
ImplementsAnimation, Editable, Iterable<Component>, StyleListener
Known subtypesFileTree
The Tree component allows constructing simple tree component hierarchies that can be expanded
seamlessly with no limit. The tree is bound to a model that can provide data with free form depth such as file system
or similarly structured data.
To customize the look of the tree the component can be derived and component creation can be replaced.
class StringArrayTreeModel implements TreeModel {
String[][] arr = new String[][] {
{"Colors", "Letters", "Numbers"},
{"Red", "Green", "Blue"},
{"A", "B", "C"},
{"1", "2", "3"}
};
public Vector getChildren(Object parent) {
if(parent == null) {
Vector v = new Vector();
for(int iter = 0 ; iter iter + 1 && arr[iter + 1] != null) {
for(int i = 0 ; i
And heres a more "real world" example showing an XML hierarchy in a `Tree`:
```java
class XMLTreeModel implements TreeModel {
private Element root;
public XMLTreeModel(Element e) {
root = e;
}
public Vector getChildren(Object parent) {
if(parent == null) {
Vector c = new Vector();
c.addElement(root);
return c;
}
Vector result = new Vector();
Element e = (Element)parent;
for(int iter = 0 ; iter
Another real world example showing the `com.codename1.io.FileSystemStorage` as a tree:
```java
Form hi = new Form("FileSystemTree", new BorderLayout());
TreeModel tm = new TreeModel() {
@Override
public Vector getChildren(Object parent) {
String[] files;
if(parent == null) {
files = FileSystemStorage.getInstance().getRoots();
return new Vector(Arrays.asList(files));
} else {
try {
files = FileSystemStorage.getInstance().listFiles((String)parent);
} catch(IOException err) {
Log.e(err);
files = new String[0];
}
}
String p = (String)parent;
Vector result = new Vector();
for(String s : files) {
result.add(p + s);
}
return result;
}
@Override
public boolean isLeaf(Object node) {
return !FileSystemStorage.getInstance().isDirectory((String)node);
}
};
Tree t = new Tree(tm) {
@Override
protected String childToDisplayLabel(Object child) {
String n = (String)child;
int pos = n.lastIndexOf("/");
if(pos
@author Shai Almog
Nested types
interface Tree.TreeState | A marker interface used for Tree state returned from #getTreeState() and passed to #setTreeState(com.codename1.ui.tree.Tree.TreeState) for retaining state in a Tree when the model is changed. |
Constructors
public Tree() | Constructor for usage by GUI builder and automated tools, normally one should use the version that accepts the model |
public Tree(TreeModel model) | Construct a tree with the given tree model |
Methods
public static void setFolderIcon(Image folderIcon) | Sets the icon for a tree folder |
public static void setFolderOpenIcon(Image folderIcon) | Sets the icon for a tree folder in its expanded state |
public static void setNodeIcon(Image nodeIcon) | Sets the icon for a tree node |
public Tree.TreeState getTreeState() | Gets the state of the tree in a format that can be restored later by either the same tree or a different tree whose model includes the same nodes. |
public void setTreeState(Tree.TreeState state) | Sets the tree state. |
public boolean isMultilineMode() | Toggles a mode where rows in the tree can be broken since span buttons will be used instead of plain buttons. |
public void setMultilineMode(boolean multilineMode) | Toggles a mode where rows in the tree can be broken since span buttons will be used instead of plain buttons. |
public String[] getPropertyNames() | A component may expose mutable property names for a UI designer to manipulate, this API is designed for usage internally by the GUI builder code |
public Class[] getPropertyTypes() | Matches the property names method (see that method for further details). |
public String[] getPropertyTypeNames() | This method is here to workaround an XMLVM array type bug where property types aren’t identified properly, it returns the names of the types using the following type names: String,int,double,long,byte,short,char,String[],String[][],byte[],I… |
public Object getPropertyValue(String name) | Returns the current value of the property name, this method is used by the GUI builder |
public String setPropertyValue(String name, Object value) | Sets a new value to the given property, returns an error message if failed and null if successful. |
public TreeModel getModel() | Returns the tree model instance |
public void setModel(TreeModel model) | Sets the tree model to a new value |
protected boolean isExpanded(Component node) | This method returns true if the given node is expanded. |
public Component findNodeComponent(Object node) | Finds the component for a model node. |
public Component findNodeComponent(Object node, Component root) | Finds the component for a model node. |
public void expandPath(Object... path) | Expands the tree path |
public void expandPath(boolean animate, Object... path) | Expands the tree path |
public void collapsePath(Object... path) | Collapses the last element in the path |
public Object getSelectedItem() | Returns the currently selected item in the tree |
public Object getParentNode(Component nodeComponent) | Gets the parent model node for a component. |
public Component getParentComponent(Component nodeComponent) | Gets the UI component corresponding to the parent model mode of the node corresponding with the given UI component. |
public void refreshNode(Component nodeComponent) | Refreshes a node of the tree. |
protected Button createNodeComponent(Object node, int depth) | Deprecated Creates a node within the tree, this method is protected allowing tree to be subclassed to replace the rendering logic of individual tree buttons. |
protected void bindNodeListener(ActionListener l, Component node) | Since a node may be any component type developers should override this method to add support for binding the click listener to the given component. |
protected void setNodeIcon(Image icon, Component node) | Sets the icon for the given node similar in scope to bindNodeListener |
protected void setNodeMaterialIcon(char c, Component node, float size) | Sets material icon for the node. |
protected Component createNode(Object node, int depth) | Creates a node within the tree, this method is protected allowing tree to be subclassed to replace the rendering logic of individual tree buttons. |
protected String childToDisplayLabel(Object child) | Converts a tree child to a label, this method can be overriden for simple rendering effects |
public void addLeafListener(ActionListener l) | A listener that fires when a leaf is clicked |
public void removeLeafListener(ActionListener l) | Removes the listener that fires when a leaf is clicked |
protected Object getModel(Component node) | Gets the model for a component in the tree. |
protected Dimension calcPreferredSize() | Calculates the preferred size based on component content. |
Inherited fields
From Component
DEFAULT_CURSOR, CROSSHAIR_CURSOR, TEXT_CURSOR, WAIT_CURSOR, SW_RESIZE_CURSOR, SE_RESIZE_CURSOR, NW_RESIZE_CURSOR, NE_RESIZE_CURSOR, N_RESIZE_CURSOR, S_RESIZE_CURSOR, W_RESIZE_CURSOR, E_RESIZE_CURSOR, HAND_CURSOR, MOVE_CURSOR, DRAG_REGION_NOT_DRAGGABLE, DRAG_REGION_POSSIBLE_DRAG_X, DRAG_REGION_POSSIBLE_DRAG_Y, DRAG_REGION_POSSIBLE_DRAG_XY, DRAG_REGION_LIKELY_DRAG_X, DRAG_REGION_LIKELY_DRAG_Y, DRAG_REGION_LIKELY_DRAG_XY, DRAG_REGION_IMMEDIATELY_DRAG_X, DRAG_REGION_IMMEDIATELY_DRAG_Y, DRAG_REGION_IMMEDIATELY_DRAG_XY, BRB_CONSTANT_ASCENT, BRB_CONSTANT_DESCENT, BRB_CENTER_OFFSET, BRB_OTHER, CENTER, TOP, LEFT, BOTTOM, RIGHT, BASELINE
Inherited methods
From Container
encloseIn, encloseIn, initLaf, getUIManager, setUIManager, isSurface, add, addAll, add, add, add, add, add, getLeadComponent, setLeadComponent, getLeadParent, keyPressed, keyReleased, getLayout, setLayout, invalidate, setShouldLayout, setShouldCalcPreferredSize, getLayoutWidth, getLayoutHeight, applyRTL, constrainWidthWhenScrollable, constrainHeightWhenScrollable, addComponent, addComponent, addComponent, addComponent, replaceAndWait, replaceAndWait, replace, replaceAndWait, replace, createReplaceTransition, isEnabled, setEnabled, removeComponent, cancelRepaints, flushReplace, removeAll, revalidateWithAnimationSafety, revalidate, revalidateLater, forceRevalidate, clearClientProperties, paint, paintGlass, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, paramString, refreshTheme, isScrollableX, setScrollableX, isScrollableY, setScrollableY, getSideGap, getBottomGap, setScrollable, setCellRenderer, getScrollIncrement, setScrollIncrement, findFirstFocusable, dragInitiated, fireClicked, isSelectableInteraction, getGridPosY, paintComponentBackground, getGridPosX, animateHierarchyAndWait, createAnimateHierarchy, animateHierarchy, animateHierarchyFadeAndWait, createAnimateHierarchyFade, animateHierarchyFade, animateLayoutFadeAndWait, createAnimateLayoutFadeAndWait, animateLayoutFade, createAnimateLayoutFade, animateLayoutAndWait, animateLayout, updateTabIndices, createAnimateLayout, drop, createAnimateMotion, morph, morphAndWait, animateUnlayout, animateUnlayoutAndWait, createAnimateUnlayout, getChildrenAsList, iterator, iterator
From Component
setSameSize, isSetCursorSupported, parsePreferredSize, getDefaultDragTransparency, setDefaultDragTransparency, getEditingDelegate, setEditingDelegate, getCursor, setCursor, showNativeOverlay, hideNativeOverlay, updateNativeOverlay, getNativeOverlay, getAllStyles, getSameWidth, setSameWidth, getSameHeight, setSameHeight, getX, setX, getOuterX, getInnerX, getY, setY, getOuterY, getInnerY, isVisible, setVisible, getClientProperty, stripMarginAndPadding, putClientProperty, getDirtyRegion, setDirtyRegion, isOpaque, setOpaque, getWidth, setWidth, getOuterWidth, getInnerWidth, getHeight, setHeight, getOuterHeight, getInnerHeight, isDragRegion, getDragRegionStatus, getBaseline, getBaselineResizeBehavior, getPreferredSizeStr, setPreferredSizeStr, getPreferredSize, setPreferredSize, getScrollDimension, calcScrollSize, setScrollSize, getPreferredW, setPreferredW, getPreferredH, setPreferredH, getOuterPreferredH, getInnerPreferredH, getOuterPreferredW, getInnerPreferredW, setSize, getUIID, setUIID, setUIIDFinal, setUIID, getInlineAllStyles, setInlineAllStyles, getInlineSelectedStyles, setInlineSelectedStyles, getInlineUnselectedStyles, setInlineUnselectedStyles, getInlineDisabledStyles, setInlineDisabledStyles, getInlinePressedStyles, setInlinePressedStyles, remove, getParent, getOwner, setOwner, isOwnedBy, containsOrOwns, addFocusListener, removeFocusListener, addScrollListener, removeScrollListener, getSelectCommandText, setSelectCommandText, getLabelForComponent, setLabelForComponent, focusGained, focusLost, paintBackgrounds, paintShadows, getAbsoluteX, getAbsoluteY, isInClippingRegion, paintIntersectingComponentsAbove, paintScrollbars, paintScrollbarX, getScrollOpacity, getSelectedRect, paintScrollbarY, paintComponent, paintComponent, getBorder, getScrollable, paintBackground, isScrollable, getScrollX, setScrollX, getScrollY, setScrollY, onScrollX, onScrollY, getDraggedx, getDraggedy, contains, visibleBoundsContains, hasFixedPreferredSize, getBounds, getBounds, getVisibleBounds, getVisibleBounds, isFocusable, setFocusable, onSetFocusable, resetFocusable, getTabIndex, setTabIndex, getPreferredTabIndex, setPreferredTabIndex, isTraversable, setTraversable, handlesInput, setHandlesInput, consumesRawTextInput, hasFocus, setFocus, getComponentForm, getTopLevelContainer, repaint, repaint, longKeyPress, keyRepeated, registerForAnimation, deregisterFromAnimation, getAnimationManager, getScrollAnimationSpeed, setScrollAnimationSpeed, isBlockLead, setBlockLead, isIgnorePointerEvents, setIgnorePointerEvents, isRippleEffect, setRippleEffect, getInlineStylesTheme, setInlineStylesTheme, shouldRenderComponentSelection, isHideInLandscape, setHideInLandscape, createStyleAnimation, isSmoothScrolling, setSmoothScrolling, pointerHover, stopScrollMomentum, pointerHoverReleased, pointerHoverPressed, pinch, pinchReleased, pinch, rotation, isPinchBlocksDragAndDrop, setPinchBlocksDragAndDrop, pointerDragged, getDragImage, getDragTransparency, setDragTransparency, toImage, drawDraggedImage, draggingOver, dragEnter, dragExit, addPullToRefresh, setPullToRefresh, respondsToPointerEvents, pointerDragged, isStickyDrag, pointerPressed, isDragAndDropOperation, pointerReleased, longPointerPress, pointerReleased, setVerticalScrollBounds, setHorizontalScrollBounds, isVScrollThumbGrabbed, isHScrollThumbGrabbed, isVScrollThumbHover, isHScrollThumbHover, isTensileDragEnabled, setTensileDragEnabled, getTextSelectionSupport, addDropListener, removeDropListener, addDragOverListener, removeDragOverListener, isNativeDragSource, setNativeDragSource, getNativeDragOperation, setNativeDragOperation, createNativeDragOperation, isNativeDropTarget, setNativeDropTarget, getAcceptedDropMimeTypes, setAcceptedDropMimeTypes, getAcceptedDropActions, setAcceptedDropActions, canAcceptNativeDrop, nativeDragEnter, nativeDragOver, nativeDragExit, nativeDrop, addNativeDropListener, removeNativeDropListener, addNativeDragOverListener, removeNativeDragOverListener, dragFinished, addDragFinishedListener, addStateChangeListener, removeStateChangeListener, addPointerPressedListener, addLongPressListener, addContextMenuListener, removeContextMenuListener, addMouseWheelListener, removeMouseWheelListener, addStylusListener, removeStylusListener, mouseWheel, paintRippleOverlay, removePointerPressedListener, removeLongPressListener, removeDragFinishedListener, addPointerReleasedListener, removePointerReleasedListener, addPointerDraggedListener, removePointerDraggedListener, getDragSpeed, getStyle, getPressedStyle, setPressedStyle, initUnselectedStyle, initPressedStyle, initDisabledStyle, initSelectedStyle, getUnselectedStyle, setUnselectedStyle, getSelectedStyle, setSelectedStyle, getDisabledStyle, setDisabledStyle, installDefaultPainter, requestFocus, toString, refreshTheme, refreshTheme, isDragActivated, animate, scrollRectToVisible, scrollRectToVisible, paintBorder, paintBorderBackground, isCellRenderer, isScrollVisible, setScrollVisible, setIsScrollVisible, startEditingAsync, stopEditing, isEditing, isEditable, laidOut, deinitialize, initComponent, isInitialized, setInitialized, styleChanged, getNextFocusDown, setNextFocusDown, getNextFocusUp, setNextFocusUp, getNextFocusLeft, setNextFocusLeft, getNextFocusRight, setNextFocusRight, getName, setName, initCustomStyle, deinitializeCustomStyle, isRTL, setRTL, isTactileTouch, isTactileTouch, setTactileTouch, paintLockRelease, paintLock, isSnapToGrid, setSnapToGrid, shouldBlockSideSwipe, shouldBlockSideSwipeLeft, shouldBlockSideSwipeRight, blocksSideSwipe, isFlatten, setFlatten, getTensileLength, setTensileLength, isGrabsPointerEvents, setGrabsPointerEvents, getScrollOpacityChangeSpeed, setScrollOpacityChangeSpeed, growShrink, isAlwaysTensile, setAlwaysTensile, isDraggable, setDraggable, isDropTarget, setDropTarget, isChildOf, isHideInPortrait, setHideInPortrait, getBindablePropertyNames, getBindablePropertyTypes, bindProperty, unbindProperty, getBoundPropertyValue, setBoundPropertyValue, getCloudBoundProperty, setCloudBoundProperty, getCloudDestinationProperty, setCloudDestinationProperty, getComponentState, setComponentState, setHidden, isHidden, setHidden, isHidden, announceForAccessibility, getAccessibilityText, setAccessibilityText, getSemantics, getAccessibilityNode, accessibilityChanged, accessibilityChanged, getTooltip, setTooltip
Constructor details
Tree
public Tree()Tree
public Tree(TreeModel model)Parameters
modelTreeModel- represents the contents of the tree
Method details
setFolderIcon
public static void setFolderIcon(Image folderIcon)Parameters
folderIconImage- the icon for a folder within the tree
setFolderOpenIcon
public static void setFolderOpenIcon(Image folderIcon)Parameters
folderIconImage- the icon for a folder within the tree
setNodeIcon
public static void setNodeIcon(Image nodeIcon)Parameters
nodeIconImage- the icon for a node within the tree
getTreeState
public Tree.TreeState getTreeState()Returns
#setTreeState(com.codename1.ui.tree.Tree.TreeState)setTreeState
public void setTreeState(Tree.TreeState state)Parameters
stateTree.TreeState- The state, which was returned from the
#getTreeState()method.
isMultilineMode
public boolean isMultilineMode()Returns
setMultilineMode
public void setMultilineMode(boolean multilineMode)Parameters
multilineModeboolean- the multilineMode to set
getPropertyNames
public String[] getPropertyNames()Returns
getPropertyTypes
public Class[] getPropertyTypes()Returns
getPropertyTypeNames
public String[] getPropertyTypeNames()Returns
getPropertyValue
public Object getPropertyValue(String name)Parameters
nameString- the name of the property
Returns
setPropertyValue
public String setPropertyValue(String name, Object value)Parameters
nameString- the name of the property
valueObject- new value for the property
Returns
getModel
public TreeModel getModel()Returns
setModel
public void setModel(TreeModel model)Parameters
modelTreeModel- the model of the tree
isExpanded
protected boolean isExpanded(Component node)Parameters
nodeComponent- a Component that represents a tree node.
Returns
findNodeComponent
public Component findNodeComponent(Object node)Parameters
nodeObject- The node from the model.
Returns
findNodeComponent
public Component findNodeComponent(Object node, Component root)Parameters
nodeObject- Model node whose view we seek.
rootComponent- A root component - we check root and its descendents.
Returns
expandPath
public void expandPath(Object... path)Parameters
pathObject...- the path to expand
expandPath
public void expandPath(boolean animate, Object... path)Parameters
animateboolean- whether to animate expansion
pathObject...- the path to expand
collapsePath
public void collapsePath(Object... path)Parameters
pathObject...- the path to the element that should be collapsed
getSelectedItem
public Object getSelectedItem()Returns
getParentNode
public Object getParentNode(Component nodeComponent)Parameters
nodeComponentComponent- The UI for a node.
Returns
getParentComponent
public Component getParentComponent(Component nodeComponent)Parameters
nodeComponentComponent- UI component, whose node we seek the parent.
Returns
refreshNode
public void refreshNode(Component nodeComponent)Parameters
nodeComponentComponent- The node component.
createNodeComponent
protected Button createNodeComponent(Object node, int depth)Parameters
nodeObject- the node object from the model to display on the button
depthint- the depth within the tree (normally represented by indenting the entry)
Returns
bindNodeListener
protected void bindNodeListener(ActionListener l, Component node)Parameters
lActionListener- listener interface
nodeComponent- node component returned by createNode
setNodeIcon
protected void setNodeIcon(Image icon, Component node)Parameters
iconImage- the icon for the node
nodeComponent- the node instance
setNodeMaterialIcon
protected void setNodeMaterialIcon(char c, Component node, float size)Parameters
cchar- Material icon code. See
FontImage nodeComponent- The node to set the icon for.
sizefloat- The size in millimetres for the icon.
createNode
protected Component createNode(Object node, int depth)Parameters
nodeObject- the node object from the model to display on the button
depthint- the depth within the tree (normally represented by indenting the entry)
Returns
childToDisplayLabel
protected String childToDisplayLabel(Object child)Returns
addLeafListener
public void addLeafListener(ActionListener l)Parameters
lActionListener- listener to fire when the leaf is clicked
removeLeafListener
public void removeLeafListener(ActionListener l)Parameters
lActionListener- listener to remove
getModel
protected Object getModel(Component node)Parameters
nodeComponent- The component whose model we want to obtain.
Returns
calcPreferredSize
protected Dimension calcPreferredSize()