简体   繁体   中英

Create a 2D array from text file / array

So I'm currently working on a project and I need a JTable for displaying invoices. The invoices are stored on a text file in the format

InvoiceID, InvoiceDate, InvoiceCustomer, InvoiceComplete

(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. 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.

I currently just have an empty class with a JTable for this task right now. 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

I can say that first read and iterate through the lines of that text file and perform your addRow() to your JTable instance.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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