【问题标题】:How to retain the values of the table in a GUI even after exiting the GUI即使退出 GUI,如何在 GUI 中保留表的值
【发布时间】:2021-06-25 06:30:00
【问题描述】:

我在保留/保存保存在我的 GUI 表中的值时遇到问题。我的目标是保留它存储在表中的值,退出我的 GUI,然后再次打开它,然后我希望看到存储在表中的相同值。我的问题是,每当我关闭并再次打开 GUI 时,它都会刷新值并再次使其空白。

我通过写入和读取 CSV 文件来保存我的值。

在编写 CSV 文件时,它取决于用户在我的 GUI 的文本字段中输入的值,然后它会在我的驱动器 C 中的特定位置创建一个 CSV 文件。

在读取 CSV 文件时,它会读取写入的 CSV 文件的内容/值,然后使用这些值存储在二维数组中,以便将其显示到我的表格中。但问题是我无法在表中保留这些值,而且表显示空值,就在显示的数据旁边(我尝试执行 != null 但它仍然在输入值之后显示连续的空值)

图形用户界面:

CSV 文件:

这是我的源代码:

public void writeCustomerCSV(){  // everything in this snippet code works fine(it creates a CSV file which stores the inputs of the user)
   try{
       BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
       StringBuilder sb = new StringBuilder();
        
       int y;
       for(int x = 0; x < itemTo2D.length; x++){
           for(y = 0; y < itemTo2D[0].length; y++){
               if(itemTo2D[x] != null){
                   sb.append(itemTo2D[x][y]);
                   sb.append(",");
               }
           }
            
           sb.append("-");  //separation for rows
           sb.append(",");  // separation for columns
            
       }
        
       bw.write(sb.toString());
       bw.close();
        
   }  catch (Exception ex){
        
     }
   
  }

public void readCustomerCSV(){  // reads the contents of the CSV file     *having issues in retaining the values
    int read2DStringIndex = 0;
    int newVarIndexer = 0;
    String[] fromfile = {};   // 1d string for getting the columns(7 columns) of the CSV file

 

    try{
         BufferedReader br = new  BufferedReader(new FileReader("C:\\Users\\RALPH\\Documents\\Database Java CSV\\customers.csv"));
         String line;
         
         while ((line = br.readLine()) != null){
             fromfile = line.split(",");  //separates the columns by a comma
         }
        
        
        
    } catch (Exception ex){
        
    }
    
    for(int g = 0; g < fromfile.length; g++){  
         if(fromfile[g].equals("-")){   //if there is a presence of a dash, it increments the read2DStringINdex (row index) of the 2D array     
             read2DStringIndex++;
              newVarIndexer = 0;

         }
         else{
             
             cust[read2DStringIndex][newVarIndexer] = fromfile[g];    //cust is the 2D array(declared universal) which is going to display the values to the table
            newVarIndexer++;
              
                   
              
              
         }
    }
    
 
       for(int h = 0; h < cust.length; h++){  //prints cust (2D array) , just to check what data is being stored
        for(int p = 0; p < cust[0].length; p++){
            System.out.println(cust[h][p] + ",");
        }
    }
     

    DefaultTableModel tblmodelll = (DefaultTableModel) mainTable.getModel();  // table

    setrowcount = 0;    
    for(int r = 0; r < cust.length; r++){
        if(setrowcount == 0){
            tblmodelll.setRowCount(0);
        }
        if(cust[r][0] != null){
            tblmodelll.addRow(cust[r]);  //displays the cust(2D array) data to table 
        }
        
      setrowcount++; 
     
      
   }
    
   

}

我是否遗漏了要在我的代码中添加的内容,或者代码的逻辑不正确? 您的回复确实有助于解决此问题。 非常感谢!!!

