【问题标题】:Using an Array at a specific index in a method in java在java中的方法中使用特定索引处的数组
【发布时间】:2016-07-28 05:42:37
【问题描述】:

我正在制作一款名为 Light out 的游戏!我想创建一个在某个索引处更改按钮颜色的方法。为此,我使用了以下代码:

Color bg = _buttons[x][y].getBackground();
            if(bg.equals(Color.white)){
                _buttons[x][y].setBackground(Color.yellow); 
            }
            else if (bg.equals(Color.yellow)){
                _buttons[x][y].setBackground(Color.white);  

x 和 y 是我正在查看的当前值的整数。 基本上我想做一个方法来接受我所在的任何索引。我试过做

public void flipIt(JButton _buttons[this] [this]){

            Color bg = _buttons[this][this].getBackground();


            }

但是java不喜欢这样,谁能指出我正确的方向吗?

【问题讨论】:

  • 你能举例说明你打算如何调用这个方法吗? (例如,您会将按钮实例或xy 整数传递给它)
  • @khelwood 对不起,我应该更清楚,我想这样做:button[x][y].flipIt();在这种情况下,x 和 y 是我的动作侦听器的一部分,因此它们会根据我在 GUI 中按下的按钮而改变
  • 如果你想在你的按钮本身上添加一个成员函数,那么你的按钮需要是你自己编写的类的实例,并且该类应该提供一个函数flipIt()。在那个函数中,按钮是this,而x,y根本不会被引用。
  • Java 不喜欢它?像什么? :)

标签: java arrays oop methods


【解决方案1】:

如果您的事件侦听器拾取的事件是对相关按钮的点击,则您不需要经过 x 和 y:

@Override
public void actionPerformed(ActionEvent e) {
    Object eventSource = e.getSource();
    if (eventSource instanceof JButton) {
        JButton buttonClicked = (JButton) eventSource;
        Color bg = buttonClicked.getBackground();
        if (bg.equals(Color.white)) {
            buttonClicked.setBackground(Color.yellow);
        } else if (bg.equals(Color.yellow)) {
            buttonClicked.setBackground(Color.white);
        }
    }
}

【讨论】:

    【解决方案2】:

    在您的调用代码中,您可以这样做:

    flipIt(_buttons[x][y]);
    

    你的函数看起来像这样

    `public void flipIt(JButton button){
        if(button.getBackground().equals(Color.white)){
                button.setBackground(Color.yellow); 
        } else if (button.getBackground().equals(Color.yellow)){
                     button.setBackground(Color.white);
                }
     }'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-09
      • 2012-10-25
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多