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

How do I pass a parameter from a commandButton to a bean in JSF?

我正在尝试在 JSF 中制作井字游戏。我有一个包含值 0、1 或 2 的二维矩阵 (3x3)。所以它一开始都是 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 给我现在的板子。我如何获取按钮参数以便它知道哪个按钮是哪个?

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

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

    }