如何将参数从commandButton传递给JSF中的bean?

时间:2020-02-06 16:48:15

标签: jsf el

我正在尝试在JSF中打井字游戏。我有一个二维矩阵(3x3),其值分别为0、1或2。因此,一开始它们全为0,并且根据播放器而切换为1或2。

我正在尝试从Bean中的方法获取按钮的图像,该方法读取矩阵中的值并为其提供适当的图像(无,X或O);

<h:form id="board">

<!--  id string i+j  -->

<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="00"/></h:commandButton>
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="01"/></h:commandButton>
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="02"/></h:commandButton>
<br />
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="10"/></h:commandButton>
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="11"/></h:commandButton>
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="12"/></h:commandButton>
<br />
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="20"/></h:commandButton>
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="21"/></h:commandButton>
<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg()}" style="width:200px;height:200px"> <f:param name="btn" value="22"/></h:commandButton>

</h:form>

在豆子中我有

public String btnImg() {

        String buttonId = getParameter("btn");

        int i = Integer.parseInt(String.valueOf(buttonId.charAt(0)));
        int j = Integer.parseInt(String.valueOf(buttonId.charAt(1)));

        int[][] posi = x.getTabuleiro();

        if (posi[i][j] == 0)
            return "resources/images/clear.png";

        else if (posi[i][j] == 1)
            return "resources/images/black_x.png";

        else
            return "resources/images/black_o.png";

    }

getTabuleiro给了我现在的董事会。如何获取按钮参数,以便知道哪个按钮是哪个?

1 个答案:

答案 0 :(得分:0)

使用方法参数将是最简单的方法。

<h:commandButton action="#{some_action}" image="#{beanJogo.btnImg(2,2)}" style="width:200px;height:200px"></h:commandButton>

和您的Java-方法

public String btnImg(int i, int j) {

        int[][] posi = x.getTabuleiro();

        if (posi[i][j] == 0)
            return "resources/images/clear.png";

        else if (posi[i][j] == 1)
            return "resources/images/black_x.png";

        else
            return "resources/images/black_o.png";

    }
相关问题