1

In my current project I have a jtable with 4 columns. I don't want store duplicate data in second column, so I check each row in the jtable before I store it into to database.

Here's my code:

String s="";
int row = table.getRowCount();
for (int i=0; i<row; i++) 
{
    s = table.getValueAt(i, 1).toString().trim();
    if (name.getText().equals(s)) 
    {
      JOptionPane.showMessageDialog(null, "data alreadyexist.","message",JOptionPane.PLAIN_MESSAGE);
    break; 
    } else {
      add();
      break;
    }
} 
Sajan Chandran
  • 11,287
  • 3
  • 29
  • 38
pound Pound
  • 123
  • 3
  • 12

3 Answers3

2

you aren´t iteration through the whole table as i can see it. You only check, if the data is aviable in the first row. after this the method noticeses there might be the same data in row 2 and breaks, so you added 1 row and stopped, because you check it row by row, and for each row not matching, you do add a new one, until he found a row matching the one you want to add

String s = "";
boolean exists = false;
for (int i=0; i<table.getRowCount(); i++) 
{    
    s = table.getValueAt(i, 1).toString().trim();
    if(name.equals(s))
    {
       exists = true;
       break;
    )
)
if(!exists) 
    add();
else 
    JOptionPane.showMessageDialog(null, "data already exist.","message",JOptionPane.PLAIN_MESSAGE);

now you only have to check if the String, you are looking for is trimed the right way and it should work

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
  • try to do `System.out.println("Row: "s + " compare to:" + name)` and look if they should be equal in the for loop. EDIT: what should trim actually trim out? – SomeJavaGuy Nov 26 '12 at 13:55
1

Try this

ArrayList<String> contentList = new ArrayList();
int row = table.getRowCount();
for (int i=0; i<row; i++) 
{
    String str = table.getValueAt(i, 1).toString().trim();
    if (contentList.contains(str)) 
    {
      JOptionPane.showMessageDialog(null, "data alreadyexist.","message",JOptionPane.PLAIN_MESSAGE);
      break; 
    } else {
      contentList.add(str);
      add();
      break;
    }
} 
vels4j
  • 11,208
  • 5
  • 38
  • 63
1

Try this:

    int row = jTable1.getRowCount();
    Object[] content = new Object[row];
    for (int i = 0; i < row; i++) {
        content[i] = jTable1.getValueAt(i, 0);
    }
    Object value_to_find= 2000;
    boolean exist = Arrays.asList(content).contains(value_to_find);
    if (exist){
        JOptionPane.showMessageDialog(null, "Value exist", "Duplicate", JOptionPane.ERROR_MESSAGE);
    } else {
        addRow();
    }

Save all row in an array than search for value_to_find using Arrays.asList(content).contains(value_to_find)

samfch
  • 11
  • 2