0

I am making a game called Light out! I would like to create a method that changes the color of a button at a certain index. to do this, ive used the following code:

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 and y are integers that are the currant value I am looking at. basically I would like to make a method that takes in whatever index I am at. I tried doing

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

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


            }

but java doesnt like that, can anyone point me in the right direction please?

4
  • Can you give an example of how you intend to call this method? (e.g. will you pass it the button instance or the x and y integers) Commented Apr 7, 2016 at 11:20
  • @khelwood Sorry i should've been more clear, I want to do this: button[x][y].flipIt(); x and y are part of my action listener in this case so they change depending on which button ive pressed in my GUI Commented Apr 7, 2016 at 11:23
  • If you want to add a member function on your button itself, then your button needs to be an instance of a class you write yourself, and that class should provide a function flipIt(). In that function, the button would be this, and the x,y would not be referenced at all. Commented Apr 7, 2016 at 11:28
  • Java doesn't like it? Like what? :) Commented Apr 7, 2016 at 12:10

2 Answers 2

1

If the event that you event listener picks up is a click on the button in question, you don’t need go through x and 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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

In your calling code you could do this :

flipIt(_buttons[x][y]);

and your function would look like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.