Reputation: 789
In a for loop, I want to
here what I've got so far :
for(int i = 0 ;i < bts1.length ; i++){
bts1[i] = new JButton(""+i);
pan3.add(bts1[i]);
//The NullPointerException happens after this line .
bts[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
int j = 0 ;
screen.setText(screen.getText()+bts[j].getText());
j++;
}
});
}
My question is how to solve the NullPointerException ? note for the j I add it because when I tried to use the i , a compiler error occurs ,
Upvotes: 0
Views: 178
Reputation: 57381
Try the event source instead
screen.setText(screen.getText()+((JButton)ae.getSource()).getText());
Upvotes: 1
Reputation: 3608
You are using two different arrays of JButtons, bts
and bts1
.
bts1[i]
. bts[j]
.Have you initialized also bts[j]
somewhere? If not you will run into a NPE.
Upvotes: 1
Reputation: 5731
You initialized JButton
as bts1
and calling it as bts
. I think that caused the error.
Also,
Declare int i=0;
as global scope and for(i = 0 ;i < bts1.length ; i++)
then you can use i
instead of j
.
Or else use as following:
for(int i = 0 ;i < bts1.length ; i++){
bts1[i] = new JButton(""+i);
pan3.add(bts1[i]);
final int j=i;
bts1[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
screen.setText(screen.getText()+bts1[j].getText());
}
});
}
Upvotes: 1
Reputation: 3197
Beforr you add the button to Panels. You need add Listener for button first.
Have a try with the following code first.
//The NullPointerException happens after this line .
bts[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
int j = 0 ;
screen.setText(screen.getText()+bts[j].getText());
j++;
}
});
**pan3.add(bts1[i]);**
Upvotes: 0
Reputation: 21
try this:
for(int i = 0 ;i < bts1.length-1 ; i++){
//rest of your code
}
As the array of 10 elements has elements with indexes 0 through 9, not 0 through 10.
Upvotes: 0