org.formaria.swing
Class TreeTable

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JTable
                  extended by org.formaria.swing.TreeTable
All Implemented Interfaces:
java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible, javax.swing.event.CellEditorListener, javax.swing.event.ListSelectionListener, javax.swing.event.RowSorterListener, javax.swing.event.TableColumnModelListener, javax.swing.event.TableModelListener, javax.swing.Scrollable, RowSelector, ErrorDisplay, ListenerHelper, ModelHolder, StyleComponent, AdaptedTable

public class TreeTable
extends javax.swing.JTable
implements ModelHolder, RowSelector, StyleComponent, ListenerHelper, AdaptedTable, ErrorDisplay

This example shows how to create a simple TreeTable component, by using a JTree as a renderer (and editor) for the cells in a particular column in the JTable.

Copyright (c) Formaria Ltd., 2008, This software is licensed under the GNU Public License (GPL), please see license.txt for more details. If you make commercial use of this software you must purchase a commercial license from formaria.

$Revision: 1.22 $

See Also:
Serialized Form

Nested Class Summary
 class TreeTable.TreeTableCellEditor
          TreeTableCellEditor implementation.
 class TreeTable.TreeTableCellRenderer
          A TreeCellRenderer that displays a JTree.
 class TreeTable.TreeTableTreeCellRenderer
           
 
Nested classes/interfaces inherited from class javax.swing.JTable
javax.swing.JTable.AccessibleJTable, javax.swing.JTable.DropLocation, javax.swing.JTable.PrintMode
 
Nested classes/interfaces inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
protected  java.awt.Color altUnselectedBackground
           
protected  java.awt.Color altUnselectedForeground
           
protected  java.lang.String errorMessage
           
protected  int errorStatus
           
protected  HandlerInvoker invoker
           
protected  AbstractTreeTableModel model
           
protected  java.util.Hashtable renderers
           
protected  TreeTable.TreeTableCellRenderer tree
          A subclass of JTree.
protected  boolean updateModelSelection
           
protected  DataModel xmodel
           
 
Fields inherited from class javax.swing.JTable
AUTO_RESIZE_ALL_COLUMNS, AUTO_RESIZE_LAST_COLUMN, AUTO_RESIZE_NEXT_COLUMN, AUTO_RESIZE_OFF, AUTO_RESIZE_SUBSEQUENT_COLUMNS, autoCreateColumnsFromModel, autoResizeMode, cellEditor, cellSelectionEnabled, columnModel, dataModel, defaultEditorsByColumnClass, defaultRenderersByColumnClass, editingColumn, editingRow, editorComp, gridColor, preferredViewportSize, rowHeight, rowMargin, rowSelectionAllowed, selectionBackground, selectionForeground, selectionModel, showHorizontalLines, showVerticalLines, tableHeader
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
TreeTable()
          Create a new TreeTable
 
Method Summary
 void addHandler(java.lang.Object page, java.lang.String handlerType, java.lang.String methodName)
          Add an event handler response method to a component such that the page's response method is invoked when the event occurs
 void addRenderer(int column, javax.swing.table.TableCellRenderer renderer)
          Add a cell renderer for the specified column
 void displayAsColorField(int column, java.util.Hashtable colors)
          Display the field formatted with a background color from the hashtable such that the field value acts as a key into the hashtable of colors
 void displayAsNumericField(int column, java.text.Format format)
          Display the field as a numeric value
 javax.swing.table.TableCellRenderer getCellRenderer(int row, int column)
          Get a render for this cell
 int getEditingRow()
           
 java.lang.String getFieldName(int column, java.lang.String field)
          Get the name ofthe field as displayed in the table header
 java.lang.String getFieldValue(int fieldIdx)
          Gets a field value as a string from the currently selected row
 java.lang.String getFieldValue(int rowIdx, int fieldIdx)
          Gets a field value as a string from the specified row
 java.lang.String getHeadingStyle()
          Set the style of the header data
 int getSelectedRow()
          Get the row selection index
 java.lang.String getSelectionStyle()
          Get the style of the selected row
 javax.swing.JTree getTree()
          Returns the tree that is being shared between the model.
 boolean getUpdateModelSelection()
          Get the model selection update flag
 java.lang.Object getValue(int fieldIdx)
          Gets a field value object from the currently selected row
 java.lang.Object getValue(int rowIdx, int fieldIdx)
          Gets a field value object from the specified row
 void paint(java.awt.Graphics g)
          Paint the component, rendering the error badge if necessary
 void reload()
           
