Iterating Through Rows in Java Swing JTable

Applies to TestComplete 15.47, last modified on January 20, 2023

Iterating through grid rows means accessing rows in series, one by one. You may need to iterate through JTable rows if you need to locate a particular row in the grid, export grid data to a file or perform the same set of operations over each row.

To determine the number of grid rows, you can use the wRowCount property of the JTable object. Once you have determined the number of data rows in the grid, you can iterate through them in a loop. Since the numeration of grid rows is zero-based, the index of the first grid row is 0, and the index of the last row is wRowCount-1. On each loop iteration, you can perform the needed actions with the current row. For example, you can modify values in its cells or save them to a file. To learn how to obtain or modify grid cell values, see Obtaining and Setting Cell Values in Java Swing JTable.

TestComplete extends JTable's functionality with properties and methods of the JTable object only if the Java Control Support plugin is installed and enabled.

Below is an example that demonstrates how you can iterate through grid tables and rows and save grid data to an XML file.

Example

View description

JavaScript

function Main ()
{
  var p, Grid, FileName;

  // Obtains the grid object
  p = Sys.Process("javaw");
  Grid = p.SwingObject("JFrame", "SimpleTableDemo", 0, 1).SwingObject("JRootPane", "", 0).SwingObject("null.layeredPane").SwingObject("SimpleTableDemo", "", 0).SwingObject("JScrollPane", "", 0).SwingObject("JViewport", "", 0).SwingObject("JTable", "", 0);

  // Saves the grid data to a file
  FileName = "C:\\GridData.xml";
  ExportToXml (Grid, FileName);
  Log.File(FileName, "Exported grid data.");
}

// Exports the grid data to a file
function ExportToXml (Grid, FileName)
{
  Indicator.PushText ("Exporting the grid data to a file...");

  // Creates a text file and opens it for writing
  let Overwrite = true;
  let Unicode = true;
  let fso = getActiveXObject("Scripting.FileSystemObject");
  let XmlFile = fso.CreateTextFile (FileName, Overwrite, Unicode);

  // Writes the root tag
  XmlFile.WriteLine("<?xml version=\"1.0\"?>");
  XmlFile.WriteLine ("<grid>");

  ExportTable (Grid, XmlFile, "  ");

  // Closes the root tag
  XmlFile.WriteLine ("</grid>");
  // Closes the file
  XmlFile.Close();

  Indicator.PopText();
}

// Writes the grid table data to the specified file
function ExportTable (View, XmlFile, indent)
{

  // Exports column captions
  for (let i=0; i<View.wColumnCount; i++)
    XmlFile.WriteLine (indent + "  <column>" + ReplaceSpecialChars(View.wColumn(i)) + "</column>");

  // If the table is grouped, ...
    // Exports data rows
    ExportRows (View, XmlFile, indent + "  ");

  XmlFile.WriteLine (indent + "</table>");
}

function ExportRows (Level, XmlFile, indent)
{
  var CellValue, TextValue;

  // Iterates through data rows and exports their data
  for (let i=0; i<Level.wRowCount; i++)
  {
    XmlFile.WriteLine (indent + "<row>");
    for (let j=0; j<Level.wColumnCount; j++)
    {
      // Gets the cell value
      CellValue = Level.wValue(i, j);
      // Gets the text representation of the cell value
      if (equal(aqObject.GetVarType(CellValue), varDispatch))
        TextValue = CellValue.ToString().OleValue
      else
        TextValue = aqConvert.VarToStr(CellValue);
      XmlFile.WriteLine (indent + "  <cell>" + ReplaceSpecialChars(TextValue) + "</cell>");
    }

  }
}

// Replaces special XML characters in the specified string
function ReplaceSpecialChars (str)
{
  let s;
  s = aqString.Replace (str, "&", "&amp;", true);
  s = aqString.Replace (s, "<", "&lt;", true);
  s = aqString.Replace (s, ">", "&gt;", true);
  s = aqString.Replace (s, "\"", "&quot;", true);
  s = aqString.Replace (s, "'", "&apos;", true);
  return s;
}

