33.10 (Random cards) Write a JSF that displays four random cards from a deck of 52 cards, as shown in Figure 33.33. When the user clicks the Refresh button, four new random cards are displayed.
import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; @ManagedBean @RequestScoped public class Exercise10 { private int[] deck = new int[54]; public Exercise10() { changeCards(); } public void changeCards() { for (int i = 0; i < deck.length; i++) { deck[i] = i + 1; } for (int i = 0; i < deck.length; i++) { int index = (int) (Math.random() * deck.length); int temp = deck[i]; deck[i] = deck[index]; deck[index] = temp; } } public int getCard0() { return deck[0]; } public int getCard1() { return deck[1]; } public int getCard2() { return deck[2]; } public int getCard3() { return deck[3]; } }
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html"> <h:head> <title>Exercise10</title> </h:head> <h:body><h:form><center><br /><br /> Display Four Random Cards<br /> <br /> <table><tr> <td width="100"><center><h:graphicImage name="#{exercise10.card0}.png" library="cards"/></center></td> <td width="100"><center><h:graphicImage name="#{exercise10.card1}.png" library="cards"/></center></td> <td width="100"><center><h:graphicImage name="#{exercise10.card2}.png" library="cards"/></center></td> <td width="100"><center><h:graphicImage name="#{exercise10.card3}.png" library="cards"/></center></td> </tr></table> <br /> <h:commandButton value="Refresh" action="#{exercise10.changeCards()}"/> </center></h:form></h:body> </html>
No comments:
Post a Comment