Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

jsf - Dynamically change CSS style of cell in <h:dataTable> column

how to calculate cell values of B column and how to change their css style dynamically how to calculate the values of column B and how to change his color

my java object :

public class MyObject{
   private Date date;
   private int A;
   private int C;

   //Getters & Setters
}

my managed bean :

public class MyBean(){
    List<MyObject> List = myObjectDao.FindAll();

    //Getters & Setters
}

my jsf code :

<p:dataTable id="idList" var="list" value="#{myBean.list}" >
    <p:column headerText="DATE">
        <h:outputText value="#{list.date}"  />
    </p:column>
        <p:column headerText="A">
        <h:outputText value="#{list.A}"  />
    </p:column>
        <p:column headerText="B">
        <h:outputText value="????????" style="???????"  //>
    </p:column>
        <p:column headerText="C">
        <h:outputText value="#{list.C} />
    </p:column>
</p:dataTable> 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can just use the conditional operator ?: in EL.

E.g.

<c:set var="B" value="#{(list.A / list.C) * 100}" />
<h:outputText value="#{B}" style="display: block; background-color: #{B lt 50 ? 'red' : (B lt 90 ? 'blue' : 'green')}" />

If B is also used elsewhere in the model or controller, then you could add a public int getB() method which just contains return (A/C) * 100; and then use #{list.B} instead of #{B}.

Note that proper design is to use a CSS class instead. E.g.

<h:outputText value="#{B}" styleClass="percentage #{B lt 50 ? 'poor' : (B lt 90 ? 'average' : 'good')}" />

with

td .percentage {
    display: block;
}

.percentage.poor {
    background-color: red;
}

.percentage.average {
    background-color: blue;
}

.percentage.good {
    background-color: green;
}

You can of course also perform the determination of CSS style/class in a getter method as suggested by the other answer, but that's a poor separation of concerns.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...