public class Table
ImplementsAnimation, Editable, Iterable<Component>, StyleListener
The Table class represents a grid of data that can be used for rendering a grid
of components/labels. The table reflects and updates the underlying model data.
Table relies heavily on the com.codename1.ui.table.TableLayout class and
com.codename1.ui.table.TableModel interface to present its UI. Unlike a
com.codename1.ui.List a Table doesn’t feature a separate renderer
and instead allows developers to derive the class.
Form hi = new Form("Table", new BorderLayout());
TableModel model = new DefaultTableModel(new String[] {"Col 1", "Col 2", "Col 3"}, new Object[][] {
{"Row 1", "Row A", "Row X"},
{"Row 2", "Row B can now stretch", null},
{"Row 3", "Row C", "Row Z"},
{"Row 4", "Row D", "Row K"},
}) {
public boolean isCellEditable(int row, int col) {
return col != 0;
}
};
Table table = new Table(model) {
@Override
protected Component createCell(Object value, int row, int column, boolean editable) { // (1)
Component cell;
if(row == 1 && column == 1) { // (2)
Picker p = new Picker();
p.setType(Display.PICKER_TYPE_STRINGS);
p.setStrings("Row B can now stretch", "This is a good value", "So Is This", "Better than text field");
p.setSelectedString((String)value); // (3)
p.setUIID("TableCell");
p.addActionListener((e) -> getModel().setValueAt(row, column, p.getSelectedString())); // (4)
cell = p;
} else {
cell = super.createCell(value, row, column, editable);
}
if(row > -1 && row % 2 == 0) { // (5)
// pinstripe effect
cell.getAllStyles().setBgColor(0xeeeeee);
cell.getAllStyles().setBgTransparency(255);
}
return cell;
}
@Override
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint con = super.createCellConstraint(value, row, column);
if(row == 1 && column == 1) {
con.setHorizontalSpan(2);
}
con.setWidthPercentage(33);
return con;
}
};
hi.add(BorderLayout.CENTER, table);
hi.show();
Fields
public static final int INNER_BORDERS_NONE = 0 | Constant denoting that inner borders should not be drawn at all |
public static final int INNER_BORDERS_ROWS = 1 | Constant denoting that only inner borders rows should be drawn |
public static final int INNER_BORDERS_COLS = 2 | Constant denoting that only inner borders columns should be drawn |
public static final int INNER_BORDERS_ALL = 3 | Constant denoting that inner borders should be drawn fully |
Constructors
public Table() | Constructor for usage by GUI builder and automated tools, normally one should use the version that accepts the model |
public Table(TableModel model) | Create a table with a new model |
public Table(TableModel model, boolean includeHeader) | Create a table with a new model |
Methods
public int getSelectedRow() | Returns the selected row in the table |
protected boolean includeNullValues() | By default createCell/constraint won’t be invoked for null values by overriding this method to return true you can replace this behavior |
public int getSelectedColumn() | Returns the selected column in the table |
protected void paintGlass(Graphics g) | This method can be overriden by a component to draw on top of itself or its children after the component or the children finished drawing in a similar way to the glass pane but more refined per component |
protected Comparator<Object> createColumnSortComparator(int column) | Returns a generic comparator that tries to work in a way that will sort columns with similar object types. |
public void sort(int column, boolean ascending) | Sorts the given column programmatically |
protected Component createCell(Object value, int row, int column, boolean editable) | Creates a cell based on the given value |
public void initComponent() | Allows subclasses to bind functionality that relies on fully initialized and “ready for action” component state |
public void deinitialize() | Invoked to indicate that the component initialization is being reversed since the component was detached from the container hierarchy. |
public TableModel getModel() | Returns the model instance |
public void setModel(TableModel model) | Replaces the underlying model |
public boolean isDrawBorder() | Indicates whether the table border should be drawn |
public void setDrawBorder(boolean drawBorder) | Indicates whether the table border should be drawn |
public int getInnerBorderMode() | Returns the current inner border mode |
public void setInnerBorderMode(int innerBorder) | Sets how to draw the inner border (All of it, only rows/columns, none, groups) Note that setting to any mode other than NONE/ALL will result in the border drawing as collapsed whether this is a collpased border or not |
protected boolean shouldDrawInnerBorderAfterRow(int row) | Returns whether an inner border should be drawn after the specified row. |
public void setCollapseBorder(boolean collapseBorder) | Indicates whether the borders of the cells should collapse to form a one line border |
public void setDrawEmptyCellsBorder(boolean drawEmptyCellsBorder) | Indicates whether empty cells should have borders (relevant only for separate borders and not for collapsed) |
public void setBorderSpacing(int horizontal, int vertical) | Sets the spacing of cells border (relevant only for separate borders and not for collapsed) |
public int getTitleAlignment() | Indicates the alignment of the title see label alignment for details |
public void setTitleAlignment(int titleAlignment) | Indicates the alignment of the title see label alignment for details |
public int getCellColumn(Component cell) | Returns the column in which the given cell is placed |
public int getCellRow(Component cell) | Returns the row in which the given cell is placed |
public int getCellAlignment() | Indicates the alignment of the cells see label alignment for details |
public void setCellAlignment(int cellAlignment) | Indicates the alignment of the cells see label alignment for details |
public boolean isIncludeHeader() | Indicates whether the table should render a table header as the first row |
public void setIncludeHeader(boolean includeHeader) | Indicates whether the table should render a table header as the first row |
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) | Creates the table cell constraint for the given cell, this method can be overriden for the purposes of modifying the table constraints. |
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 int translateSortedRowToModelRow(int row) | If the table is sorted returns the position of the row in the actual underlying model |
public boolean isSortSupported() | Sort support can be toggled with this flag |
public void setSortSupported(boolean sortSupported) | Sort support can be toggled with this flag |
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, layoutContainer, isSafeArea, setSafeArea, isSafeAreaRoot, getSafeAreaRoot, setSafeAreaRoot, getComponentCount, getComponentAt, getComponentIndex, contains, scrollComponentToVisible, getClosestComponentTo, getResponderAt, getComponentAt, findDropTargetAt, pointerPressed, calcPreferredSize, 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, 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
Field details
INNER_BORDERS_NONE
public static final int INNER_BORDERS_NONE = 0INNER_BORDERS_ROWS
public static final int INNER_BORDERS_ROWS = 1INNER_BORDERS_COLS
public static final int INNER_BORDERS_COLS = 2INNER_BORDERS_ALL
public static final int INNER_BORDERS_ALL = 3Constructor details
Table
public Table()Table
public Table(TableModel model)Parameters
modelTableModel- the model underlying this table
Table
public Table(TableModel model, boolean includeHeader)Parameters
modelTableModel- the model underlying this table
includeHeaderboolean- Indicates whether the table should render a table header as the first row
Method details
getSelectedRow
public int getSelectedRow()Returns
includeNullValues
protected boolean includeNullValues()Returns
getSelectedColumn
public int getSelectedColumn()Returns
paintGlass
protected void paintGlass(Graphics g)Parameters
gGraphics- the graphics context
createColumnSortComparator
protected Comparator<Object> createColumnSortComparator(int column)Parameters
columnint- the column that’s sorted
Returns
sort
public void sort(int column, boolean ascending)Parameters
columnint- the column to sort
ascendingboolean- true to sort in ascending order
createCell
protected Component createCell(Object value, int row, int column, boolean editable)Parameters
valueObject- the new value object
rowint- row number, -1 for the header rows
columnint- column number
editableboolean- true if the cell is editable
Returns
initComponent
public void initComponent()deinitialize
public void deinitialize()getModel
public TableModel getModel()Returns
setModel
public void setModel(TableModel model)Parameters
modelTableModel- the new model
isDrawBorder
public boolean isDrawBorder()Returns
setDrawBorder
public void setDrawBorder(boolean drawBorder)Parameters
drawBorderboolean- the drawBorder to set
getInnerBorderMode
public int getInnerBorderMode()Returns
setInnerBorderMode
public void setInnerBorderMode(int innerBorder)Parameters
innerBorderint- one of the INNER_BORDER_* constants
shouldDrawInnerBorderAfterRow
protected boolean shouldDrawInnerBorderAfterRow(int row)Parameters
rowint- The row in question
Returns
setCollapseBorder
public void setCollapseBorder(boolean collapseBorder)Parameters
collapseBorderboolean- true to collapse (default), false for separate borders
setDrawEmptyCellsBorder
public void setDrawEmptyCellsBorder(boolean drawEmptyCellsBorder)Parameters
drawEmptyCellsBorderboolean- true to draw (default), false otherwise
setBorderSpacing
public void setBorderSpacing(int horizontal, int vertical)Parameters
horizontalint- The horizontal spacing
verticalint- The vertical spacing
getTitleAlignment
public int getTitleAlignment()Returns
setTitleAlignment
public void setTitleAlignment(int titleAlignment)Parameters
titleAlignmentint- the title alignment
getCellColumn
public int getCellColumn(Component cell)Parameters
cellComponent- the component representing the cell placed in the table
Returns
getCellRow
public int getCellRow(Component cell)Parameters
cellComponent- the component representing the cell placed in the table
Returns
getCellAlignment
public int getCellAlignment()Returns
setCellAlignment
public void setCellAlignment(int cellAlignment)Parameters
cellAlignmentint- the table cell alignment
isIncludeHeader
public boolean isIncludeHeader()Returns
setIncludeHeader
public void setIncludeHeader(boolean includeHeader)Parameters
includeHeaderboolean- the includeHeader to set
createCellConstraint
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column)Parameters
valueObject- the value of the cell
rowint- the table row
columnint- the table column
Returns
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
translateSortedRowToModelRow
public int translateSortedRowToModelRow(int row)Parameters
rowint- the row as it visually appears in the table or in the
createCellmethod
Returns
isSortSupported
public boolean isSortSupported()Returns
setSortSupported
public void setSortSupported(boolean sortSupported)Parameters
sortSupportedboolean- the sortSupported to set