JScript

function Main ()
{
  var p, Grid, FileName;

  // Obtains the grid object
  p = Sys.Process("javaw");
  Grid = p.SwingObject("JFrame", "SimpleTableDemo", 0, 1).SwingObject("JRootPane", "", 0).SwingObject("null.layeredPane").SwingObject("SimpleTableDemo", "", 0).SwingObject("JScrollPane", "", 0).SwingObject("JViewport", "", 0).SwingObject("JTable", "", 0);

  // Saves the grid data to a file
  FileName = "C:\\GridData.xml";
  ExportToXml (Grid, FileName);
  Log.File(FileName, "Exported grid data.");
}

// Exports the grid data to a file
function ExportToXml (Grid, FileName)
{
  Indicator.PushText ("Exporting the grid data to a file...");

  // Creates a text file and opens it for writing
  var Overwrite = true;
  var Unicode = true;
  var fso = new ActiveXObject ("Scripting.FileSystemObject");
  var XmlFile = fso.CreateTextFile (FileName, Overwrite, Unicode);

  // Writes the root tag
  XmlFile.WriteLine("<?xml version=\"1.0\"?>");
  XmlFile.WriteLine ("<grid>");

  ExportTable (Grid, XmlFile, "  ");

  // Closes the root tag
  XmlFile.WriteLine ("</grid>");
  // Closes the file
  XmlFile.Close();

  Indicator.PopText();
}

// Writes the grid table data to the specified file
function ExportTable (View, XmlFile, indent)
{
  var i;

  // Exports column captions
  for (i=0; i<View.wColumnCount; i++)
    XmlFile.WriteLine (indent + "  <column>" + ReplaceSpecialChars(View.wColumn(i)) + "</column>");

  // If the table is grouped, ...
    // Exports data rows
    ExportRows (View, XmlFile, indent + "  ");

  XmlFile.WriteLine (indent + "</table>");
}

function ExportRows (Level, XmlFile, indent)
{
  var i, j, CellValue, TextValue;

  // Iterates through data rows and exports their data
  for (i=0; i<Level.wRowCount; i++)
  {
    XmlFile.WriteLine (indent + "<row>");
    for (j=0; j<Level.wColumnCount; j++)
    {
      // Gets the cell value
      CellValue = Level.wValue(i, j);
      // Gets the text representation of the cell value
      if (aqObject.GetVarType(CellValue) == varDispatch)
        TextValue = CellValue.ToString().OleValue
      else
        TextValue = aqConvert.VarToStr(CellValue);
      XmlFile.WriteLine (indent + "  <cell>" + ReplaceSpecialChars(TextValue) + "</cell>");
    }

  }
}

// Replaces special XML characters in the specified string
function ReplaceSpecialChars (str)
{
  var s;
  s = aqString.Replace (str, "&", "&amp;", true);
  s = aqString.Replace (s, "<", "&lt;", true);
  s = aqString.Replace (s, ">", "&gt;", true);
  s = aqString.Replace (s, "\"", "&quot;", true);
  s = aqString.Replace (s, "'", "&apos;", true);
  return s;
}

Python

def Main ():

  # Obtains the grid object
  p = Sys.Process("javaw")
  Grid = p.SwingObject("JFrame", "SimpleTableDemo", 0, 1).SwingObject("JRootPane", "", 0).SwingObject("None.layeredPane").SwingObject("SimpleTableDemo", "", 0).SwingObject("JScrollPane", "", 0).SwingObject("JViewport", "", 0).SwingObject("JTable", "", 0)

  # Saves the grid data to a file
  FileName = "C:\\GridData.xml"
  ExportToXml (Grid, FileName)
  Log.File(FileName, "Exported grid data.")

