java - 矩阵到 JTable

标签 java swing file matrix jtable

我需要用静态二维数组填充 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]中......等等。

最佳答案

问题是你写的是:

public void InsertMatToJTable()

但你应该写:

public InsertMatToJTable()

请注意,没有 void在第二个片段中。

您已声明一个名为 InsertMatToJTable 的方法而不是同名类的构造函数。因此,当您调用new InsertMatToJTable()时您调用默认的无参数构造函数,并且您的代码永远不会运行,使您的矩阵保持未初始化状态,因此 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);
            }
        });
    }
}

关于java - 矩阵到 JTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552377/

相关文章:

java - JAX-RS CXF 异常包装

java - 在排序数组列表中查找 2 个最近的前一个值和 2 个最近的下一个值

java - 仅将日期传递到 sql : Unparseable date error

java - Java EE 包命名约定是什么?

java - 有没有办法将对象添加到 JComboBox 并分配一个要显示的字符串?

php - 当我添加 'files' => true 时,Laravel 表单不返回输入

java - 加载类文件后出现 ClassNotFoundException

java - 如何确定鼠标是否指向特定对象?

java - JMenu 项目将 jgraph 导出为图像

python将变音符号写入文件