-2

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");
}

but it shows error

cannot find the method set Background(Java.awt.colour).

Rangith
  • 39
  • 2
  • 9

1 Answers1

6

You're making some conceptual mistakes.

  1. You're confusing JSF with Swing.
  2. You're trying to manipulate the view in the controller.

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.

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).

Below is the right way:

private boolean dateEqual;

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

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

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'}" />

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' : ''}" />
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • bro one small help.. I have data grid and table.In data grid ,I have command buttons for every location. In table I have id,date,location attributes. The button should get coloured based on the id present in the table. how can I get this? please do some favour..Thanks in advance.. – Rangith Aug 20 '15 at 10:04
  • This section is for comments on the above post, not for new questions. For new questions, press "Ask Question" button on right top. – BalusC Aug 20 '15 at 10:05
  • yea I got that bro... but whole command button for every location change to yellow colour, that present in the data grid.But I need the particular location command button to display in yellow colour – Rangith Aug 20 '15 at 10:15
  • Then just alter the code logic inside `#{...}` accordingly that it checks the row instead of the bean? – BalusC Aug 20 '15 at 10:16
  • I didn't get it... :( – Rangith Aug 20 '15 at 11:40