Search code examples
jsf-2multidimensional-array

How to display a 2d array of elements


I'd like to display 2d array of floats in a table on a xhtml page using JSF2 and I have no idea how to do that. I tried to find the answer in google but I couldn't. All examples were displaying classes objects and I was not able to make it working with the table.

The sitation is: I have the array of some size - the size of the array depends on entered data: float [][] variables = new float[size1][size2]

After user enters data and pressess button a method is called in the managed bean. The calculation begins and the table is filled with data.

Please tell me how can I display the array.


Solution

  • To achieve that you can use c:forEach tag to dinamically buid a h:panelGrid. Just save size2, which is the column number as a property and store all the input numbers in a normal java.util.List. Then you set that size to the h:panelGrid columns attribute and the component will split the rows for you. You can also style the content inside the c:forEach tag, bordering it in order to give it a table behaviour.

    <h:form>
        <h:panelGrid columns="#{bean.numberCount}">
            <c:forEach var="num" items="#{bean.numberList}">
                #{number}
            </c:forEach>
        </h:panelGrid>
    </h:form>
    

    EDITED

    If you want to maintain the original structure but in a List, you can create a List<List<Float>>. That means a List which is composed by List which contains Float Objects. The same as a 2d array.

    private List<List<Float>> _Matrix;
    
    public List<List<Float>> get_Matrix() {
        return this._Matrix;
    }
    
    /**
     * Constructor for BackingBean.
     */
    public BackingBean() {
        this._Matrix = new ArrayList<List<Float>>();
        this._Matrix.add(new ArrayList<Float>());
        this._Matrix.add(new ArrayList<Float>());
        this._Matrix.get(0).add(1.0f);
        this._Matrix.get(0).add(2.0f);
        this._Matrix.get(0).add(3.0f);
        this._Matrix.get(1).add(1.0f);
        this._Matrix.get(1).add(2.0f);
        this._Matrix.get(1).add(3.0f);
    }
    

    In the code above I'm constructing the equivalent to a 2d array with 2 rows and values 1.0,2.0 and 3.0 on each row. You can use this code to iterate it over the view:

    <h:panelGrid columns="#{backingBean._ColumnNumber}">
            <c:forEach var="row" items="#{backingBean._Matrix}">
    
                <c:forEach var="value" items="#{row}">
    
                    #{value}
                        </c:forEach>
            </c:forEach>
        </h:panelGrid>
    

    Where #{backingBean._ColumnNumber} will be the length of the first array of the List (supposing all of them have the same length).

    Good Luck.