使用IceFaces进行动态样式化:如何在渲染时更改outputText的颜色?

时间:2015-03-16 13:08:14

标签: icefaces

我是ICEFaces的新手,我必须维护别人的代码。我正在进行网络聊天,用户可以在其中发送和接收消息。我希望这些消息具有不同的颜色,具体取决于它们是由用户还是其他人发送的。

我目前在xhtml文件中有以下代码:

<h:dataTable id="history" value="#{chatBean.messages}" var="message" border="0" align="left" style="width: 100%" >
    <h:column width="590" height="25" align="left" valign="bottom" >
        <h:outputText value="#{message}" styleClass="#{chatBean.messageColor}" />
    </h:column>
</h:dataTable>

这显示了所有发送和接收的消息,但所有消息都具有相同的颜色,即使聊天bean的messageColor属性发生了变化:我做了一个实验,并在每条消息的末尾添加了getMessageColor()的结果,更改,但文本仍然以相同的颜色呈现。

CSS有以下类(等等):

.class1
{
  color:#818181;
  width: 100%; 
  font-size: 15px; 
  font-family: Arial, Helvetica, sans-serif; 
  font-weight: bold;    
}

.class2
{
  color:#00657c;
  width: 100%; 
  font-size: 15px; 
  font-family: Arial, Helvetica, sans-serif; 
  font-weight: bold;
} 

以下是ChatBean类的代码:

@ManagedBean(name = "chatBean")
@SessionScoped
public class ChatBean implements Serializable {
  private static final long serialVersionUID = -12636320254821872L;
  private static final String PUSH_GROUP = "chatPage";
  private PortableRenderer renderer;
  private String message;
  private String lastMessageSent = "";
  private Date lastMessageTime = new Date();
  private String isDown = "false";
  private List<String> messages = new ArrayList<String>();
  private String buttonDisabled = "true";
  private String buttonCancelDisabled = "true";
  private String pollDisabled = "false";
  private String id = "";
  private ChatClient chat;
  private Timer timer = new Timer();
  private String messageColor;

  public class ChatThread extends Thread implements Serializable {
      private static final long serialVersionUID = -7636532554421738019L;
      private Map<String, String> data;
      private String mail;
      public ChatThread(final Map<String, String> data, final String mail) {
          this.data = data;
          this.mail = mail;
      }
      @Override
      public void run() {
          chat = new ChatClient(new ChatClient.Event() {
              @Override
              public void handle(String msg) {
                  if(msg != null && msg.length() > 0)
                      pushMessage(msg);
              }
              @Override
              public void agentConnected(String msg) {
                  buttonDisabled = "false";
                  buttonCancelDisabled = "false";
                  pushMessage(msg);
              }
              @Override
              public void agentDisconnected(String msg) {
                  buttonDisabled = "true";
                  pushMessage(msg);
                  try {
                      timer.cancel();
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
              }
          });

          chat.login(mail, data);
          chat.join(mail, data.get("partner"), data.get("business"));
          timer.scheduleAtFixedRate(new RefreshTimerTask(), 0, 1000);
      }
  }
  public class RefreshTimerTask extends TimerTask implements Serializable {
      private static final long serialVersionUID = 1852678537009150141L;
      public void run() {
          chat.refresh();
      }
  }

  public ChatBean() {
      if(getSession() != null) {
          id = getSession().getId();
          PushRenderer.addCurrentSession(PUSH_GROUP + id);
          renderer = PushRenderer.getPortableRenderer();
          setMessageColor("class1");
          Log.getLogger().debug("New chat bean.");
          if(getData().containsKey("login_chat")) {
              ChatThread chat = new ChatThread(getData(), getSessionAttribute(GenesysSingleton.getInstance().getConfigApp().getDisplayName(), "<mail>"));
              chat.start();
          }
      }
  }

