0

As described in tuytuys question i get data from a jTable to an 2d array.

Object [][] newarr = null;

newarr = getTableData(jTable);

the code of getTableData:

public Object[][] getTableData (JTable table) {
    DefaultTableModel dtm = (DefaultTableModel) table.getModel();
    int nRow = dtm.getRowCount();
    int nCol = dtm.getColumnCount();
    Object[][] tableData = new Object[nRow][nCol];
    for (int i = 0 ; i < nRow ; i++){
        for (int j = 0; j < nCol ; j++)
        tableData[i][j] = dtm.getValueAt(i,j);
    }
    System.out.println(Arrays.asList(tableData));
    return tableData;
}

The newarr 2d object array contains the data of the jTable, I have debugged it.

The question is: How may I get the string data from the 2d object array in which is the string from the cell of the jTable?

String s = newarr[0][1].toString();

for example is not working.

4
  • what do you mean by is not working. Commented Feb 28, 2019 at 6:46
  • "is not working". actually, it is, but maybe it doesn't produce the output you want, because it is the Object class's toString method you use, or you get a NPE somewhere Commented Feb 28, 2019 at 6:46
  • 3
    try to explicitly cast your object with (String) newarr[0][1] instead of using toString() method from Object class Commented Feb 28, 2019 at 6:50
  • Yes you are allright. "Not working" was not exact enough. I need the string which was in the jTable. Sorry! Commented Feb 28, 2019 at 6:59

1 Answer 1

1

I think what you want to do is cast Object to String. To do that just make sure that newarr[0][1] is instanceof String. Example code using ? insted of if statement. What I did is basically check if newarr[0][1] is String then assign it to s else assign "":

String s = (newarr[0][1] instanceof String) ? (String)newarr[0][1] : "";
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.