1

Hello all I'm to return a particular JButton to then later setText on it. Here is a snippet of the code:

JButton[][] tiles = new JButton[4][4];
for (int i=0; i<4; i++) {
    for (int j=0; j<4; j++){
        tiles[i][j] = new JButton();
    }   
}

I would basically like to return this JButton using an accessor method.

public JButton getJButton(int i, int j) {   
    return JButton[i][j];   
}

This is my current idea however that is currently returning null, any ideas on a solution?

Many thanks.

warunapww
  • 966
  • 4
  • 18
  • 38
Danny
  • 105
  • 1
  • 1
  • 9
  • Change it to: return tiles[i][j]; – Buddy May 07 '15 at 04:46
  • thanks, my current issue is that I cannot use this method outside the class as it returns this: Cannot make a static reference to the non-static method getJButton(int, int) from the type TileBoard, however declaring it static causes it to return null. any ideas? – Danny May 07 '15 at 04:51

2 Answers2

1

private JButton[][] tiles; should be a field variable

In you constructor do tiles = new JButton[4][4]; for...

And then change you get method to:

public JButton getJButton(int i, int j) {   
    return tiles[i][j];   
}
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
1

declare

JButton[][] tiles = null;

public void init() {
    tiles = new JButton[4][4];
    for (int i=0; i<4; i++) {
        for (int j=0; j<4; j++) {
            tiles[i][j] = new JButton();
        }   
    }
}

public JButton getJButton(int i, int j) {   
    return tiles[i][j];
}
ELITE
  • 5,815
  • 3
  • 19
  • 29
  • Thank you, a new issue has arisen however: if I try to call this method from another class the error: Cannot make a static reference to the non-static method getJButton(int, int) from the type TileBoard. And the only solution offered is to make the get method a static, which makes this solution not work, any ideas? – Danny May 07 '15 at 04:39
  • declare JButton[][] tiles = null to static JButton[][] tiles = null; it solve your problem. – ELITE May 07 '15 at 04:43
  • This now just returns null, not the correct JButton. – Danny May 07 '15 at 04:46
  • Make sure that you have initialised the JButton array before calling the getter.. also check that JButton[][] tiles is not declared local variable in init() method.. – ELITE May 07 '15 at 04:50