【问题标题】:Displaying data in JTable while reading the data from the text file从文本文件中读取数据时在 JTable 中显示数据
【发布时间】:2018-02-18 06:00:48
【问题描述】:

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

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.

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖 minimal reproducible exampleShort, Self Contained, Correct Example。将一些数据硬编码为 MCVE / SSCCE 中的 String 对象。更一般地: 1) 另见How to create great screenshots? 2) 不要包含文本内容的图像,将文本包含为文本。 3) 使用合乎逻辑且一致的缩进代码行和块的形式。缩进是为了让代码的流程更容易理解!
  • 根据我的小实验,似乎没有任何特别的问题。这表明问题出在输入文件本身
  • @MadProgrammer 但我检查了很多次的文件确实由
  • 根据我的简单测试,用于读取文件的代码似乎是正确的,我推测输入在行中间某处包含“返回”字符,这导致了 BufferedReader过早地分裂它。记事本不会显示这个,它需要一个“换行符”和“返回”才能拆分行

标签: java swing jframe jtable


【解决方案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 事件中添加一些“易于遵循”(且可控)的代码。可控,我的意思是,例如,如果(无论出于何种原因)columnsName 字符串数组为空或 null(此处未处理),您可以确定会发生什么:

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

当运行并选择订单按钮时​​,表格列名将被放置,表格将被文件数据填充,并且会出现一个消息框,指示向表格添加了多少文件记录。

【讨论】:

  • 还是一样的东西,它的显示增加了 2 行
  • @cheekybones - 不确定在这种情况下可能出现什么问题。我似乎无法模拟这个问题。我建议你用一个新的 JTable 试试这个,然后看看会发生什么(也许在一个新的测试项目中)。
猜你喜欢
  • 1970-01-01
  • 2011-11-07
  • 2014-05-16
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
相关资源
最近更新 更多