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

时间:2018-02-18 06:00:48

标签: 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);
    }
}

问题是它显示列直到产品类型,之后它变为新行并在那里显示其余内容:

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

这是the text file for column which.

1 个答案:

答案 0 :(得分:1)

首先,你真的不需要一个文件来保存列名。您可以将列名称应用为 ORDERITEMFILE.txt 文件的第一行,非常类似于 CSV 文件。通常,CSV文件的第一行是列名称的分隔字符串,它的具体用途就是这样。

如果您坚持使用两个文件,那么我建议您先处理Column Names文件并删除它,以免它在您的事件代码中混乱。也许这可以通过单独的方法来实现:

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);
}

当运行并且选择了Order Button时,将放置表列名称,表格将填充文件数据,并且将出现一个消息框,指示向表中添加了多少文件记录。