簡體   English   中英

從文本文件到jTable Java將2D數組內存儲1D數組

[英]Storing 1D arrays inside 2D array from text file to jTable java

嗨,我需要將文本文件導入到Jtable中。 我必須將每一列存儲到單獨的數組中,因此我正在考慮為表創建2D數組,為內部的每一列創建1D數組。 (9列,共20行)

到目前為止,我所要做的就是導入文本文件並將其顯示在Jtable中。 我必須使用的數據類型是int,string和double(或float),因為我必須創建為學生表,其中將顯示其ID號(int)名稱,地址ect(string)和成績(double),但不適用於才能進行成績計算。

 private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    // When the window is opened, the information from the text file will be loaded into the table (tblStudentDetails)


    try {
        BufferedReader br = new BufferedReader(new FileReader ("C:\\Users\\XXX\\NetBeansProjects\\StudentDetailsJava\\lib\\StudentDetails.txt"));

        //Get the first line
        //Get the columns name from the first line
        // Set columns name to the tblStudentDetails model 

        String firstLine = br.readLine().trim(); // Reading the file line (row) of the text file
      //  while(firstLine !=null) {
        String[] columnsName = firstLine.split("\t"); // The coloums are split by tab

        DefaultTableModel model = (DefaultTableModel)tblStudentDetails.getModel();
        model.setColumnIdentifiers(columnsName);

        // Get lines from txt file
        Object[] tableLines = br.lines().toArray();


              // Extract data from lines
              // Set data to tblStudentsData model
              for (Object tableLine : tableLines) {
                  String line = tableLine.toString().trim();
                  String[] dataRow = line.split("\t");
              {

              model.addRow(dataRow);   
              }
              }

                   br.close();
    } catch (Exception ex) {
        Logger.getLogger(StudentTable.class.getName()).log(Level.SEVERE, null, ex);
    }


}   

到目前為止,這就是我所擁有的,在你們殺死我之前,我花了過去三天的時間來嘗試使它生效,並且我嘗試了在該站點上可以找到的幾乎所有解決方案,但均無濟於事。

我已經能夠創建2D數組,但是在讀取文本文件或將其導入Jtable時卻無法使其真正起作用。 有人幫忙! 一年級的學生,所以我絕對是新手,我的任務很快就會到期,我不能繼續解決這個問題!

謝謝! -太太x

另外,文本文件看起來像這樣(用制表符分隔,因此第一行太長,但是可以很好地導入到Jtable中)

在此處輸入圖片說明

試試這個代碼:

Scanner input = new Scanner(new File(FILE_NAME));
    int rows = 0;
    String[] columnsName = null;
    if (input.hasNext()) {
        columnsName = input.nextLine().split("\t");
    } else {
        return;
    }

    while (input.hasNextLine()) {
        input.nextLine();
        ++rows;
    }
    String[][] a = new String[rows][columnsName.length];

    input.close();

    input = new Scanner(new File(FILE_NAME));
    if (input.hasNextLine()) {
        input.nextLine();
    }

    for (int i = 0; i < rows; i++) {
        a[i] = input.nextLine().split("\t");
    }

    JTable jt = new JTable(a, columnsName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM