-4

I want to check if the value does exist or not in Tree when trying to add node from Tree. The value does not match in the case that I got Object instead of String.

Here is the action code for calling existsInTable()

     try {
        DefaultMutableTreeNode selectedElement = (DefaultMutableTreeNode) TestTree.getSelectionPath().getLastPathComponent();
        Object[] row = {selectedElement};
        DefaultTableModel model = (DefaultTableModel) myTests_table.getModel();

        if (selectedElement.isLeaf() == true && existsInTable(myTests_table, row) == false) {
            model.addRow(row);
        } else {
            JOptionPane.showMessageDialog(null, "Please Choose Test name!", "Error", JOptionPane.WARNING_MESSAGE);
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error");
    }

Here are the check method

    public boolean existsInTable(JTable table, Object[] testname) {
    int row = table.getRowCount();
       for (int i = 0; i < row; i++) {
        String str = "";
        str = table.getValueAt(i, 0).toString();
        if (testname.equals(str)) {
            System.out.println(str);
            JOptionPane.showMessageDialog(null, "data alreadyexist.", "message", JOptionPane.PLAIN_MESSAGE);
            return true;
        }
    }
    return false;

}
the result is this : [Ljava.lang.Object;@11da1f8     
but it should be   : Test
trashgod
  • 203,806
  • 29
  • 246
  • 1,045

1 Answers1

2

If you add an instance of Object to your TableModel, that is what getValueAt() will return. Given an Object, the result returned by toString() is entirely expected—"a string consisting of the name of the class of which the object is an instance, the at-sign character @, and the unsigned hexadecimal representation of the hash code of the object."

Looking closer, you appear to have added an array of Object instances. Given a default table model,

DefaultTableModel model = new DefaultTableModel(1, 1);

the following lines

model.setValueAt(new Object[1], 0, 0);
System.out.println(model.getValueAt(0, 0));

produce this output:

[Ljava.lang.Object;@330bedb4

To see a string, such as "Test", add a corresponding instance of String to your TableModel:

model.setValueAt("Test", 0, 0);
System.out.println(model.getValueAt(0, 0));

which produces the desired output:

Test

For best results, verify that your implementation of getColumnClass() is compatible, as suggested in How to Use Tables: Concepts: Editors and Renderers.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Thanks for reply,,, actually my date comes from DB, could u please make this command clear model.setValueAt("Test", 0, 0); How to use it with daynamic data – محمد عويضات Mar 04 '16 at 15:33
  • Because they are are conveniently `Comparable`, use `java.sql.Date`; here are some [examples](http://stackoverflow.com/search?tab=votes&q=java.sql.date). – trashgod Mar 04 '16 at 17:44