  private void pushMessage(String msg) {
      if(msg != null && !msg.isEmpty()) {
          ChatBean.this.isDown = "true";
          messages.add(msg);//Acá se puede acceder a textColor.
          try {
              PushRenderer.render(PUSH_GROUP + id);
          } catch (Exception e) {
              renderer.render(PUSH_GROUP + id);
          }
          setMessageColor("class1");
      }
  }
  private String getSessionAttribute(String key, String ref) {
      Object value = getSession().getAttribute(key);
      return value != null ? value.toString() : ref;
  }

  private Map<String, String> getData() {
      Map<String, String> data = new HashMap<String, String>();
      HttpSession session = getSession();
      @SuppressWarnings("rawtypes")
      Enumeration enums = session.getAttributeNames();
      while(enums.hasMoreElements()) {
          String key = enums.nextElement().toString();
          if(!"com.sun.faces.application.view.activeViewMaps".equals(key)
              && !"com.sun.faces.renderkit.ServerSideStateHelper.LogicalViewMap".equals(key)
              && !"javax.faces.request.charset".equals(key))
              data.put(key, session.getAttribute(key).toString());
      }
      return data;
  }

  public void sendMessage(ActionEvent event) {
      sendMessage();
  }

  protected synchronized void sendMessage() {
      if (message != null && !message.trim().isEmpty()){
          Date now = new Date();
          //No permito mandar el mismo mensaje 2 veces seguidas en un intervalo menor a un segundo.
          message = message.trim();
          if (message.equals(lastMessageSent)&&(now.getTime()<(1000+lastMessageTime.getTime()))){
              message = null;
          }
          else{
              setMessageColor("class2");
              lastMessageSent = message;
              message = null;
              lastMessageTime = new Date();
              chat.refresh(lastMessageSent);
          }
      }
  }

  public String disconnect() {
      pollDisabled = "true";
      return "login";
  }

  public void sendClose(ActionEvent event) {
  }

  public void receiveMessage() {
  }

  @PreDestroy
  public void destroy() {
      buttonDisabled = "true";
      try {

          //pushMessage(SISTEMA_3);
      } catch (Exception e) {
          e.printStackTrace();
      }
      try {
          Thread.sleep(1000);
      } catch (InterruptedException e) {
          e.printStackTrace();
      };
      System.out.println(id + "- ssssssss");
      try {
          timer.cancel();
      } catch (Exception e) {
      }
      chat.logout();
      chat.close();
  }

  private HttpSession getSession() {
      return (HttpSession) getContext().getSession(false);
  }
  private ExternalContext getContext() {
      return getFacesContext().getExternalContext();
  }
  private FacesContext getFacesContext() {
      return FacesContext.getCurrentInstance();
  }

  public String getMessage() {
      return message;
  }

  public void setMessage(String message) {
      this.message = message;
  }

  public String getButtonDisabled() {
      return buttonDisabled;
  }

  public void setButtonDisabled(String buttonDisabled) {
      this.buttonDisabled = buttonDisabled;
  }

  public List<String> getMessages() {
      try {
          JavascriptContext.addJavascriptCall(getFacesContext(), "document.getElementById('scrollDataTable').scrollIntoView();");
      } catch (Exception e) {
          e.printStackTrace();
      }
      return messages;
  }

  public void setMessages(List<String> messages) {
      this.messages = messages;
  }

  public String getPollDisabled() {
      return pollDisabled;
  }

  public void setPollDisabled(String pollDisabled) {
      this.pollDisabled = pollDisabled;
  }

  public String getButtonCancelDisabled() {
      return buttonCancelDisabled;
  }

  public void setButtonCancelDisabled(String buttonCancelDisabled) {
      this.buttonCancelDisabled = buttonCancelDisabled;
  }

  public String getIsDown() {
      return isDown;
  }

  public void setIsDown(String isDown) {
      this.isDown = isDown;
  }

  public String getMessageColor() {
      return messageColor;
  }

