Class ExpandableCollapsableJTable

java.lang.Object
  extended byjava.awt.Component
      extended byjava.awt.Container
          extended byjavax.swing.JComponent
              extended byjavax.swing.JTable
                  extended byExpandableCollapsableJTable
All Implemented Interfaces:
javax.accessibility.Accessible, javax.swing.event.CellEditorListener, java.util.EventListener, java.awt.image.ImageObserver, javax.swing.event.ListSelectionListener, java.awt.MenuContainer, javax.swing.Scrollable, java.io.Serializable, javax.swing.event.TableColumnModelListener, javax.swing.event.TableModelListener

public class ExpandableCollapsableJTable
extends javax.swing.JTable

Play around with expand/collapse of column headings in a JTable. It's done here using a custom JLabel-based cell renderer, defined in the companion class TableCellRendererLabel.

The approach is to leave out the built-in JTable headings and define them manually as the first one or two rows of the table. There are two buttons at the bottom of the display to demonstrate the effect of expanding and collapsing the headings rows. Most of the work to make this happen is done in the companion cell renderer.

Note in particular the specializations of the getCellRenderer and getCellEditor JTable methods. The former is specialized to return the custom cell renderer. The latter is specialized to disable editing in the column headings.

There is also a button at the bottom to demonstrate programmatic cell editing. It pops up a dialog to enter the value for an arbitrary data cell in the table, and then changes that cell to the entered value.

The model data in this example are totally canned. They are two-dimensional arrays for both the expanded and collapsed states of the table. A real model/view design would use a separate model data class, with methods to access the real data and set the table state.

See Also:
Serialized Form

Nested Class Summary
 
Nested classes inherited from class javax.swing.JTable
javax.swing.JTable.AccessibleJTable
 
Nested classes inherited from class javax.swing.JComponent
javax.swing.JComponent.AccessibleJComponent
 
Nested classes inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
static javax.swing.JButton changeButton
          The change button; it's only a data field for use in input dialog positioning
protected static java.lang.Object[][] collapsedData
          Canned model data for a collapsed table
protected static java.lang.Object[][] data
          Canned model data for an expanded table
protected static java.lang.String[] dummyHeadings
          Dummy headings for the model.
protected static boolean isExpanded
          Flag indicating whether the table is expanded or collapsed.
protected static javax.swing.table.DefaultTableModel model
          The table model.
protected static java.lang.String[] oneSubheadings
          Headings for the second row, second column of an expanded table.
protected static TableCellRendererLabel renderer
          The custom renderer.
protected static java.lang.String[] topHeadings
          Headings for the top row of an collapsed table.
 
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
ExpandableCollapsableJTable(javax.swing.table.DefaultTableModel model)
          Just call the parent constructor for this overload of the constructor signature.
 
Method Summary
protected static void changeData()
           
protected static void collapse()
          Change the model data state to the collapsed version of the data and set isExpanded to true.
protected static javax.swing.Box createButtons()
          Put the three buttons at the bottom of the screen -- "Expand", "Collapse", and "Change Data".
protected static void expand()
          Change the model data state to the expanded version of the data and set isExpanded to true.
 javax.swing.table.TableCellEditor getCellEditor(int row, int column)
          Specialize this method to turn off editing in the column headings.
 javax.swing.table.TableCellRenderer getCellRenderer(int row, int column)
          Specialize this method to return the custom cell renderer defined in TableCellRendererLabel.
static void main(java.lang.String[] args)
          Do some initialization, a bit of layout, and the normal stuff to put up a Swing JFrame.
 
