简体   繁体   English

从文本文件/数组创建2D数组

[英]Create a 2D array from text file / array

So I'm currently working on a project and I need a JTable for displaying invoices. 所以我目前正在开发一个项目,我需要一个JTable来显示发票。 The invoices are stored on a text file in the format 发票以格式存储在文本文件中

InvoiceID, InvoiceDate, InvoiceCustomer, InvoiceComplete InvoiceID,InvoiceDate,InvoiceCustomer,InvoiceComplete

(int, String, String, boolean) (int,String,String,boolean)

For the other parts of my program, each line is read in and an invoice object is created. 对于我的程序的其他部分,读入每一行并创建一个发票对象。

However, for my JTable, I'm not too sure how to create a 2D array with the text file data. 但是,对于我的JTable,我不太清楚如何使用文本文件数据创建2D数组。 I thought of maybe trying to do this by creating an Array first but am not really too sure. 我想过可能首先通过创建一个数组来做到这一点,但我并不太确定。 The 2D array would need to be of type Object as it will store the invoices so I can have a checkbox in the JTable. 2D数组需要是Object类型,因为它将存储发票,因此我可以在JTable中有一个复选框。

I currently just have an empty class with a JTable for this task right now. 我现在只有一个带有JTable的空类,用于此任务。 Any advice would be appreciated. 任何意见,将不胜感激。 Thanks 谢谢

UPDATE: 更新:

JPanel invoiceViewPanel= new JPanel(null); //layout

Object data[][]= new Object[4][10];  
String columnHeaders[]={"Invoice ID","Invoice Name","Customer", "Complete?"};  

DefaultTableModel model = new DefaultTableModel(data, columnHeaders) {

boolean[] Editable= new boolean[]{
                false, false, false, true
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return editableCells[columnIndex];
        }

@Override
public Class<?> getColumnClass(int columnIndex)
{
    return columnClass[columnIndex];
}
};

JTable table=new JTable(model);  

JScrollPane tableContainer=new JScrollPane(table);      

final Class[] columnClass = new Class[] 
{
Integer.class, String.class, String.class, Boolean.class
};

 public void launch()
 {
this.setLayout(new FlowLayout());
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    


this.add(invoiceViewPanel);
invoiceViewPanel.add(tableContainer);
createObject();
this.add(tableContainer);

this.setTitle("Invoices");
this.setSize(500,600);
this.setVisible(true);
this.setResizable(false);

 }

public void tableData()
{
try
            {
                FileReader reader = new FileReader("Invoices.txt"); 
                BufferedReader bReader = new BufferedReader(reader);

                String sReadline = bReader.readLine(); 
                int x=0;

                while(sReadline!=null)
                {
                    String[] invoiceData= sReadline.split(",");     

                    data[x][0]=Integer.parseInt(invoiceData[0]);
                    data[x][1]=invoiceData[1];
                    data[x][2]=invoiceData[2];
                    data[x][3]=Boolean.parseBoolean(invoiceData[1]);

                    x=x+1;

                    sReadline=bReader.readLine();//sreadline
                }
            }

            catch (Exception e)
            {
               System.out.println(e);
            }

}

Although i have tried individually assigning the array values, either I get an ArrayIndexOutOfBoundsException or the JTable just still comes up as blank 虽然我已尝试单独分配数组值,但我得到一个ArrayIndexOutOfBoundsException或者JTable仍然是空白

I can say that first read and iterate through the lines of that text file and perform your addRow() to your JTable instance. 我可以说首先阅读并遍历该文本文件的行并对您的JTable实例执行addRow()。

List<String[]> rowList = new ArrayList<String[]>();
FileInputStream fstream = new FileInputStream("yourfile.txt");
      DataInputStream in = new DataInputStream(fstream);
      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      String strLine;
      while ((strLine = br.readLine()) != null)   {
      try{
        String[] tokens = str.split(" ");
       //process record 
        rowList.add(tokens);

      /*either add to row list first and then use the global variable
        for your job or simply add row to that jTable instance 
        right here */

         }
        catch (Exception e){
         e.printStacktrace();
        }
      }
     in.close();

Replace your code with this hope it will help. 替换你的代码希望它会有所帮助。

            JPanel invoiceViewPanel= new JPanel(null); //layout
        List<String[]> rowList = new ArrayList<String[]>();
        //Object data[][]= new Object[4][10];  
        String columnHeaders[]={"Invoice ID","Invoice Name","Customer", "Complete?"};  

        DefaultTableModel model = new DefaultTableModel(convertToArray, columnHeaders) {

        boolean[] Editable= new boolean[]{
                        false, false, false, true
                };

                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return editableCells[columnIndex];
                }

                private Object convertToArray(){
                    String[][] array = new String[list.size()][2];
                    int i = 0;
                    for (String[] nestedList : rowList) {
                        array[i++] = {nestedList[0],nestedList[1]};
                    }
                    /*
                    you can add dynamic column no. here i added 2
                    */
                    return array;
                }
        @Override
        public Class<?> getColumnClass(int columnIndex)
        {
            return columnClass[columnIndex];
        }
        };

        JTable table=new JTable(model);  

        JScrollPane tableContainer=new JScrollPane(table);      

        final Class[] columnClass = new Class[] 
        {
        Integer.class, String.class, String.class, Boolean.class
        };

         public void launch()
         {
        this.setLayout(new FlowLayout());
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    


        this.add(invoiceViewPanel);
        invoiceViewPanel.add(tableContainer);
        createObject();
        this.add(tableContainer);

        this.setTitle("Invoices");
        this.setSize(500,600);
        this.setVisible(true);
        this.setResizable(false);

         }

        public void tableData()
        {
          FileInputStream fstream = new FileInputStream("yourfile.txt");
          DataInputStream in = new DataInputStream(fstream);
          BufferedReader br = new BufferedReader(new InputStreamReader(in));
          String strLine;
          while ((strLine = br.readLine()) != null)   {
          try{
            String[] tokens = str.split(" ");
           //process record 
            rowList.add(tokens);

          /*either add to row list first and then use the global variable
            for your job or simply add row to that jTable instance 
            right here */

             }
            catch (Exception e){
             e.printStacktrace();
            }
          }
         in.close();
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM