Package totalcross.ui

Class Grid

  • All Implemented Interfaces:
    Scrollable

    public class Grid
    extends Container
    implements Scrollable
    This is a common grid component. The features are:
    • Vertical scrollbar to scroll up and down the information on the grid
    • Horizontal scrolling in case the columns widths are greater than the parent container's width
    • An easy to use interface for adding/removing information to the grid
    • An optional check column, which is a column that is clickable, marking an specific line as checked/unchecked. This is usefull if you want the user to be able to mark multiple lines displayed on the grid
    • Columns can be resized so that the user can see all the information displayed in a given column
    • Style configuration, you can set the color of captions boxes all the way thru the stripes colors and vertical line types. The grid is compatible with all user interface styles (Flat, WinCE, etc... )
    • The GridEvent class contains the events generated by the grid.
    • A column may be marked as editable. In this case, an Edit will be placed in the currently focused cell. A column can also have choices (ComboBox).
    • A column can also have a ComboBox associated.
    • The columns can be sorted by clicking in the title.
    • If the text is bigger than the size of the column, you can click and hold in the cell to display a tooltip with the full text.
    • You can customize cell back and fore colors, enabled state and choices by using the CellController class.
    • Clicking in the column's caption will sort in ascending order; clicking on it again sorts on descending order.
    • It is possible to assign a DataSource to a Grid, making the elements be fetched on demand.
    • A column with size 0 is not displayed, so you can use it to store in the grid important information, for example the rowid of a table.
    Here's an example:
         Rect r = getClientRect();
    
         String []gridCaptions = {" WPT "," HDG "," DST "," ETE "," FUEL "};
         int gridWidths[] =
         {
          -25, // negative numbers are percentage of width
          fm.stringWidth(" 000 "),
          -25,
          -20,
          -20,
         };
         int gridAligns[] = { LEFT, CENTER, RIGHT, CENTER, RIGHT };
         grid = new Grid(gridCaptions, gridWidths, gridAligns, false);
         add(grid, LEFT+3,TOP+3,r.width/2,r.height/2);
         grid.secondStripeColor = Color.getRGB(235,235,235);
    
         String[][] data = new String[][]
         {
            {"0AAAA","000","000.0","00:00","00.0"},
            {"1BBBB","111","111.1","11:11","11.1"},
            {"2CCCC","222","222.2","22:22","22.2"},
            {"3DDDD","333","333.3","33:33","33.3"},
            {"4EEEE","444","444.4","44:44","44.4"},
            {"5FFFF","555","555.5","55:55","55.5"},
         };
         grid.setItems(data);
     
    This will create a grid with the given captions, column widths, information alignment and a check column.

    Don't forget to take a look at tc.samples.ui.grid.GridTest.

    Also consider using the ListContainer instead of Grid if you're using devices with big screens. See the UIGadgets sample, click menu / Tests2 / ListContainer.

    Since:
    SuperWaba 5.5
    • Field Detail

      • flick

        protected Flick flick
        The Flick object listens and performs flick animations on PenUp events when appropriate.
      • disabledFlick

        protected Flick disabledFlick
      • VERT_LINE

        public static final int VERT_LINE
        Draws a solid vertical line. Used in the property verticalLineStyle
        See Also:
        Constant Field Values
      • VERT_DOT

        public static final int VERT_DOT
        Draws a dotted vertical line. Used in the property verticalLineStyle
        See Also:
        Constant Field Values
      • VERT_NONE

        public static final int VERT_NONE
        Draws no vertical lines. Used in the property verticalLineStyle
        See Also:
        Constant Field Values
      • ALL_CHECKED

        public static final int ALL_CHECKED
        When the user clicks on the header check to check all, a CHECK_CHANGED_EVENT is dispatched, and the row is set as ALL_CHECKED.
        See Also:
        Constant Field Values
      • ALL_UNCHECKED

        public static final int ALL_UNCHECKED
        When the user clicks on the header check, to uncheck all, a CHECK_CHANGED_EVENT is dispatched, and the row is set as ALL_UNCHECKED.
        See Also:
        Constant Field Values
      • drawCheckBox

        public boolean drawCheckBox
        Set this to false if you dont want the check column to have the rect underneath the check mark
      • checkColor

        public int checkColor
        Check color. Defaults to black.
      • disableSort

        public boolean disableSort
        Set to true to disable sorting when clicking in the column's header.
      • enableColumnResize

        public boolean enableColumnResize
        Set this to false if you dont want to let the user resize the columns
      • columnResizeMargin

        public static int columnResizeMargin
        How many pixels are used to define the place where the column will be resized. Defaults to 3 on pen devices, and 5 on touch devices (must be ODD!)
        Since:
        TotalCross 1.22
      • captions

        public java.lang.String[] captions
        The column captions. Can be directly assigned, but always make sure it has the same number of elements of the widths array, set with the setWidths method.
      • firstStripeColor

        public int firstStripeColor
        first stripe color. WHITE by default.
      • secondStripeColor

        public int secondStripeColor
        second stripe color. BRIGHT by default
      • highlightColor

        public int highlightColor
        The color of the selected (highlighted) row. DARK by default
      • captionsBackColor

        public int captionsBackColor
        Sets the caption's box background color. BRIGHT by default
      • drawHighlight

        public boolean drawHighlight
        Set to false do don't let the highlighted (selected) row be drawn.
        Since:
        TotalCross 1.39
      • verticalLineStyle

        public int verticalLineStyle
        Sets the vertical line style of the grid. VERT_DOT by default.
        See Also:
        VERT_LINE, VERT_DOT, VERT_NONE
      • selectedLine

        protected int selectedLine
        The current selected line, or -1 if none.
      • linesPerPage

        protected int linesPerPage
        How many lines fits in a page
      • oldCellText

        public java.lang.String oldCellText
        The text that was in the cell before the user had editted it.
      • canClickSelectAll

        public boolean canClickSelectAll
        Set to false to disable the click on the check column of the captions to select all and unselect all
      • boldCheck

        public boolean boldCheck
        Set it to true to draw a bold check
      • tip

        public ToolTip tip
        The tooltip used to display a column's text when it exceeds the column width. You can directly customize the tooltip.
      • extraHorizScrollButtonHeight

        public int extraHorizScrollButtonHeight
        The extra height of the horizontal scroll buttons. Defaults 2 in 160x160 or a multiple of it in other resolutions.
        See Also:
        ListBox.EXTRA_HEIGHT_FACTOR
      • lastStartingRow

        public int lastStartingRow
        Stores the last line that was requested from the current data source. The last lines retrieved will be cached to prevent requesting the same data. If you want to ensure that the data will be fetched again, set this member to -1 in getItems.
        Since:
        TotalCross 1.0 beta 5
      • useHorizontalScrollBar

        public static boolean useHorizontalScrollBar
        Set to true before constructing the Grids to use an horizontal scrollbar instead of the two left/right buttons. Note that this member is static so it will affect all Grids created afterwards, unless you reset it to false.
        Since:
        TotalCross 1.01
      • currencyDecimalPlaces

        public int[] currencyDecimalPlaces
        Used to show a given (set of) column(s) formatted as currency. You must assign this with an array with the column count, and place the wanted number of decimal places, or -1 if you don't want to format it. Note that the original value must be already formatted with the wanted number of decimal places, and also that only the displayed value is changed; the internal value will remain without formatting. Example:
         Grid g = new Grid(new String[]{"Name","Age","Salary"},false);
         g.currencyDecimalPlaces = new int[]{-1,-1,2}; // ignore name and age, and format salary with 2 decimal places.
         
      • enableSelectDisabledCell

        public boolean enableSelectDisabledCell
        Set to false to disallow the selection of a row if the selected cell is disabled (via CellController).
        Since:
        TotalCross 1.2
      • lineScroll

        public boolean lineScroll
        Set to true to enable navigation per line instead of per page when in non-penless mode. By default, in pen mode (devices with touch-screen), when the user press up/down, the grid is scrolled one page at a time. Setting this flag to true makes it scroll a line at a time.
        Since:
        TotalCross 1.23
      • borderGap

        public int borderGap
        Defines the border gap when using CellController.getBackColor. Setting it to something bigger than 0 will make a space between the cells.
        Since:
        TotalCross 1.24
      • aligns

        public int[] aligns
        The aligns that are used in the constructor. You may change them after the constructor is called.
      • titleMayBeClipped

        public boolean titleMayBeClipped
        When the width of a title is greater than the width you specified for a the column, the title's width is used instead. Set this flag to true to disable this behaviour.
        Since:
        TotalCross 1.39
      • captionImages

        public Image[] captionImages
        A way to mix Images and Strings at the caption. The array's length must be the same of the caption's passed in the constructor, but the indices that are an image will have it drawn. For example:
         String[] tits = {"","Add","Minus",""};
         captionImages = {img1, null,null, img2};
         
        Since:
        TotalCross 3.1
      • controls

        protected Control[] controls
    • Constructor Detail

      • Grid

        public Grid​(java.lang.String[] captions,
                    int[] widths,
                    int[] aligns,
                    boolean checkEnabled)
        This will create a grid with the given captions, column widths, information alignment and an optional multi-selection check column so that the user can select multiple lines of the grid
        Parameters:
        captions - Captions for the columns. Cannot be null!
        widths - Widths of the columns. If the total width is less than the grid's width, the last column will fill until the grid width. If null, the caption widths will be computed and used as the row width. If a negative value is passed, it will be computed as a percentage against the Grid's width.
        aligns - Alignment of information on the given column. If null, all aligns will be LEFT.
        checkEnabled - True if you want the multi-selection check column, false otherwise
      • Grid

        public Grid​(java.lang.String[] captions,
                    boolean checkEnabled)
        This will create a grid with the given captions and an optional multi-selection check column so that the user can select multiple lines of the grid. The widths will be computed as the width of the grid captions and the alignment will be all LEFT.
        Parameters:
        captions - Captions for the columns
        checkEnabled - True if you want the multi-selection check column, false otherwise
    • Method Detail

      • flickStarted

        public boolean flickStarted()
        Description copied from interface: Scrollable
        Called when the flick animation is started.
        Specified by:
        flickStarted in interface Scrollable
      • flickEnded

        public void flickEnded​(boolean atPenDown)
        Description copied from interface: Scrollable
        Called when the flick animation is ended.
        Specified by:
        flickEnded in interface Scrollable
        Parameters:
        atPenDown - Flag indicating if the animation ended due to a pendown event.
      • canScrollContent

        public boolean canScrollContent​(int direction,
                                        java.lang.Object target)
        Description copied from interface: Scrollable
        Checks if there is room to flick this container in the given direction.
        Specified by:
        canScrollContent in interface Scrollable
        Parameters:
        direction - The direction we want to flick given by one of the following constants:
        target - The target of the series of PEN events that triggered this flick attempt.
        Returns:
        true if the container can flick in the indicated direction.
      • scrollContent

        public boolean scrollContent​(int dx,
                                     int dy,
                                     boolean fromFlick)
        Description copied from interface: Scrollable
        Performs a relative move.
        Specified by:
        scrollContent in interface Scrollable
        Parameters:
        dx - The relative amount of pixels to move in the X axis.
        dy - The relative amount of pixels to move in the Y axis.
      • wasScrolled

        public boolean wasScrolled()
        Description copied from interface: Scrollable
        Returns true if the control was scrolled since last pen down
        Specified by:
        wasScrolled in interface Scrollable
      • getFlick

        public Flick getFlick()
        Description copied from interface: Scrollable
        Returns the current flick object.
        Specified by:
        getFlick in interface Scrollable
      • getScrollPosition

        public int getScrollPosition​(int direction)
        Description copied from interface: Scrollable
        Returns the current position given the direction. Used on page scrolls.
        Specified by:
        getScrollPosition in interface Scrollable
      • setCellController

        public void setCellController​(Grid.CellController cc)
        Sets the CellController instance for this grid. Read the javadocs of the top of this page for more information.
        Since:
        SuperWaba 5.8
        See Also:
        Grid.CellController
      • setColumnWidth

        public void setColumnWidth​(int col,
                                   int newWidth)
        Sets the column width of the given column. Positive values are used as pixels, negative values represent percentage of the grid's width and 0 hides the column.
        Since:
        TotalCross 1.15
      • getColumnWidths

        public int[] getColumnWidths()
        Returns an array with the current column widths, not the original ones passed in the constructor. Changing these values will NOT change the column's width
        Since:
        TotalCross 1.15
        See Also:
        setColumnWidth(int, int)
      • setColumnEditable

        public Edit setColumnEditable​(int col,
                                      boolean editable)
        Sets the given column as an editable one. Note that setting an editable column as not editable will remove all its formats. Returns the previous Edit or the new one, so you can easily change its formats. Important: this must be called AFTER the grid has set its bounds.
      • isColumnEditable

        public boolean isColumnEditable​(int col)
        Returns true if the given column is editable.
        Since:
        TotalCross 1.39
      • setColumnChoices

        public ComboBoxDropDown setColumnChoices​(int col,
                                                 java.lang.String[] choices)
        Makes the given column ComboBox-like. The given choice array is used to create a PopList that is shown when the user clicks on the column. Note that calling this method removes any Edit assigned to this column. You can change dynamically the choices by extending the CellController class.
        Parameters:
        col - The column to set as a ComboBox column
        choices - The choices that will be displayed. Passing a null value removes any ComboBox assigned to the column.
        Since:
        SuperWaba 5.7
        See Also:
        setCellController(totalcross.ui.Grid.CellController)
      • onFontChanged

        protected void onFontChanged()
        Description copied from class: Control
        Called after a setFont
        Overrides:
        onFontChanged in class Control
      • setItems

        public void setItems​(java.lang.String[][] items)
        Sets the grid items to be displayed. Note that it needs to be conforming to the numbers of columns that the grid currently have. This method removes any assigned datasource. The strings inside the matrix cannot be null, If items is null, the grid will remain empty.
      • setDataSource

        public void setDataSource​(Grid.DataSource ds,
                                  int nrItems)
        Sets the data source of this grid to be the given one. Note that when using data sources, the add, remove, insert, etc methods CANNOT BE USED. A data source is mostly used to assign a ResultSet to it, so its nonsense any data modification. Note that the scroll is made not live scrolling to speedup data retrieval.
        Since:
        SuperWaba 5.7
      • add

        public void add​(java.lang.String[] item)
        Add a new line to the end of the grid. Its up to the user to call Window.needsPaint = true afterwards. This method does not work if there's a datasource assigned.
        Parameters:
        item - string containing the information of the row
      • add

        public void add​(java.lang.String[] item,
                        int row)
        Add a new line at the given index position of the grid. Its up to the user to call Window.needsPaint = true afterwards. This method does not work if there's a datasource assigned.
        Parameters:
        item - string containing the information of the row
        row - index position to insert the row in
      • add

        public void add​(java.lang.String[][] items)
        Appends the give lines at the end of the grid.
        Its up to the user to call Window.needsPaint = true afterwards. This method does not work if there's a datasource assigned.
        Parameters:
        items - the lines to be appended to the grid.
        Since:
        TotalCross 1.2
      • replace

        public void replace​(java.lang.String[] item,
                            int row)
        Replace a given line by the specified by its index with the supplied one. This method does not work if there's a datasource assigned.
        Parameters:
        item - String containing the information of the new line
        row - Index position to insert the row in
      • move

        public boolean move​(int row,
                            boolean up)
        Move the items at given indexes.
        Since:
        TotalCross 1.53
      • del

        public boolean del​(int row)
        Remove the given line index from the grid. This method does not work if there's a datasource assigned.
      • getCellText

        public java.lang.String getCellText​(int row,
                                            int col)
        Returns the text's column of the given row number. If the grid has a check column, col must start from 1.
      • getSelectedItem

        public java.lang.String[] getSelectedItem()
        Get the information on the currently selected line. Any changes made into the returned array is applied back to the grid automatically (because it holds the grid's data).
      • getSelectedIndex

        public int getSelectedIndex()
        Get the index of the currently selected row, or -1 if none is selected.
      • setChecked

        public void setChecked​(int row,
                               boolean check)
        Checks or unchecks the given index based on the second argument. This method only works with a grid that has checks and repaint must be called.
      • isChecked

        public boolean isChecked​(int row)
        Check if a given row is checked
      • getItemsVector

        public Vector getItemsVector()
        Return a vector containing all information inside the grid. Note that if a datasource is assigned, this method returns null.
      • getItem

        public java.lang.String[] getItem​(int row)
        Returns the line corresponding to the given index. This method works with or without a datasource.
      • refreshDataSource

        public void refreshDataSource()
        Causes a refresh to be made in the items of the datasource.
        Since:
        TotalCross 1.01
      • scrollTo

        public void scrollTo​(int row)
        Scrolls the grid to the given row.
      • onColorsChanged

        protected void onColorsChanged​(boolean colorsChanged)
        Description copied from class: Control
        Called after a setEnabled, setForeColor and setBackColor and when a control has been added to a Container. If colorsChanged is true, it was called from setForeColor/setBackColor/Container.add; otherwise, it was called from setEnabled
        Overrides:
        onColorsChanged in class Container
      • setNinePatch

        public void setNinePatch​(Image img,
                                 int corner,
                                 int side)
        Description copied from class: Control
        Set the NinePatch of the control. This is used to draw the background image.
        Overrides:
        setNinePatch in class Control
        Parameters:
        img - The image to make the NinePatch. The image must be on a NinePatch format.
        corner - The size, in pixels, of the NinePatch's corner
        side - The size, in pixels, of the NinePatch's side.
      • setNinePatchCaption

        public void setNinePatchCaption​(Image img,
                                        int corner,
                                        int side)
      • initUI

        public void initUI()
        Description copied from class: Container
        Called to initialize the User Interface of this container. This differs from the onAddAgain method by that this method is called only once, at the first time the control is added to the parent. When the container is being setup, the initUI method is called; then, the onAddAgain is called every time the container is added again.
        Overrides:
        initUI in class Container
      • getPreferredWidth

        public int getPreferredWidth()
        If all widths (passed in constructor) are positive (ie, not a percentage), then it will use the sum as the preferred width.
        Overrides:
        getPreferredWidth in class Control
      • getPreferredHeight

        public int getPreferredHeight()
        Description copied from class: Control
        Returns the preferred height of this control.
        Overrides:
        getPreferredHeight in class Control
      • onBoundsChanged

        protected void onBoundsChanged​(boolean screenChanged)
        Description copied from class: Control
        Called after a setRect.
        Overrides:
        onBoundsChanged in class Control
        Parameters:
        screenChanged - If the bounds were changed due to a screen change (rotation, collapse)
      • removeAllElements

        public void removeAllElements()
        Remove all elements from the grid, leaving it blank. Removes any assigned datasource.
      • clear

        public void clear()
        Selects the clearValueInt row, which defaults to -1.
        Overrides:
        clear in class Container
      • markAll

        public void markAll​(boolean check)
        Checks or unchecks all rows in this grid.
        Since:
        TotalCross 1.2
      • horizontalScroll

        public boolean horizontalScroll​(boolean toLeft)
        Scrolls the grid horizontaly as needed
      • setCellText

        public void setCellText​(int row,
                                int col,
                                java.lang.String text)
        Sets the text of a column. If the grid has a check column, col must start from 1.
        Since:
        SuperWaba 5.8
      • onEvent

        public void onEvent​(Event e)
        Description copied from class: Control
        Called to process key, pen, control and other posted events.
        Overrides:
        onEvent in class Control
        Parameters:
        e - the event to process
        See Also:
        Event, KeyEvent, PenEvent
      • qsort

        public void qsort​(int col,
                          boolean ascending)
        Performs a quicksort in the items of the given column in the given order. This method does not work if there's a datasource assigned.
        Since:
        TotalCross 1.15
      • qsort

        public void qsort​(int col)
        Performs a quicksort in the items of the given column. This method does not work if there's a datasource assigned.
      • setSelectedIndex

        public void setSelectedIndex​(int row)
        Sets the selected row index to the given one. Note: if this grid has checks, the selected line is used to scroll to mark the line that may be checked; if the grid does not have checks, then it acts like a normal selected line.
      • size

        public int size()
        Returns the number of lines in this grid
      • reposition

        public void reposition()
        Repositions this control in the screen.
        Overrides:
        reposition in class Control
      • getFocusableControls

        public void getFocusableControls​(Vector v)
        Description copied from class: Container
        Get a list of child controls of this container which are focus candidates
        Overrides:
        getFocusableControls in class Container
        Parameters:
        v - A vector into which to add the focus candidates.
      • handleGeographicalFocusChangeKeys

        public Control handleGeographicalFocusChangeKeys​(KeyEvent ke)
        Description copied from class: Control
        Used by the main event loop to give the currently focused control an opportunity to act directly on the KeyEvent.
        Overrides:
        handleGeographicalFocusChangeKeys in class Control
        Parameters:
        ke - The KeyEvent to be processed
        Returns:
        The control that should get focus as a result of this KeyEvent. Null if this control did not handle the KeyEvent.
        See Also:
        Settings.geographicalFocus
      • setVisibleLines

        public void setVisibleLines​(int visibleLines)
        Sets the number of visible lines (excluding the caption), used to make PREFERRED height return the given number of lines as the grid height. This method must be called before setRect.
        Since:
        TotalCross 1.0
      • getDataSource

        public Grid.DataSource getDataSource()
        Returns the DataSource assigned for this grid, or null if there are none.
      • getCheckCount

        public int getCheckCount()
        Returns the number of items checked.
        Since:
        TotalCross 1.27
      • setImage

        public void setImage​(java.lang.String tag,
                             Image image)
                      throws ImageException
        Sets an image to be used in the Grid. You must use the same tag in the grid's item. The image will be resized to the current font's height, so be sure to call this method AFTER the font is set (or after the grid is added to the container).
              try
              {
                 String []gridCaptions = {"Image", "Name", "Details" };
                 int gridWidths[] = {-25, -50, -25};
                 int gridAligns[] = {CENTER,LEFT,LEFT};
                 String items[][] =
                 {
                    {"@foto1", "Car number one", "good car"},
                    {"@foto2", "Car number two", "great car"},
                 };
          
                 Grid grid = new Grid(gridCaptions, gridWidths, gridAligns, false);
                 add(grid, LEFT+5, AFTER+2, FILL-10, PREFERRED);
                 grid.setImage("@foto1",new Image("foto1.jpg"));
                 grid.setImage("@foto2",new Image("foto2.jpg"));
                 grid.setItems(items);
              }
              catch (Exception ee)
              {
                 MessageBox.showException(ee,true);
              }
              
        Throws:
        ImageException
        Since:
        TotalCross 1.53.
      • moveFocusToNextControl

        public Control moveFocusToNextControl​(Control c,
                                              boolean forward)
        Traverse throught the Edits of this Grid.
        Overrides:
        moveFocusToNextControl in class Container
        Returns:
        The selected control or null if none was found.
      • disableFlick

        public void disableFlick()
        Disables the 'flick' behaviour from this scroll container. This is useful when you have small scrollable containers and are facing usability problems. We recommend leaving the flick behavior on for large scrollable surfaces, with many items. All scroll containers have the flick behaviour on by default. If disabled, this behavior can be reenabled using the 'enableFlick' method.
        See Also:
        enableFlick()
      • enableFlick

        public void enableFlick()
        Reenables the 'flick' behaviour of this container. @see disableFlick