# Exports the grid data to a file
def ExportToXml (Grid, FileName):
  Indicator.PushText ("Exporting the grid data to a file...")

  # Creates a text file and opens it for writing
  Overwrite = True
  Unicode = True
  fso = Sys.OleObject ['Scripting.FileSystemObject']
  XmlFile = fso.CreateTextFile (FileName, Overwrite, Unicode)

  # Writes the root tag
  XmlFile.WriteLine("<?xml version=\"1.0\"?>")
  XmlFile.WriteLine ("<grid>")

  ExportTable (Grid, XmlFile, "  ")

  # Closes the root tag
  XmlFile.WriteLine ("</grid>")
  # Closes the file
  XmlFile.Close()

  Indicator.PopText()

# Writes the grid table data to the specified file
def ExportTable (View, XmlFile, indent):

  # Exports column captions
  for i in range(0, View.wColumnCount-1):
    XmlFile.WriteLine (indent + "  <column>" + ReplaceSpecialChars(View.wColumn[i]) + "</column>")

  # If the table is grouped, ...
    # Exports data rows
    ExportRows (View, XmlFile, indent + "  ")

  XmlFile.WriteLine (indent + "</table>")

def ExportRows (Level, XmlFile, indent):

  # Iterates through data rows and exports their data
  for i in range(0, Level.wRowCount-1):
    XmlFile.WriteLine (indent + "<row>")
    for j in range(0, Level.wColumnCount-1):
      # Gets the cell value
      CellValue = Level.wValue[i, j]
      # Gets the text representation of the cell value
      if (aqObject.GetVarType(CellValue) == varDispatch):
        TextValue = CellValue.ToString().OleValue
      else:
        TextValue = aqConvert.VarToStr(CellValue)
      XmlFile.WriteLine (indent + "  <cell>" + ReplaceSpecialChars(TextValue) + "</cell>")

# Replaces special XML characters in the specified string
def ReplaceSpecialChars (str):
  s = aqString.Replace (str, "&", "&amp;", True)
  s = aqString.Replace (s, "<", "&lt;", True)
  s = aqString.Replace (s, ">", "&gt;", True)
  s = aqString.Replace (s, "\"", "&quot;", True)
  s = aqString.Replace (s, "'", "&apos;", True)
  return s

VBScript

Sub Main
  Dim p, Grid, FileName

  ' Obtains the grid object
  Set p = Sys.Process("javaw")
  Set Grid = p.SwingObject("JFrame", "SimpleTableDemo", 0, 1).SwingObject("JRootPane", "", 0).SwingObject("null.layeredPane").SwingObject("SimpleTableDemo", "", 0).SwingObject("JScrollPane", "", 0).SwingObject("JViewport", "", 0).SwingObject("JTable", "", 0)

  ' Saves the grid data to a file
  FileName = "C:\GridData.xml"
  Call ExportToXml (Grid, FileName)
  Call Log.File(FileName, "Exported grid data.")
End Sub

' Exports the grid data to a file
Sub ExportToXml (Grid, FileName)
  Dim fso, XmlFile, Overwrite, Unicode

  Indicator.PushText ("Exporting the grid data to a file...")

  ' Creates a text file and opens it for writing
  Overwrite = True
  Unicode = True
  Set fso = CreateObject ("Scripting.FileSystemObject")
  Set XmlFile = fso.CreateTextFile (FileName, Overwrite, Unicode)

  ' Writes the root tag
  Call XmlFile.WriteLine("<?xml version=""1.0""?>")
  XmlFile.WriteLine ("<grid>")

  Call ExportTable (Grid, XmlFile, "  ")

  ' Closes the root tag
  XmlFile.WriteLine ("</grid>")
  ' Closes the file
  XmlFile.Close

  Indicator.PopText
End Sub

' Writes the grid table data to the specified file
Sub ExportTable (View, XmlFile, indent)
  Dim i

  ' Exports column captions
  For i = 0 To View.wColumnCount-1
    XmlFile.WriteLine (indent & "  <column>" & ReplaceSpecialChars(View.wColumn(i)) & "</column>")
  Next

  ' Exports data rows
  Call ExportRows (View, XmlFile, indent & "  ")
  XmlFile.WriteLine (indent & "</table>")
End Sub