  public void setMessageColor(String textColor) {
      this.messageColor = textColor;
  }

}

所有帮助将不胜感激。提前谢谢。

4 个答案:

答案 0 :(得分:0)

我根据bean属性动态更改css的一种可能方法是使用styleClass的{​​{1}}属性。

在你的css文件中定义两个不同的类,例如

<h:outputText>

然后在您的java bean代码中,您可以使用getter和setter声明.class1 { color:red; //Put your colour here (#818181) } .class2 { color:green; //Put your colour here (#00657c) } 字段,例如

String

然后在你的代码中

private String messageColor;

您可以将此更改为要将文本更改为的类,例如:

setTextColor(COLOR_AGENTE);

然后在setMessageColor("class1"); 附加

<h:outputText>

这应该有用;

答案 1 :(得分:0)

由于我原来的建议不起作用,你可以尝试一下。
从您private String messageColor;和getter / setter中删除chatBean以及对setMessageColor("class1");的任何来电。

但请将这两个课程保留在你的CSS中。

现在在chatBean

中声明一个带有getter和setter的布尔属性
private boolean colourAgente;

声明一个方法:

public String setColor() {
    if (colourAgente) {
        return "class1";
    } else {
        return "class2";
    }

}

然后在您的xhtml中将styleClass属性更改为:

styleClass="#{chatBean.setColor()}"

最后,在你的java代码更改中:

setMessageColor("class1");

colourAgente = true;colourAgente=false;,具体取决于您要设置的颜色。

答案 2 :(得分:0)

我终于做到了,但我不得不使用丑陋的JavaScript解决方法。也就是说,我每次刷新聊天时都会运行此脚本:

function updateColors(){
    var username = document.getElementById("form:username").value;
    if (username.length > 0){
        var x = document.getElementsByClassName("class1");
        if (x != null){
            for (i = 0; i < x.length; i++){
                if (x[i].innerHTML.indexOf(username) === 0){
                    x[i].className = "class2";
                }
            }
        }
    }
}

无论如何,谢谢你的帮助,LiamWilson94。我仍然不知道我正在使用的代码的哪一部分使得你的答案不起作用,但是你给了我很多洞察力,帮助我达到了这个“解决方案”,我学到了关于IceFaces的一些事情在这个过程中。

答案 3 :(得分:0)

好的,我找到了更好的解决方案。

我创建了一个TextModel类:

import java.io.Serializable;



public class TextModel implements Serializable {

    private static final long serialVersionUID = -8470475291191399871L;

    private String text;

    private String clase;



    public TextModel() {

    }



    public TextModel(String text, String clase) {

        this.text = text;

        this.clase = clase;

    }



    public String getText() {

        return text;

    }



    public void setText(String text) {

        this.text = text;

    }



    public String getClase() {

        return clase;

    }



    public void setClase(String clase) {

        this.clase = clase;

    }



    public String toString() {

        return text;

    }

}

然后我将ChatBean中的消息从List更改为List,并更改了ChatBean.java中的以下函数:

private void pushMessage(String msg) {
    if(msg != null && !msg.isEmpty()) {
        ChatBean.this.isDown = "true";
        messages.add(new TextModel(msg,clase));
        try {
            PushRenderer.render(PUSH_GROUP + id);
        } catch (Exception e) {
            renderer.render(PUSH_GROUP + id);
        }
        clase = "class1";
    }
}
protected synchronized void sendMessage() {
    if (message != null && !message.trim().isEmpty()){
        Date now = new Date();
        message = message.trim();
        if (message.equals(lastMessageSent)&&(now.getTime()<(1000+lastMessageTime.getTime()))){
            message = null;
        }
        else{
            clase = "class2";
            lastMessageSent = message;
            message = null;
            lastMessageTime = new Date();
            chat.refresh(lastMessageSent);
        }
    }
}

其中clase是&#34; class1&#34;或&#34; class2&#34; (可能比较整洁,但现在可以使用了,我以后总能把它弄得更整洁。)

最后,在chat.xhtml上,我将outputtext标记更改为:

<h:outputText value="#{message.text}" styleClass="#{message.clase}" />

那就是它。没有更混乱的JavaScript补丁。

诀窍是使类成为消息本身的属性,而不是ChatBean。

我希望将来可以帮助别人。