protected  void reload(java.lang.Object node)
          Invoked to reload the children of a particular node.
 void setAlignment(int column, int alignment)
          Set the alignment of a column
 void setAltStyle(java.lang.String style)
          Set the style of the alternate rows
 void setAltUnselectedColors(java.awt.Color frgd, java.awt.Color bkgd)
          Set the colors for alternate ( odd ) row colors
 void setBorder(java.lang.String hasBorder)
           
 void setBorderStyle(java.lang.String style)
          Set the style of the border
 void setColumnWidth(int columnIdx, int width)
          Set the column width.
 void setDataModel(DataModel _xmodel)
          Set the model data.
 void setDataModel(DataModel _xmodel, javax.swing.table.TableModel delegModel)
          Set the DataModel which we will be generating the table from
 void setEnabled(boolean b)
          Set the enabled state
 void setErrorMessage(java.lang.String errorMsg)
          Set the error message
 void setErrorStatus(int status)
          Set the error status
 void setHeaderRenderer()
          Set a header renderer for thetable.
 void setHeadingStyle(java.lang.String style)
          Set the style of the header data
 void setModelAdapter(TableModelAdapter xmodel)
          Set the XModel which we will be generating the table from
 void setRowHeight(int rowHeight)
          Overridden to pass the new rowHeight to the tree.
 void setSelectedRow(int rowIdx)
          Set the row selection index
 void setSelection(int rowIdx)
          Select the nth visible row one level down from the parent.
 void setSelectionStyle(java.lang.String style)
          Set the style of the selected row
 void setStyle(java.lang.String style)
          Set the general style of the Table
 void setUpdateModelSelection(boolean doUpdate)
          Tie the model selection to this table's selection
 void update()
          Update the table's model
 void updateTable()
          Force the table to update itself
 void updateUI()
          Overridden to message super and forward the method to the tree.
 
Methods inherited from class javax.swing.JTable
addColumn, addColumnSelectionInterval, addNotify, addRowSelectionInterval, changeSelection, clearSelection, columnAdded, columnAtPoint, columnMarginChanged, columnMoved, columnRemoved, columnSelectionChanged, configureEnclosingScrollPane, convertColumnIndexToModel, convertColumnIndexToView, convertRowIndexToModel, convertRowIndexToView, createDefaultColumnModel, createDefaultColumnsFromModel, createDefaultDataModel, createDefaultEditors, createDefaultRenderers, createDefaultSelectionModel, createDefaultTableHeader, createScrollPaneForTable, doLayout, editCellAt, editCellAt, editingCanceled, editingStopped, getAccessibleContext, getAutoCreateColumnsFromModel, getAutoCreateRowSorter, getAutoResizeMode, getCellEditor, getCellEditor, getCellRect, getCellSelectionEnabled, getColumn, getColumnClass, getColumnCount, getColumnModel, getColumnName, getColumnSelectionAllowed, getDefaultEditor, getDefaultRenderer, getDragEnabled, getDropLocation, getDropMode, getEditingColumn, getEditorComponent, getFillsViewportHeight, getGridColor, getIntercellSpacing, getModel, getPreferredScrollableViewportSize, getPrintable, getRowCount, getRowHeight, getRowHeight, getRowMargin, getRowSelectionAllowed, getRowSorter, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedColumn, getSelectedColumnCount, getSelectedColumns, getSelectedRowCount, getSelectedRows, getSelectionBackground, getSelectionForeground, getSelectionModel, getShowHorizontalLines, getShowVerticalLines, getSurrendersFocusOnKeystroke, getTableHeader, getToolTipText, getUI, getUIClassID, getUpdateSelectionOnSort, getValueAt, initializeLocalVars, isCellEditable, isCellSelected, isColumnSelected, isEditing, isRowSelected, moveColumn, paramString, prepareEditor, prepareRenderer, print, print, print, print, print, processKeyBinding, removeColumn, removeColumnSelectionInterval, removeEditor, removeNotify, removeRowSelectionInterval, resizeAndRepaint, rowAtPoint, selectAll, setAutoCreateColumnsFromModel, setAutoCreateRowSorter, setAutoResizeMode, setCellEditor, setCellSelectionEnabled, setColumnModel, setColumnSelectionAllowed, setColumnSelectionInterval, setDefaultEditor, setDefaultRenderer, setDragEnabled, setDropMode, setEditingColumn, setEditingRow, setFillsViewportHeight, setGridColor, setIntercellSpacing, setModel, setPreferredScrollableViewportSize, setRowHeight, setRowMargin, setRowSelectionAllowed, setRowSelectionInterval, setRowSorter, setSelectionBackground, setSelectionForeground, setSelectionMode, setSelectionModel, setShowGrid, setShowHorizontalLines, setShowVerticalLines, setSurrendersFocusOnKeystroke, setTableHeader, setUI, setUpdateSelectionOnSort, setValueAt, sizeColumnsToFit, sizeColumnsToFit, sorterChanged, tableChanged, unconfigureEnclosingScrollPane, valueChanged
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

