本文介绍了如何在后台Bean中为h:commandButton设置背景色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个命令按钮,单击该按钮时,该按钮的背景色应更改.这应该在后备bean方法中完成.如何在Java方法中设置命令按钮的颜色?我尝试过这个

I have a command button, when I click that, the background colour of that button should be changed. This should be done in backing bean method. How to set the colour for command button in Java method? I tried this one

if (dt.equals(getDate())) {
  System.out.println("Date is equal....");
  button.setBackground(Color.yellow);
}
else {
  System.out.println("date is different");
}

但显示错误

推荐答案

您正在犯一些概念上的错误.

You're making some conceptual mistakes.

  1. 您将JSF与Swing混淆了.
  2. 您正在尝试在控制器中操作视图.

要了解什么是JSF,请从此处开始.要了解什么是Swing,请从此处开始.它们不一样.使用JSF开发时,请停止思考Swing或寻找Swing解决方案.

To learn what JSF is, start here. To learn what Swing is, start here. They are not the same. Stop thinking in Swing or searching for Swing solutions when developing with JSF.

关于MVC方面,后备bean是控制器.它应该只操纵模型(bean的属性),而不操纵视图(XHTML文件).视图(XHTML文件)应仅通过控制器(受管bean实例)访问模型(bean的属性).

As to the MVC aspect, the backing bean is the controller. It should only manipulate the model (bean's properties), not the view (XHTML file). The view (XHTML file) should only access the model (bean's properties) via the controller (the managed bean instance).

下面是正确的方法:

private boolean dateEqual;

public void someActionMethod() {
    dateEqual = dt.equals(date);
}

public boolean isDateEqual() {
    return dateEqual;
}
<h:commandButton ... style="background: #{bean.dateEqual ? 'yellow' : 'none'}" />

或者,如果您同时具有dtdate属性的getter方法,则甚至可以不用其他属性就可以逃脱:

Alternatively, you can even get away without an additional property if you have getter methods for both dt and date properties:

<h:commandButton ... style="background: #{bean.dt eq bean.date ? 'yellow' : 'none'}" />

请注意,从HTML角度来看,通过style属性使用内联CSS是一种较差的做法.最好是创建一个代表特定条件的CSS类.例如. 突出显示"(或特定条件所具有的任何特定术语).

Note that using inline CSS via style attribute is a poor practice in HTML perspective. Best would be to create a CSS class representing the specific condition. E.g. "highlight" (or whatever specific term the particular conditon has).

.highlight {
    background: yellow;
}
<h:outputStylesheet name="style.css" />
...
<h:commandButton ... styleClass="#{bean.dateEqual ? 'highlight' : ''}" />

这篇关于如何在后台Bean中为h:commandButton设置背景色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 07:05