在java中的方法中的特定索引处使用Array

时间:2016-04-07 11:14:36

标签: java arrays oop methods

我正在制作一款名为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不喜欢这样,有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:1)

在您的通话代码中,您可以这样做:

`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);
            }
 }'

,你的功能看起来像这样

transform-style: preserve-3d;

答案 1 :(得分: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);
        }
    }
}