1

I have a code where I am getting data when I input values say itr.get(0),str.get(0)etc... But I want to create a for loop to it but I cannot use it since its inside model.addRow

And also each one is of different size array list object(itr,str,dub).

How do I input data through for loop to it so I don't have to call it manually.

    public Data1()
{
    super();
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    JTable table = new JTable(new DefaultTableModel(new Object[]{"Integers", "RealNumbers","OtherTokens"},5));
    DefaultTableModel model = (DefaultTableModel) table.getModel();

        model.addRow(new Object[]{itr.get(0),dub.get(0) ,str.get(0) });
        model.addRow(new Object[]{itr.get(1),dub.get(1) ,str.get(1) });
        model.addRow(new Object[]{itr.get(2),dub.get(2) ,str.get(2) });
        model.addRow(new Object[]{itr.get(3), ""  ,str.get(3) });
        model.addRow(new Object[]{itr.get(4), ""  ,str.get(4) });
        model.addRow(new Object[]{"", ""  ,str.get(5) });

    table.setPreferredScrollableViewportSize(new Dimension(500,80));
    JScrollPane pane = new JScrollPane(table);
    getContentPane().add(pane,BorderLayout.CENTER);

}
Box
  • 113
  • 12
  • You could acquire the data before making the JTable. You could use a TableModel (a better approach), and follow the [Example Here](http://stackoverflow.com/questions/3549206/how-to-add-row-in-jtable) of adding rows. You are too locked into a single solution, and are suffering for the [XY Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – KevinO Apr 14 '16 at 17:30
  • @kevin I used it but I am stuck in a similar way – Box Apr 14 '16 at 17:53
  • @kevin DefaultTableModel model = (DefaultTableModel) table.getModel(); model.addRow(new Object[]{itr.get(1),dub.get(1) ,str.get(1) }); – Box Apr 14 '16 at 17:53
  • @kevin those are array list object data – Box Apr 14 '16 at 17:53
  • After obtaining the model, why wouldn't you do something like `for (int i = 0; i < 10; ++i) { GATHER_THE_DATA; model.addRow(new Object[] {...})}`. Or, if you already have the data, then it is like `for int i = 0; i < 10; ++i) } model.addRow(new Object{itr.get(i),dub.get(i), str.get(i)}).` – KevinO Apr 14 '16 at 17:59
  • @kevin When array object is of different sizes ? I say for loop for 10 data - Arrray Index out of bound - As I said above its of different sizes. – Box Apr 14 '16 at 18:09
  • Yes, you added the comment, but I didn't see it (no comment indicated you updated the question), and your examples have all had the same index (0 or 1) in them. So, what is "10 data" then? At some point, you are gathering 10 inputs of something. You loop either (a)gathering them and then adding the row, or (b)have the data and then loop adding it. You have not explained *why* the arrays are of different sizes. – KevinO Apr 14 '16 at 18:13
  • @kevin I have fetched these data from text file & text file data is of different sizes that's the data I fetched ;). Sorry no 10 data my mistake updated it long back. – Box Apr 14 '16 at 18:16
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/109188/discussion-between-kevino-and-don-op). – KevinO Apr 14 '16 at 18:18

1 Answers1

1

The original question asked about adding in a loop to a table. However, the real problem is not the loop per se but rather the fact that there are a different number of elements of different types. This answer takes some data that was presented in the chat, and puts it into arrays. It could be read out of a file. It solves the question of what to put in a given row when there is no data by placing an empty String in the array.

The approach is to use the TableModel rather than attempting to add in a single shot. However, one could construct the necessary array if desired and pass it to the constructor instead. However, the TableModel is a better approach in the long run, IMHO.

public static void main(String[] args)
{
    // these three arrays represent the test data otherwise read
    //  from a file
    int[] ia = { 1493, -832722, 0, 1, 162 };
    double[] da = { 0.4, -6.382, 9.0E-21 };
    String[] sa = { "The", "fox", "jumped", "over", "the", "dog!"};


    Object[] columnNames = { "Int", "Real", "Tokens" };


    DefaultTableModel dm = new DefaultTableModel(columnNames, 0);
    JTable tbl = new JTable(dm);

    // while reading for a file, would know the max length in
    // a different way
    int loopCtr = Math.max(ia.length, da.length);
    loopCtr = Math.max(loopCtr, sa.length);

    // loop for the longest entry; for each entry decide if there
    // is a value
    for (int i = 0; i < loopCtr; ++i) {
        Integer iv = (i < ia.length ? ia[i] : null);
        Double dv = (i < da.length ? da[i] : null);
        String sv = (i < sa.length ? sa[i] : "");

        //add the row; if no value for a given entry, use an empty
        // String
        dm.addRow(new Object[]{(iv != null ? iv : ""),
                (dv != null ? dv : ""),
                sv});
    }

    //just output for the moment
    int cols = dm.getColumnCount();
    int rows = dm.getRowCount();
    StringBuilder sb = new StringBuilder();
    for (int row = 0; row < rows; ++row) {
        sb.setLength(0);
        for (int col = 0; col < cols; ++col) {
            sb.append(dm.getValueAt(row, col));
            sb.append("\t");                
        }

        System.out.println(sb.toString());
    }
}

The output demonstrates a table with blanks as needed.

1493        0.4       The       
-832722     -6.382    fox       
0           9.0E-21   jumped        
1                     over      
162                   the       
                      dog!
KevinO
  • 4,303
  • 4
  • 27
  • 36