java - 从文本文件读取数据时在 JTable 中显示数据

标签 java swing jframe jtable

我试图显示来自单独文件的列数据和来自另一个文件的行数据,但它的输出不正常,因为下面附加的行文件是用于输出的图像文件和文本文件:

private void orbuttonActionPerformed(java.awt.event.ActionEvent evt) {
    DefaultTableModel model = (DefaultTableModel) orderitemtable.getModel();
    model.setRowCount(0);
    String filename = "ORDERITEMFILE.txt";
    String idnamefile = "odcofile.txt";
    File file1 = new File(idnamefile);
    File file = new File(filename);
    try {
        BufferedReader br = new BufferedReader(new FileReader(file1));
        BufferedReader br1 = new BufferedReader(new FileReader(file));
        //to make the columns name so to get the first line of code
        //set columnsname to the jtable Model
        String firstLine = br.readLine().trim();
        String[] columnsName = firstLine.split("/");
        model.setColumnIdentifiers(columnsName);
        //get lines from txt files
        Object[] tablelines = br1.lines().toArray();
        //Extracting the data from lines
        //set data to jtable Model
        for (int i = 0; i < tablelines.length; i++) {
            String line = tablelines[i].toString().trim();
            String[] dataRow = line.split(",");
            model.addRow(dataRow);
        }
    } catch (Exception ex) {
        Logger.getLogger(productpage.class.getName()).log(Level.SEVERE, null, ex);
    }
}

问题在于它显示该列的直到产品类型,然后它更改为新行并在那里显示其余内容:

这是the text file对于它从 txt 文件中正确读取的行,唯一的问题是当它显示在 JTable 中时,它在单独的行中读取最后两个数量。

这是the text file for column which.

最佳答案

首先,您确实不需要一个文件来保存列名称。您可以将列名称应用为 ORDERITEMFILE.txt 文件的第一行,这与 CSV 文件的布局非常相似。通常,CSV 文件的第一行是列名称的分隔字符串,它是专门用于此类用途的。

如果您坚持使用两个文件,那么我建议您首先处理列名称文件并删除它,这样它就不会在您的事件代码中造成困惑。也许用一个单独的方法来做到这一点:

private String[] getColumnNames(String filePath) {
    String[] columns = {};
    //Try with Resources (auto closes the reader)
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String line;
        // Assumes there is only one line in file.
        while ((line = br.readLine()) != null) {
            // Ignore blank lines (if any) leading to the line we want.
            if (!line.equals("")) { break; }
        }
        if (line != null && !line.equals("")) {
           columns = line.split("/");
        }
    }
    catch (FileNotFoundException ex) {
        System.err.println("Column Names File Not Found!");
    }
    catch (IOException ex) {
        System.err.println("IO Exception Encounterd!\n" + ex.getMessage());
    }
    return columns;
}

抱着在某种程度上保持事物井井有条的想法,我们现在可以有另一种方法来将新的列名称设置为 JTable:

private void setTableColumns(JTable table, String[] columnsName) {
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    model.setColumnIdentifiers(columnsName);
}

并且仍然坚持组织思想,我们还有另一种方法来用文件数据填充 JTable:

private int fillTableFromFile(JTable table, String filePath) {
    DefaultTableModel model = (DefaultTableModel) table.getModel();
    int recordCount = 0;
    //Try with Resources (auto closes the reader)
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        // Clear current table rows
        while (model.getRowCount() > 0) {
            for (int i = 0; i < model.getRowCount(); i++) {
                model.removeRow(i);
            }
        }
        String dataLine;
        Object[] dataArray;
        // read in the data and add to table.
        while ((dataLine = br.readLine()) != null) {
            // Ignore blank lines (if any).
            if (dataLine.equals("")) { continue; }
            //Split the comma delimited data line into a Object Array
            dataArray = dataLine.split(",");
            model.addRow(dataArray);
            recordCount++;
        }
    }
    catch (FileNotFoundException ex) {
        System.err.println("Data File Not Found!");
    }
    catch (IOException ex) {
        System.err.println("IO Exception Encounterd!\n" + ex.getMessage());
    }
    return recordCount; // The number of records added to table from file.
}

使用上述方法后,您现在可以在 JButton Action Performed 事件中拥有一些“易于遵循”(且可控)的代码。通过可控,我的意思是,例如,您可以确定如果(无论出于何种原因)coloumnsName字符串数组为空或为空(此处未处理)会发生什么:

private void orbuttonActionPerformed(java.awt.event.ActionEvent evt) {
    String filename="ORDERITEMFILE.txt";
    String idnamefile="odcofile.txt";
    String[] columnsName = getColumnNames(idnamefile);
    setTableColumns(orderitemtable, columnsName);
    int numOfRecords = fillTableFromFile(orderitemtable, filename);
    JOptionPane.showMessageDialog(orderitemtable, "There were " + numOfRecords + 
                        " Records Added to Table.", "Records Added", 
                        JOptionPane.INFORMATION_MESSAGE);
}

运行并选择“排序”按钮时,将放置表列名称,表将填充文件数据,并且将出现一个消息框,指示向表添加了多少文件记录。

关于java - 从文本文件读取数据时在 JTable 中显示数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48848936/

相关文章:

java - 如何使用 for 循环从 char 数组中绘制 Sprite

java - Oracle 连接压缩?

Java QuickSort 最佳案例数组生成

java - 使用 JFrame 在 JPanel 之间切换

java - 无法使用新数据刷新我的 JTable

java - 我想在图形用户界面中绘制矩形

java - 将 .swf 文件嵌入到我的 Jframe 中

java - GWT TypeOracle.getTypes 不返回所有类型

java - 如何解决 Android Studio 中的 Phenotype API 错误?

java - 将所有 Jtable、JList 选中时的边框单元格颜色更改为