xmodel

protected DataModel xmodel

model

protected AbstractTreeTableModel model

updateModelSelection

protected boolean updateModelSelection

invoker

protected HandlerInvoker invoker

tree

protected TreeTable.TreeTableCellRenderer tree
A subclass of JTree.


renderers

protected java.util.Hashtable renderers

altUnselectedForeground

protected java.awt.Color altUnselectedForeground

altUnselectedBackground

protected java.awt.Color altUnselectedBackground

errorStatus

protected int errorStatus

errorMessage

protected java.lang.String errorMessage
Constructor Detail

TreeTable

public TreeTable()
Create a new TreeTable

Method Detail

getSelectedRow

public int getSelectedRow()
Description copied from interface: RowSelector
Get the row selection index

Specified by:
getSelectedRow in interface RowSelector
Overrides:
getSelectedRow in class javax.swing.JTable
Returns:
the current row selection index (zero based)

getValue

public java.lang.Object getValue(int fieldIdx)
Gets a field value object from the currently selected row

Parameters:
fieldIdx - the field offset
Returns:
the value

getValue

public java.lang.Object getValue(int rowIdx,
                                 int fieldIdx)
Gets a field value object from the specified row

Parameters:
rowIdx - the row offset
fieldIdx - the field offset
Returns:
the value

getFieldValue

public java.lang.String getFieldValue(int fieldIdx)
Gets a field value as a string from the currently selected row

Parameters:
fieldIdx - the field offset
Returns:
the value

getFieldValue

public java.lang.String getFieldValue(int rowIdx,
                                      int fieldIdx)
Gets a field value as a string from the specified row

Parameters:
rowIdx - the row offset
fieldIdx - the field offset
Returns:
the value

update

public void update()
Update the table's model

Specified by:
update in interface ModelHolder

updateTable

public void updateTable()
Force the table to update itself


setDataModel

public void setDataModel(DataModel _xmodel)
Description copied from interface: ModelHolder
Set the model data.

Specified by:
setDataModel in interface ModelHolder
Parameters:
_xmodel - the model node containing the data to be used by the component

setDataModel

public void setDataModel(DataModel _xmodel,
                         javax.swing.table.TableModel delegModel)
Set the DataModel which we will be generating the table from

Parameters:
_xmodel - The DataModel of data

reload

public void reload()

setColumnWidth

public void setColumnWidth(int columnIdx,
                           int width)
Set the column width. Sets the maximum width as a workaround for a Swing problem

Parameters:
columnIdx - the column index
width - the new width

setAltUnselectedColors

public void setAltUnselectedColors(java.awt.Color frgd,
                                   java.awt.Color bkgd)
Set the colors for alternate ( odd ) row colors

Parameters:
frgd - the foreground color
bkgd - the background color

getCellRenderer

public javax.swing.table.TableCellRenderer getCellRenderer(int row,
                                                           int column)
Get a render for this cell

Overrides:
getCellRenderer in class javax.swing.JTable

setEnabled

public void setEnabled(boolean b)
Set the enabled state

Overrides:
setEnabled in class javax.swing.JComponent
Parameters:
b - true to enable

setAlignment

public void setAlignment(int column,
                         int alignment)
Set the alignment of a column

Parameters:
column - the column index
alignment - the SwingContants aliignment constant

displayAsNumericField

public void displayAsNumericField(int column,
                                  java.text.Format format)
Display the field as a numeric value

