jTable does not add the second string I put in an array

Asked

Viewed 34 times

0

I created an array with two values and wanted to put it in a table... with an insert button (insert several lines) 1-I declared the string line[] and the values below; 2- I thought a 'for each' would solve by adding a line (add.Row) to each pass. but not. 3-for testing, the Sout is ok. 4 as a result, it prints twice the first string "first line"

String[] linha = {"primeira linha", "segunda linha"};
  for(String linhas : linha){
    ((DefaultTableModel) jTable.getModel()).addRow(linha);
    System.out.println(linha);
  }

inserir a descrição da imagem aqui

to remove the lines, I did it here and solved; because it comes to "int" in "removeRow"

// limpar todas as linhas da tabela jTable
        for(int i = jTable.getRowCount(); i>0 ; i--){
            ((DefaultTableModel) jTable.getModel()).removeRow(0);
        }
  • Translate the question, Luke. Otherwise it will be closed

  • I’ve already noticed that in foreach I have to use the string "lines" but addRow asks for an Object array... so I don’t know how.

  • I tried this one too &#xA;String[] linha = {"primeira linha","segunda linha"};&#xA; for (int i = 0 ; i<linha.length ; i++){&#xA; ((DefaultTableModel) jTableListaObstaculos.getModel()).addRow(linha);&#xA; }&#xA;

2 answers

0

Hello,

You can initialize Jtable otherwise, passing an array with the columns, and an array with the data (which Voce can mount with what Voce needs) Also add Jtable to a Jscrollpane to display the column header

Looks like this

String[] colunas = new String[] { "Nome", "Sobrenome", "Idade" };

Object[][] dados = new Object[][] { { "Jose", "Silva", 44 }, { "Manuel", "Bento", 44 }, };

JTable table = new JTable(dados, colunas);

JFrame frame = new JFrame();
frame.add(new JScrollPane(table));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
  • it only adds the "first row" in the table

0


The error is in foreach

String[] linha = {"primeira linha", "segunda linha"};
for(String linhas : linha){
((DefaultTableModel) jTable.getModel()).addRow(linha);
System.out.println(linha);
}

In the third line Voce is adding the LINE ARRAY, and not the line element as you wanted to do. The method is directly accessing the array and picking up the first element only. To fix just change line for lines within the commands of foreach:

String[] linha = {"primeira linha", "segunda linha"};
  for(String linhas : linha){
    ((DefaultTableModel) jTable.getModel()).addRow(linhas);
    System.out.println(linhas);
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.