Matrix转换为JTable

时间:2012-11-25 15:22:48

标签: java swing file matrix jtable

我需要使用静态2D数组填充JTable。我为JTable

创建了这个模型
 public class InsertMatToJTable extends AbstractTableModel{

   String titre[] = {"age real", "sex real", "chest real", "resting_blood_pressure real","serum_cholestoral real","fasting_blood_sugar real","resting_electrocardiographic_results real","maximum_heart_rate_achieved real","exercise_induced_angina real","oldpeak real","slope real","number_of_major_vessels real","thal real", "class"};

   String line;

    float mat[][]= new float[270][13];

    float matrice_normalise[][];

    int i = 0,j=0;

    public void InsertMatToJTable()
    {

try {
        FileInputStream fis = new FileInputStream("fichier.txt");
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));

            while ((line = br.readLine()) != null) {
                            StringTokenizer st1 = new StringTokenizer(line, " ");
                            while (st1.hasMoreTokens())
                            {mat[i][j]=Float.valueOf(st1.nextToken()).floatValue(); 
                                                        j++;

                           if (st1.hasMoreTokens()!=true)   i++;
                            }      
            }
            br.close();
      }catch(Exception e) {
                    e.printStackTrace();}

      Normalisation norm = new Normalisation(mat);

   // for(i=0;i<270;i++)
    //{for(j=0; j<14;j++)
    //{matrice_normalise[i][j]=norm.mat_normalised[i][j];
    //}
      matrice_normalise=norm.mat_normalised;


    }
 @Override
   public int getRowCount() {
    return 270*13;
  }

 @Override
public int getColumnCount() {
    return 13;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    return  matrice_normalise[rowIndex][columnIndex];
}

public String getColumnName(int columnIndex) {
    return titre[columnIndex];

}
    }

基本上,此代码从文本文件中读取,每行包含13个数值,并将它们存储到静态矩阵中,然后应用其他一些称为“规范化”的处理。

这里的问题似乎出现在“getValueAt”函数中。我每次都有这个错误:

         Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at prodm.InsertMatToJTable.getValueAt(InsertMatToJTable.java:62)

首先,我需要知道这段代码是否真的符合我的想法,即将数据存储在矩阵中的方式与存储在文本文件中的方式相同。

第二,我真的不知道getValueAt函数有什么问题?

另外,我注意到了别的东西。这部分肯定有问题:

  while ((line = br.readLine()) != null) {
                            StringTokenizer st1 = new StringTokenizer(line, " ");
                            while (st1.hasMoreTokens())
                            {mat[i][j]=Float.valueOf(st1.nextToken()).floatValue(); 
                                                        j++;
                                                       if (j==13) {i++;j=1;}
                            }  

它从文件中读取,但它不会按照应有的方式存储数据。基本上,它从第二行开始引入“转变”。例如,应该存储在[1] [0]的是[1] [1],[2] [0]在[2] [2] ......等等。

1 个答案:

答案 0 :(得分:2)

问题是你写了:

public void InsertMatToJTable()

但你应该写:

public InsertMatToJTable()

请注意,第二个代码段中没有void

您已声明了一个名为InsertMatToJTable的方法,而不是具有相同名称的类的构造函数。因此,当您调用new InsertMatToJTable()时,您调用默认的no-args构造函数并且您的代码永远不会运行,从而使您的矩阵保持未初始化状态,因此NullPointerException

要避免出现这类错字问题,请将日志添加到代码中并使用调试程序查找问题。

以下是工作代码的示例演示。

import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;

public class TestTables {

    private static final int ROWS = 270;
    private static final String titre[] = { "age real", "sex real", "chest real", "resting_blood_pressure real", "serum_cholestoral real",
            "fasting_blood_sugar real", "resting_electrocardiographic_results real", "maximum_heart_rate_achieved real",
            "exercise_induced_angina real", "oldpeak real", "slope real", "number_of_major_vessels real", "thal real", "class" };

    public static class InsertMatToJTable extends AbstractTableModel {

        private float[][] matrice_normalise;

        public InsertMatToJTable(float[][] matrice_normalise) {
            this.matrice_normalise = matrice_normalise;
        }

        @Override
        public int getRowCount() {
            return matrice_normalise.length;
        }

        @Override
        public int getColumnCount() {
            return titre.length;
        }

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            return matrice_normalise[rowIndex][columnIndex];
        }

        @Override
        public String getColumnName(int columnIndex) {
            return titre[columnIndex];

        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame(TestTables.class.getSimpleName());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                float[][] matrix = new float[ROWS][titre.length];
                Random random = new Random();
                for (int i = 0; i < matrix.length; i++) {
                    for (int j = 0; j < matrix[i].length; j++) {
                        matrix[i][j] = random.nextFloat() * 100;
                    }
                }
                InsertMatToJTable model = new InsertMatToJTable(matrix);
                JTable table = new JTable(model);
                JScrollPane scroll = new JScrollPane(table);
                frame.add(scroll);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}