Reputation: 241
To make my program shorter I am using arrays and loops to accomplish a task but I am having problems with it. I am not sure whether I'm initializing the array wrong or accessing it wrong. I am initializing an array of 40 JCheckBoxes as such.
JCheckBox[] seatz={chk_a1,chk_a2,chk_a3,chk_a4,chk_a5,chk_a6,chk_a7,chk_a8,chk_a9,chk_a10,chk_b1,chk_b2...chk_d10};
Whenever the item state of a JCheckBox is changed the seatChecker()
method is called
public void seatChecker(JCheckBox chkbox) {
if(chkbox.isSelected()){
chkboxcount=chkboxcount+1;
} else {
chkboxcount=chkboxcount-1;
}
if(chkboxcount>=totalseats){
disableSeats();
} else {
enableSeats();
}
}
Here I am disableing the JCheckBoxes if the count reaches a certain limit, else enabling them. The code for the two methods is
public void disableSeats() {
for(int x = 0; x < 40 ; x++) {
if(seatz[x].isSelected()==false){
seatz[x].setEnabled(false);
}
}
}
public void enableSeats() {
for(int x = 0; x < 40 ; x++) {
seatz[x].setEnabled(true);
}
}
I am getting the error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at if(seatz[x].isSelected()==false)
and seatz[x].setEnabled(true)
What am I doing wrong over here?
Upvotes: 2
Views: 265
Reputation: 285430
You state:
I am getting the error
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
atif(seatz[x].isSelected()==false)
andseatz[x].setEnabled(true)
What am I doing wrong over here?
This can only occur if seatz[x] is null.
You appear to be declaring an array of reference type (JCheckBox here), but have not yet constructed valid non-null objects for each array item before using them. You must first fill your array with references to valid non-null objects before trying to use them. This is the same for any array of reference type.
Another way to look at is, when you create an array of objects it's like creating an egg carton. You can't use any eggs until you put some in the carton first. You can't use any objects in the array before you've initialized them, which is often done within a for loop.
i.e. you need to do this first:
for (int i = 0; i < myReferenceArray.length; i++) {
myReferenceArray[i] = new MyReference();
}
Before you can use any items in the array.
As an aside, on seeing this:
I am initializing an array of 40 JCheckBoxes as such.
I keep wondering if a JTable would better serve your needs.
Note that if you can't use a JTable, then this code:
JCheckBox[] seatz={chk_a1,chk_a2,chk_a3,chk_a4,chk_a5,chk_a6,chk_a7,chk_a8,chk_a9,chk_a10,chk_b1,chk_b2...chk_d10};
could easily be changed to:
JCheckBox[][] seats = new JCheckBox[4][10]; // magic numbers replaced by constants
for (int row = 0; row < seats.length; row++) {
for (int col = 0; col < seats[row].length; col++) {
seats[row][col] = new Seat();
seatPanel.add(seats[row][col]);
}
}
Upvotes: 5