Parameters:
column - the column or field index
format - format the number format to use in displaying the field

displayAsColorField

public void displayAsColorField(int column,
                                java.util.Hashtable colors)
Display the field formatted with a background color from the hashtable such that the field value acts as a key into the hashtable of colors

Parameters:
column - the column or field index
colors - the color hashtable

addRenderer

public void addRenderer(int column,
                        javax.swing.table.TableCellRenderer renderer)
Add a cell renderer for the specified column

Parameters:
column - the column or field index

setHeaderRenderer

public void setHeaderRenderer()
Set a header renderer for thetable.


setBorder

public void setBorder(java.lang.String hasBorder)

setStyle

public void setStyle(java.lang.String style)
Set the general style of the Table

Specified by:
setStyle in interface StyleComponent
Parameters:
style - Style

setHeadingStyle

public void setHeadingStyle(java.lang.String style)
Set the style of the header data

Parameters:
style - Style

setSelectionStyle

public void setSelectionStyle(java.lang.String style)
Set the style of the selected row

Parameters:
style - Style

setAltStyle

public void setAltStyle(java.lang.String style)
Set the style of the alternate rows

Parameters:
style - Style

getHeadingStyle

public java.lang.String getHeadingStyle()
Set the style of the header data

Returns:
the header styles

getSelectionStyle

public java.lang.String getSelectionStyle()
Get the style of the selected row

Returns:
the selected style

setBorderStyle

public void setBorderStyle(java.lang.String style)
Set the style of the border

Parameters:
style - Style

setSelectedRow

public void setSelectedRow(int rowIdx)
Set the row selection index

Specified by:
setSelectedRow in interface RowSelector
Parameters:
rowIdx - the new row selection index (zero based)

addHandler

public void addHandler(java.lang.Object page,
                       java.lang.String handlerType,
                       java.lang.String methodName)
                throws java.lang.NoSuchMethodException
Add an event handler response method to a component such that the page's response method is invoked when the event occurs

Specified by:
addHandler in interface ListenerHelper
Parameters:
page - the page containing the method
handlerType - the type of event handler
methodName - the method to invoke
Throws:
java.lang.NoSuchMethodException - cannot add the handler

setUpdateModelSelection

public void setUpdateModelSelection(boolean doUpdate)
Tie the model selection to this table's selection

Parameters:
doUpdate - true to tie the selections together, false to ignore

getUpdateModelSelection

public boolean getUpdateModelSelection()
Get the model selection update flag


updateUI

public void updateUI()
Overridden to message super and forward the method to the tree. Since the tree is not actually in the component hieachy it will never receive this unless we forward it in this manner.

Overrides:
updateUI in class javax.swing.JTable

getEditingRow

public int getEditingRow()
Overrides:
getEditingRow in class javax.swing.JTable

setRowHeight

public void setRowHeight(int rowHeight)
Overridden to pass the new rowHeight to the tree.

Overrides:
setRowHeight in class javax.swing.JTable

getTree

public javax.swing.JTree getTree()
Returns the tree that is being shared between the model.


setSelection

public void setSelection(int rowIdx)
Select the nth visible row one level down from the parent.

Parameters:
rowIdx - the row index

reload

protected void reload(java.lang.Object node)
Invoked to reload the children of a particular node. This will also restart the timer.


setModelAdapter

public void setModelAdapter(TableModelAdapter xmodel)
Description copied from interface: AdaptedTable
Set the XModel which we will be generating the table from

Specified by:
setModelAdapter in interface AdaptedTable
Parameters:
xmodel - The XModel of data

getFieldName

public java.lang.String getFieldName(int column,
                                     java.lang.String field)
Get the name ofthe field as displayed in the table header

Specified by:
getFieldName in interface AdaptedTable
Parameters:
field -
column - the column index
Returns:
the displayable names

paint

public void paint(java.awt.Graphics g)
Paint the component, rendering the error badge if necessary

Overrides:
paint in class javax.swing.JComponent
Parameters:
g -

setErrorStatus

public void setErrorStatus(int status)
Set the error status

Specified by:
setErrorStatus in interface ErrorDisplay
Parameters:
status -

setErrorMessage

public void setErrorMessage(java.lang.String errorMsg)
Set the error message

Specified by:
setErrorMessage in interface ErrorDisplay
Parameters:
errorMsg - the message text