Methods inherited from class javax.swing.JTable
addColumn, addColumnSelectionInterval, addNotify, addRowSelectionInterval, changeSelection, clearSelection, columnAdded, columnAtPoint, columnMarginChanged, columnMoved, columnRemoved, columnSelectionChanged, configureEnclosingScrollPane, convertColumnIndexToModel, convertColumnIndexToView, createDefaultColumnModel, createDefaultColumnsFromModel, createDefaultDataModel, createDefaultEditors, createDefaultRenderers, createDefaultSelectionModel, createDefaultTableHeader, createScrollPaneForTable, doLayout, editCellAt, editCellAt, editingCanceled, editingStopped, getAccessibleContext, getAutoCreateColumnsFromModel, getAutoResizeMode, getCellEditor, getCellRect, getCellSelectionEnabled, getColumn, getColumnClass, getColumnCount, getColumnModel, getColumnName, getColumnSelectionAllowed, getDefaultEditor, getDefaultRenderer, getDragEnabled, getEditingColumn, getEditingRow, getEditorComponent, getGridColor, getIntercellSpacing, getModel, getPreferredScrollableViewportSize, getRowCount, getRowHeight, getRowHeight, getRowMargin, getRowSelectionAllowed, getScrollableBlockIncrement, getScrollableTracksViewportHeight, getScrollableTracksViewportWidth, getScrollableUnitIncrement, getSelectedColumn, getSelectedColumnCount, getSelectedColumns, getSelectedRow, getSelectedRowCount, getSelectedRows, getSelectionBackground, getSelectionForeground, getSelectionModel, getShowHorizontalLines, getShowVerticalLines, getSurrendersFocusOnKeystroke, getTableHeader, getToolTipText, getUI, getUIClassID, getValueAt, initializeLocalVars, isCellEditable, isCellSelected, isColumnSelected, isEditing, isRowSelected, moveColumn, paramString, prepareEditor, prepareRenderer, processKeyBinding, removeColumn, removeColumnSelectionInterval, removeEditor, removeNotify, removeRowSelectionInterval, resizeAndRepaint, rowAtPoint, selectAll, setAutoCreateColumnsFromModel, setAutoResizeMode, setCellEditor, setCellSelectionEnabled, setColumnModel, setColumnSelectionAllowed, setColumnSelectionInterval, setDefaultEditor, setDefaultRenderer, setDragEnabled, setEditingColumn, setEditingRow, setGridColor, setIntercellSpacing, setModel, setPreferredScrollableViewportSize, setRowHeight, setRowHeight, setRowMargin, setRowSelectionAllowed, setRowSelectionInterval, setSelectionBackground, setSelectionForeground, setSelectionMode, setSelectionModel, setShowGrid, setShowHorizontalLines, setShowVerticalLines, setSurrendersFocusOnKeystroke, setTableHeader, setUI, setValueAt, sizeColumnsToFit, sizeColumnsToFit, tableChanged, unconfigureEnclosingScrollPane, updateUI, valueChanged
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paint, paintBorder, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, 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, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, 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, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getPeer, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, 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, processMouseEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, 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

model

protected static javax.swing.table.DefaultTableModel model
The table model.


renderer

protected static TableCellRendererLabel renderer
The custom renderer.


dummyHeadings

protected static java.lang.String[] dummyHeadings
Dummy headings for the model. These are not displayed, but the DefaultTableModel wants them anyway.


topHeadings

protected static java.lang.String[] topHeadings
Headings for the top row of an collapsed table.


oneSubheadings

protected static java.lang.String[] oneSubheadings
Headings for the second row, second column of an expanded table.


data

protected static java.lang.Object[][] data
Canned model data for an expanded table


collapsedData

protected static java.lang.Object[][] collapsedData
Canned model data for a collapsed table


changeButton

public static javax.swing.JButton changeButton
The change button; it's only a data field for use in input dialog positioning


isExpanded

protected static boolean isExpanded
Flag indicating whether the table is expanded or collapsed.

Constructor Detail

ExpandableCollapsableJTable

public ExpandableCollapsableJTable(javax.swing.table.DefaultTableModel model)
Just call the parent constructor for this overload of the constructor signature.

Method Detail

main

public static void main(java.lang.String[] args)
Do some initialization, a bit of layout, and the normal stuff to put up a Swing JFrame. See the code for details.


getCellRenderer

public javax.swing.table.TableCellRenderer getCellRenderer(int row,
                                                           int column)
Specialize this method to return the custom cell renderer defined in TableCellRendererLabel.


getCellEditor

public javax.swing.table.TableCellEditor getCellEditor(int row,
                                                       int column)
Specialize this method to turn off editing in the column headings. These are the first two rows of an expanded table, or the first row of a collapsed table.


createButtons

protected static javax.swing.Box createButtons()
Put the three buttons at the bottom of the screen -- "Expand", "Collapse", and "Change Data".


expand

protected static void expand()
Change the model data state to the expanded version of the data and set isExpanded to true.


collapse

protected static void collapse()
Change the model data state to the collapsed version of the data and set isExpanded to true.


changeData

protected static void changeData()