Sub ExportRows (Level, XmlFile, indent)
  Dim i, j, CellValue, TextValue

  ' Iterates through data rows and exports their data
  For i = 0 To Level.wRowCount-1
    XmlFile.WriteLine (indent & "<row>")
    For j = 0 To Level.wColumnCount-1
      ' Gets the cell value and its text representation
      If aqObject.GetVarType(Level.wValue(i, j)) = varDispatch Then
        Set CellValue = Level.wValue(i, j)
        TextValue = CellValue.ToString.OleValue
      Else
        CellValue = Level.wValue(i, j)
        TextValue = aqConvert.VarToStr(CellValue)
      End If
      XmlFile.WriteLine (indent & "  <cell>" & ReplaceSpecialChars(TextValue) & "</cell>")
    Next
  Next
End Sub

' Replaces special XML characters in the specified string
Function ReplaceSpecialChars (str)
  Dim s
  s = aqString.Replace (str, "&", "&amp;", True)
  s = aqString.Replace (s, "<", "&lt;", True)
  s = aqString.Replace (s, ">", "&gt;", True)
  s = aqString.Replace (s, """", "&quot;", True)
  s = aqString.Replace (s, "'", "&apos;", True)
  ReplaceSpecialChars = s
End Function

DelphiScript

procedure ExportToXml (Grid, FileName); forward;
procedure ExportTable (View, XmlFile, indent); forward;
procedure ExportRows (Level, XmlFile, indent); forward;
function ReplaceSpecialChars (str); forward;

procedure Main;
var p, Grid, FileName : OleVariant;
begin
  // Obtains the grid object
  p := Sys.Process('javaw');
  Grid := p.SwingObject('JFrame', 'SimpleTableDemo', 0, 1).SwingObject('JRootPane', '', 0).SwingObject('null.layeredPane').SwingObject('SimpleTableDemo', '', 0).SwingObject('JScrollPane', '', 0).SwingObject('JViewport', '', 0).SwingObject('JTable', '', 0);

  // Saves the grid data to a file
  FileName := 'C:\GridData.xml';
  ExportToXml (Grid, FileName);
  Log.File(FileName, 'Exported grid data.');
end;

// Exports the grid data to a file
procedure ExportToXml (Grid, FileName);
var fso, XmlFile, Overwrite, Unicode : OleVariant;
begin
  Indicator.PushText ('Exporting the grid data to a file...');

  // Creates a text file and opens it for writing
  Overwrite := true;
  Unicode := true;
  fso := Sys.OleObject ('Scripting.FileSystemObject');
  XmlFile := fso.CreateTextFile (FileName, Overwrite, Unicode);

  // Writes the root tag
  XmlFile.WriteLine('<?xml version="1.0"?>');
  XmlFile.WriteLine ('<grid>');

  ExportTable (Grid, XmlFile, '  ');

  // Closes the root tag
  XmlFile.WriteLine ('</grid>');
  // Closes the file
  XmlFile.Close;

  Indicator.PopText;
end;

// Writes the grid table data to the specified file
procedure ExportTable (View, XmlFile, indent);
var i : OleVariant;
begin
  // Exports column captions
  for i := 0 to View.wColumnCount-1 do
    XmlFile.WriteLine (indent + '  <column>' + ReplaceSpecialChars(View.wColumn[i]) + '</column>');

    // Exports data rows
    ExportRows (View, XmlFile, indent + '  ');

  XmlFile.WriteLine (indent + '</table>');
end;

procedure ExportRows (Level, XmlFile, indent);
var i, j, CellValue, TextValue : OleVariant;
begin
  // Iterates through data rows and exports their data
  for i := 0 to Level.wRowCount-1 do
  begin
    XmlFile.WriteLine (indent + '<row>');
    for j := 0 to Level.wColumnCount-1 do
    begin
      // Gets the cell value
      CellValue := Level.wValue[i, j];
      // Gets the text representation of the cell value
      if aqObject.GetVarType(CellValue) = varDispatch then
        TextValue := CellValue.ToString.OleValue
      else
        TextValue := aqConvert.VarToStr(CellValue);
      XmlFile.WriteLine (indent + '  <cell>' + ReplaceSpecialChars(TextValue) + '</cell>');
    end;

  end;
end;

// Replaces special XML characters in the specified string
function ReplaceSpecialChars (str);
var s : OleVariant;
begin
  s := aqString.Replace (str, '&', '&amp;', true);
  s := aqString.Replace (s, '<', '&lt;', true);
  s := aqString.Replace (s, '>', '&gt;', true);
  s := aqString.Replace (s, '''', '&quot;', true);
  s := aqString.Replace (s, '"', '&apos;', true);
  Result := s;
end;

C++Script, C#Script

function Main ()
{
  var p, Grid, FileName;

  // Obtains the grid object
  p = Sys["Process"]("javaw");
  Grid = p["SwingObject"]("JFrame", "SimpleTableDemo", 0, 1)["SwingObject"]("JRootPane", "", 0)["SwingObject"]("null.layeredPane")["SwingObject"]("SimpleTableDemo", "", 0)["SwingObject"]("JScrollPane", "", 0)["SwingObject"]("JViewport", "", 0)["SwingObject"]("JTable", "", 0);

  // Saves the grid data to a file
  FileName = "C:\\GridData.xml";
  ExportToXml (Grid, FileName);
  Log["File"](FileName, "Exported grid data.");
}

// Exports the grid data to a file
function ExportToXml (Grid, FileName)
{
  Indicator["PushText"]("Exporting the grid data to a file...");

  // Creates a text file and opens it for writing
  var Overwrite = true;
  var Unicode = true;
  var fso = new ActiveXObject ("Scripting.FileSystemObject");
  var XmlFile = fso["CreateTextFile"](FileName, Overwrite, Unicode);

  // Writes the root tag
  XmlFile["WriteLine"]("<?xml version=\"1.0\"?>");
  XmlFile["WriteLine"]("<grid>");

  ExportTable (Grid, XmlFile, "  ");

  // Closes the root tag
  XmlFile["WriteLine"]("</grid>");
  // Closes the file
  XmlFile["Close"]();

  Indicator["PopText"]();
}

// Writes the grid table data to the specified file
function ExportTable (View, XmlFile, indent)
{
  var i;

  // Exports column captions
  for (i=0; i<View["wColumnCount"]; i++)
    XmlFile["WriteLine"](indent + "  <column>" + ReplaceSpecialChars(View["wColumn"](i)) + "</column>");

    // Exports data rows
    ExportRows (View, XmlFile, indent + "  ");

  XmlFile["WriteLine"](indent + "</table>");
}

function ExportRows (Level, XmlFile, indent)
{
  var i, j, CellValue, TextValue;

  // Iterates through data rows and exports their data
  for (i=0; i<Level["wRowCount"]; i++)
  {
    XmlFile["WriteLine"](indent + "<row>");
    for (j=0; j<Level["wColumnCount"]; j++)
    {
      // Gets the cell value
      CellValue = Level["wValue"](i, j);
      // Gets the text representation of the cell value
      if (aqObject["GetVarType"](CellValue) == varDispatch)
        TextValue = CellValue["ToString"]()["OleValue"]
      else
        TextValue = aqConvert["VarToStr"](CellValue);
      XmlFile["WriteLine"](indent + "  <cell>" + ReplaceSpecialChars(TextValue) + "</cell>");
    }

  }
}

// Replaces special XML characters in the specified string
function ReplaceSpecialChars (str)
{
  var s;
  s = aqString["Replace"](str, "&", "&amp;", true);
  s = aqString["Replace"](s, "<", "&lt;", true);
  s = aqString["Replace"](s, ">", "&gt;", true);
  s = aqString["Replace"](s, "\"", "&quot;", true);
  s = aqString["Replace"](s, "'", "&apos;", true);
  return s;
}

See Also

Working With Java Swing JTable
Obtaining and Setting Cell Values in Java Swing JTable
Searching for Records in Java Swing JTable
wRowCount Property (Grid Controls)

Highlight search results