【问题标题】:Finding the source of an ActionEvent in a JButton[][] array without using nested loops?在不使用嵌套循环的情况下在 JButton[][] 数组中查找 ActionEvent 的源?
【发布时间】:2014-04-14 02:06:51
【问题描述】:

我创建了一个JFrame 应用程序,其中包含一个JButtons[][] 的8x8 数组,对应于一个选中和取消选中的ImageIcons 数组。当按下按钮时,它使用setSelection() 选择该按钮并取消选择任何其他按钮。但是,如果按下所选按钮旁边的任何按钮,则所选按钮和相邻按钮将交换ImageIcons

我已经成功地完成了大部分工作,但是在 ActionEvent 中使用嵌套循环来确定相邻按钮、选中按钮和取消选中按钮同时成为逻辑上的噩梦。

public void actionPerformed(ActionEvent event)
{
for (int row = 0; row < 8; row++) {
  for (int col = 0; col < 8; col++) {
    if (event.getSource() == buttons[row][col]) {
      if (row<7) buttonsAdjacent[row+1][col] = true;
      if (row>0) buttonsAdjacent[row-1][col] = true;
      if (col<7) buttonsAdjacent[row][col+1] = true;
      if (col>0) buttonsAdjacent[row][col-1] = true;
      buttons[row][col].setSelected(true);
      }
    }
  }
}

如何将actionListeners 放入数组索引[row][col] 处的每个相邻按钮中,以确定是否实际按下了相邻按钮?每次选择新按钮时如何重新分配actionListeners

【问题讨论】:

  • 喜欢this?
  • 这样的专精,谢谢老兄

标签: java arrays swing loops jbutton


【解决方案1】:

如完整的example 所示,您可以计算JButtonList&lt;JButton&gt; 中的索引,作为给定网格大小的行和列的函数,例如N * N。请参阅 cmets 和 edit history 了解替代方案。

private static final int N = 5;

private JButton getGridButton(int r, int c) {
    int index = r * N + c;
    return list.get(index);
}

【讨论】:

    【解决方案2】:

    你不能只为 2D 数组中的每个 JButton 添加一个动作监听器吗?

    buttons[row][col].addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
    //Your code that should execute on a click on the Object here
    }
    );
    

    我猜这些动作监听器将始终可用。

    【讨论】:

      猜你喜欢
      • 2015-10-07
      • 2013-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-10
      • 2019-03-10
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多