So pretty much I'm making an array of obvjects called Spots
which symbolise the different faces of a dice.
It takes user input (manually set to three for this example), and then creates that make Spots
and rolls a random number from 1 to 6.
However when I go to use the rollAgain()
method on the aleady created array of Spots
I get a null pointer even though I am using the same variable length in both for loops (the one that creates and one that rolls the spots).
My code
Global Variables
private Spots[] spots;
private int x = 3;
Contructor
public Director(JFrame window, String args[]) {
JMenuBar menus = new JMenuBar();
window.setJMenuBar(menus);
menus.add(makeFileMenu());
window.getContentPane().add(makePanel(), BorderLayout.WEST);
window.getContentPane().add(makeSpots(x), BorderLayout.CENTER);
rollAgain();
}
rollAgain() method
public void rollAgain() {
int v = 1 + (int) (Math.random() * 6);
for (int i = 0; i < x; i++) {
spots[i].setValue(v);
}
}
makeSpots() method
private JComponent makeSpots(int x) {
JPanel p = new JPanel();
p.setBorder(BorderFactory.createTitledBorder("Dice"));
Spots[] spots = new Spots[x];
for (int i = 0; i < x; i++) {
spots[i] = new Spots(200, 200);
spots[i].setBorder(BorderFactory.createEtchedBorder());
p.add(spots[i]);
}
return p;
}