【问题讨论】:

  • 两个问题很突出 - a) 如果用户输入 A,B 作为值或 AB 会怎样,以及 b) CSV 通常是行逐行读取/写入第 0 行的所有列作为一行,然后再次读取第 1 行,然后第 2 行......(注意:除了多行的值......)
  • 也许阅读此类问题的先前答案 - stackoverflow.com/a/14226913 - 会提供一些其他想法。
  • 您可以使用 gson 来保存和加载整个内容,也可以自己使用 JsonReader 和 JsonWriter 实现加载逻辑
  • 修改模型的代码是否对静态输入做一些理智的事情(即不读取文件只是用一些静态数组调用它以查看它的行为是否正确/将问题拆分为 2,检查您的 CSV 读/写往返并检查 GUI 填充)。
  • @IntoVoid 哦,好的,我会看看我能用 JsonReader 和 JsonWriter 做什么。 itemTo2D 也是一个二维字符串数组。

标签: java csv user-interface multidimensional-array


【解决方案1】:

你可以像这样读写你的表(如果它是一个字符串表。我在这里使用 Gson 库的 JsonWriter 和 JsonReader。但其他 JsonReader 和 JsonWriter 应该也可以工作。我猜):

public static void write(Writer w, String[][] table) throws IOException {
    JsonWriter writer = null;
    try {
        writer = new JsonWriter(w);
        writer.setIndent("    ");
        writer.setSerializeNulls(true);

        int height = table.length;
        int width = height > 0 ? table[0].length : 0;

        writer.beginObject();
        writer.name("len");
        writer.value((long) width * (long) height);
        writer.name("sub");
        writer.value(width);

        writer.name("entries");
        writer.beginArray();

        int y, x;
        for (y = 0; y < height; y++) {
            for (x = 0; x < width; x++) {
                String entry = table[y][x];
                if (entry == null) writer.nullValue();
                else writer.value(entry);
            }
        }
        writer.endArray();

        writer.endObject();
        writer.flush();
    } finally {
        if (writer != null) writer.close();
    }
}

public static String[][] read(Reader r) throws IOException {
    JsonReader reader = null;
    long len = 0, sub = 0;
    String[][] table = null;
    try {
        reader = new JsonReader(r);

        reader.beginObject();
        read:
        do {
            while (reader.peek() != JsonToken.NAME) {
                if (!reader.hasNext()) break read;
            }

            String name = reader.nextName();
            if ("len".equals(name)) len = reader.nextLong();
            else if ("sub".equals(name)) sub = reader.nextLong();
            else if ("entries".equals(name)) {
                reader.beginArray();
                table = new String[(int) (len / sub)][(int) sub];
                long i;
                int y, x;
                String entry;
                for (i = 0L; i < len && reader.hasNext(); i++) {
                    y = (int) (i / sub); x = (int) (i % sub);
                    if (reader.peek() != JsonToken.STRING) {
                        entry = null;
                        reader.skipValue();
                    } else entry = reader.nextString();
                    table[y][x] = entry;
                }
                reader.endArray();
            }
        } while (true);
        reader.endObject();
    } finally {
        if (reader != null) reader.close();
    }
    return table;
}

【讨论】:

    【解决方案2】:

    write 方法坏了 - 它产生可变长度输出..

           for(int x = 0; x < itemTo2D.length; x++){
               for(y = 0; y < itemTo2D[0].length; y++){
                   if(itemTo2D[x] != null){
                       sb.append(itemTo2D[x][y]);
                       sb.append(",");
                   }
               }
    

    一个小改动解决了这个问题 -

           for(int x = 0; x < itemTo2D.length; x++){
               for(y = 0; y < itemTo2D[0].length; y++){
                   if(itemTo2D[x] != null){
                       sb.append(itemTo2D[x][y]);
                   }
                   sb.append(",");
               }
    

    此外,readCSV 会出现问题,如果出于某种原因文件中有多行 -

         while ((line = br.readLine()) != null){
             fromfile = line.split(",");  //separates the columns by a com
         }
    

    这将一遍又一遍地设置 fromfile ..

    进行 2 次拆分可能更容易 - 在行分隔符 ("-") 上进行一次拆分,然后通过 (",") 对每一行进行拆分以获取列 .. 实际上它可以是 2 次 for 循环,如 write.. .

    【讨论】:

    • 不错不错!!!非常感谢你!我会看看我能用这些调整做什么,更有可能提供有关其功能的更新。再次感谢@MrR。
    猜你喜欢
    • 1970-01-01
    • 2013-09-12
    • 2018-05-06
    • 2021-03-14
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多