为什么我不能在文本区域中显示我的二维数组的值

时间:2012-10-28 08:13:51

标签: java

我有一个由列和行组成的二维数组,在计算时它会构建一个矩阵或矩阵中的值,但问题是我的文本区域只在我的2d数组中显示我的最终结果而不是所有其他数据但是在我的netbeans控制台中,它确实显示了所有值。如何更改我的代码以启用此功能。我认为这是问题所在的部分。谢谢

这是在我的actionperform按钮中显示

     for (int i =0; i < rows; i++) {
       for (int j = 0; j < cols; j++) {
         matrix_tf.setText(String.valueOf(matrix[i][j]));

这是计算我的矩阵的代码

    private void build_matrix() {
    String seq1 = sequence1_tf.getText();
    String seq2 = sequence2_tf.getText();



    int r, c, ins, sub, del;

    rows = seq1.length();
    cols = seq2.length();

    matrix = new int [rows][cols];

    // initiate first row
    for (c = 0; c < cols; c++)
        matrix[0][c] = 0;

    // keep track of the maximum score
    max_row = max_col = max_score = 0;

    // calculates the similarity matrix (row-wise)
    for (r = 1; r < rows; r++)
    {
        // initiate first column
        matrix[r][0] = 0;

        for (c = 1; c < cols; c++)
        {
                        sub = matrix[r-1][c-1] + scoreSubstitution(seq1.charAt(r),seq2.charAt(c));
                        ins = matrix[r][c-1] + scoreInsertion(seq2.charAt(c));
                        del = matrix[r-1][c] + scoreDeletion(seq1.charAt(r));

            // choose the greatest
            matrix[r][c] = max (ins, sub, del, 0);

            if (matrix[r][c] > max_score)
            {
                // keep track of the maximum score
                max_score = matrix[r][c];
                max_row = r; max_col = c;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

在这个循环中:

 for (int i =0; i < rows; i++) {
   for (int j = 0; j < cols; j++) {
     matrix_tf.setText(String.valueOf(matrix[i][j]));

在每次迭代时设置字段的文本(设置文本会覆盖一个prvitoues)。尝试连接您的文本:

 for (int i =0; i < rows; i++) {
   for (int j = 0; j < cols; j++) {
     matrix_tf.setText(matrix_tf.getText() + " " + String.valueOf(matrix[i][j]));

如果您使用的是文本区域(而不是文本字段),请使用附加为@Sujay建议

答案 1 :(得分:0)

正如其名称its javadoc所示,setText()将文本区域的文本设置为给定的String参数。它没有附加文本。

使用StringBuilder将各种矩阵元素连接到String,并使用完整结果设置文本区域的文本:

StringBuilder sb = new StringBuilder();
for (int i =0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        sb.append(String.valueOf(matrix[i][j]));
        sb.append(' ');
    }
    sb.append('\n');
}
textArea.setText(sb.toString());
相关问题