What did I do wrong here?
Well I'm starting to study a bit on Swing and the JFrame, so please, if this looks ugly please cut me a bit of slack >.<
This is what I've got:
Code java:
package Core.Engine;
import javax.swing.*;
import java.awt.*;
@SuppressWarnings("serial")
public class Engine extends JFrame {
static int i;
static JPanel PRIME;
public Engine(){
JButton[] BUTTON = new JButton[9];
PRIME = new JPanel(new GridLayout(5,6));
String b[] = {"1", "2","4", "3", "5",
"6", "7", "8", "9", "0"};
for(i = 0; i < BUTTON.length; i++){
BUTTON[i] = new JButton(b[i]);
BUTTON[i].setSize(30,30);
};
PRIME.add(BUTTON[i]);
}
public static void main(String args[]){
Engine frame = new Engine();
frame.add(PRIME);
frame.pack();
frame.setVisible(true);
}
}
I get an ArrayIndexOutOfBoundsException on line 27 and 30 which would be in the Main argument...
Here's the exact error:
Code :
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at Core.Engine.Engine.<init>(Engine.java:27)
at Core.Engine.Engine.main(Engine.java:30)
Could anyone tell me where I went wrong? The array has 9 elements. I set 9 chars... How did it go out of bounds?
Foot Note:
If you have any ideas on how I could improve this code please don't be afraid to mention it!
Re: What did I do wrong here?
I am guessing line 27 is this one:
You get an ArrayIndexOutOfBoundsException when you try and access an array with a negative index, or one >= the length of the array. Remember that array indices start at zero and go to length-1. You can test whether you are doing this here by inserting a System.out.println():
Code :
System.out.println("BUTTON has length " + BUTTON.length);
System.out.println("About to access BUTTON[i] where i=" + i);
PRIME.add(BUTTON[i]);
-----
It would be good if you followed Java coding conventions and used lowercase letters for packages and variables. This adds readability.
In terms of the logic of your code it you should remove any use of "static" other than for main(). And declare variables close to where you use them. In this case the int i might better be declared as part of the for loop rather than as a static class variable. (Of course both of these things may involve addressing problems to which the compiler alerts you. But, often, problems are made worse, not better, if the compiler is made to shut up by making variables static and/or giving them excessive scope.)