【问题标题】:How do I pass a parameter from a commandButton to a bean in JSF?如何将参数从 commandButton 传递到 JSF 中的 bean?
【发布时间】:2020-02-06 16:48:15
【问题描述】:

我正在尝试在 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 给了我现在的板子。如何获取按钮参数以便它知道哪个按钮是哪个?

【问题讨论】:

标签: jsf el


【解决方案1】:

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

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

和你的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";

    }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多